Overview of Spring Web
SpringMVC running process
The MVC architecture is the back-end architecture, which is the name of the jsp era. The concept of mvc does not exist in the era of front-end and back-end separation.
The controller class receives the request
Specify the request method: @RequestMapping(value = "/login", method = RequestMethod.GET)
1. Define formal parameter reception in the parameter list
Request method: corresponding to the method in @RequestMapping
@RestController
@RequestMapping("/students")
public class StudentController {
@RequestMapping(value="/create",method=RequestMethod.POST)
public String create(
@RequestParam("name") String name,
@RequestParam("age") Integer age,
@RequestHeader("User-Agent") String userAgent){
return null;
}
}
Note: The key in the request is consistent with the name of the formal parameter and received directly. If it is inconsistent, it needs to be received through the annotation tag
2. Use the object directly to receive
Chinese garbled
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Return result in controller ( Ajax returns JSON )
Since @RequestMapping contains the @RequestBody tag, the result returned by the method is in json format by default, and when writing the json string into the response body and returning an object, a third-party component that converts to json must be added
<!--转json需要的组件-->
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.6</version>
</dependency>
cross domain processing
<dependency>
<groupId>com.thetransactioncompany</groupId>
<artifactId>cors-filter</artifactId>
<version>2.5</version>
</dependency>
2. Configure in web.xml
<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
interceptor
2. Register interceptor
<!--配置拦截器-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/><!--配置那些请求可以进入到拦截器-->
<mvc:exclude-mapping path="/loginCtl/login"/><!--配置那些请求不可以进入拦截器-->
<bean class="com.ffyc.ssm.common.TokenInterceptor"></bean><!--配置实现类的拦截器-->
</mvc:interceptor>
</mvc:interceptors>