日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【笔记】spring的注解回顾,springboot-restful项目结构介绍 springboot-freemarker ⼯程配置详解

發布時間:2024/9/30 编程问答 29 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【笔记】spring的注解回顾,springboot-restful项目结构介绍 springboot-freemarker ⼯程配置详解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

注解

學Spring boot有一陣子了,總結一下它的注解。
@Controller :修飾class,?來創建處理http請求的對象
@RestController :Spring4之后加?的注解,原來在 @Controller 中返回json需要 @ResponseBody 來配合,如果直接? @RestController 替代 @Controller 就不需要再配置 @ResponseBody ,默認返回json格式。
@RequestMapping :配置url映射

例子:
實現對User對象的操作接?

@RestController @RequestMapping(value="/users") // 通過這?配置使下?的映射都在/users下 public class UserController { // 創建線程安全的Map static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>()); @RequestMapping(value="/", method=RequestMethod.GET) public List<User> getUserList() { // 處理"/users/"的GET請求,?來獲取?戶列表 // 還可以通過@RequestParam從??中傳遞參數來進?查詢條件或者翻?信息的傳遞 List<User> r = new ArrayList<User>(users.values()); return r; } @RequestMapping(value="/", method=RequestMethod.POST) public String postUser(@ModelAttribute User user) { // 處理"/users/"的POST請求,?來創建User // 除了@ModelAttribute綁定參數之外,還可以通過@RequestParam從??中傳遞參數 users.put(user.getId(), user); return "success"; } @RequestMapping(value="/{id}", method=RequestMethod.GET) public User getUser(@PathVariable Long id) { // 處理"/users/{id}"的GET請求,?來獲取url中id值的User信息 // url中的id可通過@PathVariable綁定到函數的參數中 return users.get(id); } @RequestMapping(value="/{id}", method=RequestMethod.PUT) public String putUser(@PathVariable Long id, @ModelAttribute User user) { // 處理"/users/{id}"的PUT請求,?來更新User信息 User u = users.get(id); u.setName(user.getName()); u.setAge(user.getAge()); users.put(id, u); return "success"; } @RequestMapping(value="/{id}", method=RequestMethod.DELETE) public String deleteUser(@PathVariable Long id) { // 處理"/users/{id}"的DELETE請求,?來刪除User

進行驗證,使用MockMvc
MockMvc是由spring-test包提供,實現了對Http請求的模擬,能夠直接使用網絡的形式,轉換到Controller的調用,使得測試速度快、不依賴網絡環境。同時提供了一套驗證的工具,結果的驗證十分方便。

接口MockMvcBuilder,提供一個唯一的build方法,用來構造MockMvc。主要有兩個實現:StandaloneMockMvcBuilder和DefaultMockMvcBuilder,分別對應兩種測試方式,即獨立安裝和集成Web環境測試(并不會集成真正的web環境,而是通過相應的Mock API進行模擬測試,無須啟動服務器)。MockMvcBuilders提供了對應的創建方法standaloneSetup方法和webAppContextSetup方法,在使用時直接調用即可。

@RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = MockServletContext.class) @WebAppConfiguration public class ApplicationTests { private MockMvc mvc; @Before public void setUp() throws Exception { mvc = MockMvcBuilders.standaloneSetup(new UserController()).build(); } @Test public void testUserController() throws Exception { // 測試UserController RequestBuilder request = null; // 1、get查?下user列表,應該為空 request = get("/users/"); mvc.perform(request) .andExpect(status().isOk()) .andExpect(content().string(equalTo("[]"))); // 2、post提交?個user request = post("/users/") .param("id", "1") .param("name", "測試?師") .param("age", "20"); mvc.perform(request) .andExpect(content().string(equalTo("success"))); // 3、get獲取user列表,應該有剛才插?的數據 request = get("/users/"); mvc.perform(request) .andExpect(status().isOk()) .andExpect(content().string(equalTo("[{\"id\":1,\"name\":\"測試?師\",\"age \":20}]"))); // 4、put修改id為1的user request = put("/users/1") .param("name", "測試終極?師") .param("age", "30"); mvc.perform(request) .andExpect(content().string(equalTo("success"))); // 5、get?個id為1的user request = get("/users/1"); mvc.perform(request) .andExpect(content().string(equalTo("{\"id\":1,\"name\":\"測試終極?師\",\"a ge\":30}"))); // 6、del刪除id為1的user request = delete("/users/1"); mvc.perform(request) .andExpect(content().string(equalTo("success"))); // 7、get查?下user列表,應該為空 request = get("/users/"); mvc.perform(request) .andExpect(status().isOk()) .andExpect(content().string(equalTo("[]"))); } }

springboot-restful ?程項?結構介紹

springboot-restful ?程項?結構如下圖所示:
org.spring.springboot.controller - Controller 層

org.spring.springboot.dao - 數據操作層 DAO
org.spring.springboot.domain - 實體類
org.spring.springboot.service - 業務邏輯層
Application - 應?啟動類
application.properties - 應?配置?件,應?啟動會?動讀取配置

什么是 REST?
REST 是屬于 WEB ?身的?種架構?格,是在 HTTP 1.1 規范下實現的。Representational State Transfer 全稱翻譯為表現層狀態轉化。Resource:資源。?如 newsfeed;Representational:表現形式,?如?JSON,富?本等;State Transfer:狀態變化。通過HTTP 動作實現。
理解 REST ,要明?五個關鍵要素:
資源(Resource)
資源的表述(Representation)
狀態轉移(State Transfer)
統?接?(Uniform Interface)
超?本驅動(Hypertext Driven)
6 個主要特性:
?向資源(Resource Oriented)
可尋址(Addressability)
連通性(Connectedness)
?狀態(Statelessness)
統?接?(Uniform Interface)
超?本驅動(Hypertext Driven)
CityRestController.java 城市 Controller 實現 Restful HTTP 服務:

public class CityRestController { @Autowired private CityService cityService; @RequestMapping(value = "/api/city/{id}", method = RequestMethod.GET) public City findOneCity(@PathVariable("id") Long id) { return cityService.findCityById(id); } @RequestMapping(value = "/api/city", method = RequestMethod.GET) public List<City> findAllCity() { return cityService.findAllCity(); } @RequestMapping(value = "/api/city", method = RequestMethod.POST) public void createCity(@RequestBody City city) { cityService.saveCity(city); } @RequestMapping(value = "/api/city", method = RequestMethod.PUT) public void modifyCity(@RequestBody City city) { cityService.updateCity(city); } @RequestMapping(value = "/api/city/{id}", method = RequestMethod.DELETE) public void modifyCity(@PathVariable("id") Long id) { cityService.deleteCity(id); } }

@RequestMapping 處理請求地址映射。
method - 指定請求的?法類型:POST/GET/DELETE/PUT 等
value - 指定實際的請求地址
consumes - 指定處理請求的提交內容類型,例如 Content-Type 頭部設置application/json,text/html
produces - 指定返回的內容類型
Springboot 實現 Restful 服務,基于 HTTP / JSON 傳輸,適?于前后端分離

通過 @ApiOperation 注解來給API增加說明、通
過 @ApiImplicitParams 、 @ApiImplicitParam 注解來給參數增加說明。

@Configuration @EnableSwagger2 public class Swagger2 { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.basePackage("com.didispace.web")) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("Spring Boot中使?Swagger2構建RESTful APIs") .description("Spring Boot?章:http://blog.didispace.com/") .termsOfServiceUrl("http://blog.didispace.com/") .contact("程序猿D") .version("1.0") .build(); } }

如上代碼所示,通過 @Configuration 注解,讓Spring來加載該類配置。再通過 @EnableSwagger2 注解
來啟?Swagger2。
再通過 createRestApi 函數創建 Docket 的Bean之后, apiInfo() ?來創建該Api的基本信息(這些
基本信息會展現在?檔??中)。 select() 函數返回?個 ApiSelectorBuilder 實例?來控制哪些接
?暴露給Swagger來展現,本例采?指定掃描的包路徑來定義,Swagger會掃描該包下所有Controller
定義的API,并產??檔內容(除了被 @ApiIgnore 指定的請求)。

@ApiOperation 注解來給API增加說明、通
過 @ApiImplicitParams 、 @ApiImplicitParam 注解來給參數增加說明。

springboot-freemarker ?程配置詳解

pom:

<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSc hema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd /maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>springboot</groupId> <artifactId>springboot-freemarker</artifactId> <version>0.0.1-SNAPSHOT</version> <name>springboot-freemarker :: Spring Boot 集成 FreeMarker 案例</name> <!-- Spring Boot 啟動?依賴 --> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.1.RELEASE</version> </parent> <properties> <mybatis-spring-boot>1.2.0</mybatis-spring-boot> <mysql-connector>5.1.39</mysql-connector> </properties> <dependencies> <!-- Spring Boot Freemarker 依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency> <!-- Spring Boot Web 依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!-- Spring Boot Test 依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis-spring-boot}</version> </dependency> <!-- MySQL 連接驅動依賴 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql-connector}</version> </dependency> <!-- Junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> </dependencies> </project>

然后在 application.properties 中加? FreeMarker 相關的配置:

Freemarker 配置

#?件配置路徑
spring.freemarker.template-loader-path=classpath:/web/
spring.freemarker.cache=false
spring.freemarker.charset=UTF-8
spring.freemarker.check-template-location=true
spring.freemarker.content-type=text/html
spring.freemarker.expose-request-attributes=true
spring.freemarker.expose-session-attributes=true
spring.freemarker.request-context-attribute=request
spring.freemarker.suffix=.ftl
使用freemarker時非前后端分離,此時的Controller層:

3.展示層 Controller 詳解 /** * 城市 Controller 實現 Restful HTTP 服務 * <p> * Created by bysocket on 07/02/2017. */ @Controller public class CityController { @Autowired private CityService cityService; @RequestMapping(value = "/api/city/{id}", method = RequestMethod.GET) public String findOneCity(Model model, @PathVariable("id") Long id) { model.addAttribute("city", cityService.findCityById(id)); return "city"; } @RequestMapping(value = "/api/city", method = RequestMethod.GET) public String findAllCity(Model model) { List<City> cityList = cityService.findAllCity(); model.addAttribute("cityList",cityList); return "cityList"; } }

a.這?不是? HTTP + JSON 模式,使?了 @Controller ?不是先前的 @RestController
b.?法返回值是 String 類型,和 application.properties 配置的 Freemarker ?件配置路徑下的各個 *.ftl?件名?致。這樣才會準確地把數據渲染到 ftl ?件??進?展示。
c.? Model 類,向 Model 加?數據,并指定在該數據在 Freemarker 取值指定的名稱。

總結

以上是生活随笔為你收集整理的【笔记】spring的注解回顾,springboot-restful项目结构介绍 springboot-freemarker ⼯程配置详解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。