使用SpringBoot開發帶返回cookies資訊的get介面
阿新 • • 發佈:2018-11-14
在maven包裡配置SpringBoot
新建maven工程,在pom.xml檔案裡新增SpringBoot的引用配置,程式碼如下:
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.2.RELEASE</version> <relativePath /> </parent> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
配置SpringBoot執行時的埠號
一、在resources包下新建application.properties檔案(file檔案),指定執行的埠,程式碼如下
server.port=${port:8081}
開發帶返回cookies資訊的get介面
一、在src/main/java包目錄下新建Application類(啟動類),程式碼如下
@SpringBootApplication //@ComponentScan表示掃描哪個包下的類 @ComponentScan("com.course.server") public class Application { public static void main(String[] args) { SpringApplication.run(Application.class,args); } }
如果啟動報錯,嘗試把@SpringBootApplication替換成@SpringBootApplication(exclude={DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class}),然後重新啟動
二、在java包下新增com.course.server包,在server包下新增MyGetMethod類,程式碼如下
//@RestController表示我是需要被掃描的類 @RestController public class MyGetMethod { //設定訪問路徑和請求方法 @RequestMapping(value = "/getCookies",method = RequestMethod.GET) @ApiOperation(value = "通過這個方法可以獲取到cookies",httpMethod = "Get") //HttpServerletRequest 裝請求資訊的類 //HttpServerletResponse 裝響應資訊的類 public String getCookies(HttpServletResponse response){ Cookie cookie = new Cookie("login","true"); response.addCookie(cookie); return "恭喜你獲得cookies成功2"; } }
執行Application啟動類,然後在瀏覽器輸入http://127.0.0.1:8081/getCookies
訪問結果