[关闭]
@File 2019-12-09T01:25:52.000000Z 字数 9774 阅读 154

spring-mvc 配置

java


pom.xml 依赖包

  1. <!-- spring-mvc集成包 -->
  2. <dependency>
  3. <groupId>org.springframework</groupId>
  4. <artifactId>spring-webmvc</artifactId>
  5. <version>5.1.9.RELEASE</version>
  6. </dependency>
  7. <!-- fastjson包 -->
  8. <dependency>
  9. <groupId>com.alibaba</groupId>
  10. <artifactId>fastjson</artifactId>
  11. <version>1.2.58</version>
  12. </dependency>
  13. <!-- 跨域请求 -->
  14. <dependency>
  15. <groupId>com.thetransactioncompany</groupId>
  16. <artifactId>cors-filter</artifactId>
  17. <version>1.3.2</version>
  18. </dependency>

xml 配置

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
  6. <!--开启springmvc 的注解-->
  7. <context:component-scan base-package="com.lidaye.ssm"/>
  8. <!-- 设置配置方案 -->
  9. <mvc:annotation-driven>
  10. <!-- 消息转化器 -->
  11. <mvc:message-converters register-defaults="false">
  12. <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
  13. <!-- 加入支持的媒体类型:返回contentType -->
  14. <property name="supportedMediaTypes">
  15. <list>
  16. <!-- 这里顺序不能反,一定先写text/html,不然IE下会出现下载提示 -->
  17. <value>text/html;charset=UTF-8</value>
  18. <value>application/json;charset=UTF-8</value>
  19. </list>
  20. </property>
  21. <property name="fastJsonConfig">
  22. <bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
  23. <property name="features">
  24. <list>
  25. <value>AllowArbitraryCommas</value>
  26. <value>AllowUnQuotedFieldNames</value>
  27. <value>DisableCircularReferenceDetect</value>
  28. </list>
  29. </property>
  30. <!--配置特定的日期格式-->
  31. <property name="dateFormat" value="yyyy-MM-dd HH:mm:ss"/>
  32. </bean>
  33. </property>
  34. </bean>
  35. </mvc:message-converters>
  36. </mvc:annotation-driven>
  37. </beans>
  1. <bean id="mappingJacksonHttpMessageConverter"class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
  2. <property name="supportedMediaTypes">
  3. <list>
  4. <value>text/html;charset=UTF-8</value>
  5. </list>
  6. </property>
  7. </bean>
  1. <mvc:default-servlet-handler/>

web.xml注册

  1. <!DOCTYPE web-app PUBLIC
  2. "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
  3. "http://java.sun.com/dtd/web-app_2_3.dtd" >
  4. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
  5. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  6. xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
  7. http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  8. version="3.1"
  9. metadata-complete="true">
  10. <display-name>Archetype Created Web Application</display-name>
  11. <!-- 网上解释:自动装配ApplicationContext.xml的配置信息(暂时不理解) -->
  12. <listener>
  13. <listener-class>org.springframework.web.context.ContextLoaderListener
  14. </listener-class>
  15. </listener>
  16. <!-- 加载spring 相关配置文件-->
  17. <context-param>
  18. <param-name>contextConfigLocation</param-name>
  19. <param-value>classpath:spring-*</param-value>
  20. </context-param>
  21. <!-- 配置 DispatcherServlet -->
  22. <servlet>
  23. <servlet-name>dispatcherServlet</servlet-name>
  24. <servlet-class>org.springframework.web.servlet.DispatcherServlet
  25. </servlet-class>
  26. <!-- 配置初始参数 -->
  27. <init-param>
  28. <param-name>contextConfigLocation</param-name>
  29. <!-- 绑定配置文件 -->
  30. <param-value>classpath:spring-mvc.xml</param-value>
  31. </init-param>
  32. <!-- 启动顺序 值越小优先级越高 -->
  33. <load-on-startup>1</load-on-startup>
  34. </servlet>
  35. <!-- 配置映射 -->
  36. <servlet-mapping>
  37. <servlet-name>dispatcherServlet</servlet-name>
  38. <url-pattern>/</url-pattern>
  39. </servlet-mapping>
  40. <!-- 编码过滤 -->
  41. <filter>
  42. <filter-name>encoding</filter-name>
  43. <filter-class>org.springframework.web.filter.CharacterEncodingFilter
  44. </filter-class>
  45. <!-- 编码 -->
  46. <init-param>
  47. <param-name>encoding</param-name>
  48. <param-value>utf-8</param-value>
  49. </init-param>
  50. <!-- 请求 -->
  51. <init-param>
  52. <param-name>forceRequestEncoding</param-name>
  53. <param-value>true</param-value>
  54. </init-param>
  55. </filter>
  56. <filter-mapping>
  57. <filter-name>encoding</filter-name>
  58. <url-pattern>/*</url-pattern>
  59. </filter-mapping>
  60. <!-- 配置首页 -->
  61. <welcome-file-list>
  62. <welcome-file>index.jsp</welcome-file>
  63. </welcome-file-list>
  64. </web-app>
  1. <filter>
  2. <filter-name>CORS</filter-name>
  3. <filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
  4. <init-param>
  5. <param-name>cors.allowOrigin</param-name>
  6. <param-value>*</param-value>
  7. </init-param>
  8. <init-param>
  9. <param-name>cors.supportedMethods</param-name>
  10. <param-value>GET, POST, HEAD, PUT, DELETE</param-value>
  11. </init-param>
  12. <init-param>
  13. <param-name>cors.supportedHeaders</param-name>
  14. <param-value>Accept, Origin, X-Requested-With, Content-Type, Last-Modified</param-value>
  15. </init-param>
  16. <init-param>
  17. <param-name>cors.exposedHeaders</param-name>
  18. <param-value>Set-Cookie</param-value>
  19. </init-param>
  20. <init-param>
  21. <param-name>cors.supportsCredentials</param-name>
  22. <param-value>true</param-value>
  23. </init-param>
  24. </filter>
  25. <filter-mapping>
  26. <filter-name>CORS</filter-name>
  27. <url-pattern>/*</url-pattern>
  28. </filter-mapping>

注解使用

@RestController 注册数据接口类

  1. // 方法一
  2. @RestController
  3. public class HelloController{}
  4. // 方法二
  5. @Controller
  6. @ResponseBody
  7. public class HelloController{}

@RequestMapping 限制请求信息

name: 指定映射器名称
value: 指定映射地址
method: 请求类型
params: 请求参数
headers: 头部参数
consumes: 接收的内容格式:Content-type
produces: 响应的内容格式:Content-type

  1. @RestController
  2. public class HelloController {
  3. // 定义请求信息
  4. @RequestMapping("/lidaye")
  5. public String lidaye(){
  6. return "hello";
  7. }
  8. }

@GetMapping get 请求(简化@RequestMapping)

@PostMapping post 请求(简化@RequestMapping)

@PutMapping put 请求(简化@RequestMapping)

@DeleteMapping delete请求(简化@RequestMapping)

@ModelAttribute 所有请求接收前执行的方法

value: 定义一个参数,值为返回值
binding: 数据绑定,默认true

  1. // 定义一个预执行方法,并声明一个name参数
  2. @ModelAttribute("name")
  3. public String lidaye(){
  4. return "李大爷";
  5. }
  6. // 接收请求方法通过 @ModelAttribute 获取name参数
  7. @GetMapping
  8. public String getMethod(@ModelAttribute("name") String name){}

@PathVariable 动态路由

  1. @RestController
  2. public class HelloController {
  3. // 定义请求信息
  4. @RequestMapping("/hellow/{type}/{page}")
  5. public String hello(@PathVariable String type,@PathVariable int page){
  6. return "hello";
  7. }
  8. }

@RequestParam 声明参数

  1. @RestController
  2. public class HelloController {
  3. @GetMapping("/lidaye")
  4. public String hello(@RequestParam("user_name") String name){
  5. return name;
  6. }
  7. }

@SessionAttribute 获取session中的数据

value: session中的key
required: 参数是否必须存在,默认true(必须存在)

@CookieValue 获取cookie中的数据

value: cookie中的key
required: 参数是否必须存在,默认true(必须存在)
defaultValue: 默认值

以对象接收参数

  1. @RestController
  2. public class HelloController {
  3. @GetMapping("/lidaye")
  4. public String hello(Lidaye ldy){
  5. return ldy;
  6. }
  7. }

@ResponseBody 方法/类声明为响应接口

  1. // 不使用 @RestController 注册
  2. @Controller
  3. public class HelloController {
  4. // 声明为响应接口
  5. @ResponseBody
  6. @GetMapping("/lidaye")
  7. public String hello(){
  8. return "hello";
  9. }
  10. }

@RequestBody 获取完整请求体的内容

  1. @RestController
  2. public class HelloController {
  3. @PostMapping("/lidaye")
  4. // required 默认为true 必须有内容
  5. public String hello(@RequestBody(required = false) String body){
  6. return body;
  7. }
  8. }

@ModelAndView

@RestControllerAdvice 统一响应处理

通过aop统一响应处理案例

value:
basePackageClasses:
assignableTypes:
annotations:

  1. @RestControllerAdvice
  2. public class ControllerResult implements ResponseBodyAdvice {
  3. @Override
  4. public boolean supports(MethodParameter methodParameter, Class aClass) {
  5. // methodParameter: 方法对象
  6. // aClass: http信息转换器类(默认jackson)
  7. // 返回 true 才会执行 beforeBodyWrite()
  8. return !methodParameter.getMethod().getReturnType().equals(Void.TYPE);
  9. }
  10. @Override
  11. public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
  12. // o: 返回值
  13. // methodParameter: 方法对象
  14. // mediaType: mediaType 媒体类型(json等...)
  15. // aClass: http信息转换器类(默认jackson)
  16. // serverHttpRequest: 请求对象
  17. // serverHttpResponse: 响应对象
  18. // 最终响应内容
  19. return null;
  20. }
  21. }

@ExceptionHandler 全局异常捕获

value: 错误类(数组)

  1. @ExceptionHandler(Exception.class)
  2. public Result baseException(){
  3. return
  4. }

@DateTimeFormat 修改日期格式

  1. @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
  2. private Date date;

fastjson

@JSONField 属性序列化设置

ordinal: 序列化的顺序
name: json中的参数名
format: 日期格式
serialize: 是否要序列化,默认true
deserialize: 是否解析,默认true
serialzeFeatures:
parseFeatures:
label:
jsonDirect: 默认false
serializeUsing:
deserializeUsing:
alternateNames:
unwrapped: 默认false

  1. @JSONField(ordinal = 2) // 修改顺序
  2. @JSONField(name = "user_id") // 修改序列化后的键名
  3. private Integer id;
  4. @JSONField(ordinal = 1)
  5. private String name;
  6. /**
  7. * 结果:{"name":"xxx","user_id":1}
  8. */

jackson

@JsonProperty熟悉序列化设置

value: json中的参数名
required:
index:
defaultValue:
access:

  1. @JsonProperty("isShow") // 设置序列化参数名
  2. private boolean show; // 不要把 boolean 类型字段名命名为 is 前缀

重定向和转发

1. redirect: 重定向

  1. @Controller
  2. public class ModelViewController {
  3. @RequestMapping("/redirect")
  4. public String redirect() {
  5. // 站内重定向
  6. return "redirect:/model";
  7. // 站内重定向带参数
  8. // return "redirect:/user/change/?uid=1"
  9. // 站外重定向
  10. // return "redirect:https://www.baidu.com";
  11. // 站外重定向带参数 后面用户名
  12. // return "redirect:https://api.github.com/users/zhangwei725"
  13. // 站外重定向带参数2
  14. // return "https://api.github.com/users/zhangwei725/repos?page=1&per_page=10"
  15. }
  16. }

2. forward: 转发

  1. @Controller
  2. public class ModelViewController {
  3. @RequestMapping("/forward")
  4. public String testForward(Model model) {
  5. model.addAttribute("key", "转发");
  6. return "forward:index";
  7. }
  8. }

过滤器

HandlerInterceptor 接口

xml配置

  1. <mvc:interceptors >
  2. <mvc:interceptor>
  3. <interceptor下面定义的mappingexclude-mapping都是可以有多个的>
  4. <!-- /user/* -->
  5. <mvc:mapping path="/admin/**" />
  6. <mvc:exclude-mapping path="/account/login" /><!-- 不拦截 -->
  7. <bean class="com.vip.mvc.interceptor.LoginInterceptor"></bean>
  8. </mvc:interceptor>
  9. </mvc:interceptors>
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注