SSM框架新增RESTAPI應用
阿新 • • 發佈:2019-01-26
SSM框架搭建看這篇http://blog.csdn.net/zhshulin/article/details/37956105
當需要把控制類升級為RESTController時,在spring-mvc.xml只需新增一句<mvc:annotation-driven />
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd"> <!-- 自動掃描該包,使SpringMVC認為包下用了@controller註解的類是控制器 --> <context:component-scan base-package="com.luoka.weixin1545.controller" /> <!-- 添加註解驅動 enable-matrix-variables="true" --> <mvc:annotation-driven /> <!--避免IE執行AJAX時,返回JSON出現下載檔案 com.luoka.weixin1545.controller --> <bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> </bean> <!-- 啟動SpringMVC的註解功能,完成請求和註解POJO的對映 --> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="mappingJacksonHttpMessageConverter" /> <!-- JSON轉換器 --> </list> </property> </bean> <!-- 定義跳轉的檔案的前後綴 ,檢視模式配置--> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 這裡的配置我的理解是自動給後面action的方法return的字串加上字首和字尾,變成一個 可用的url地址 --> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> </bean> <!-- 配置檔案上傳,如果沒有使用檔案上傳可以不用配置,當然如果不配,那麼配置檔案中也不必引入上傳元件包 --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 預設編碼 --> <property name="defaultEncoding" value="utf-8" /> <!-- 檔案大小最大值 --> <property name="maxUploadSize" value="10485760000" /> <!-- 記憶體中的最大值 --> <property name="maxInMemorySize" value="40960" /> </bean> </beans>
java原來控制類
@Controller @RequestMapping("user") public class userController { @Resource private IUserService userService; @RequestMapping("/showUser") public String toIndex(HttpServletRequest request,Model model){ int userId = Integer.parseInt(request.getParameter("id")); User user = this.userService.getUserById(userId); model.addAttribute("user", user); return "showUser"; } }
控制類升級RESTAPI後
@RestController @RequestMapping("/user") public class userController { @Resource private IUserService userService; @RequestMapping("/{id}") public User GETUSER(@PathVariable Integer id){ User user = this.userService.getUserById(id); return user; } }