SpringMVC理解

SpringMVC基础

MVC:Model+View+Controller(数据模型+视图+控制器);
三层架构:Presentation tier+Application tier+Data tier(展现层+应用层+控制层)
MVC只存在三层架构的展现层,M是数据模型,包含数据的对象。用来与V进行数据交互、传值;V是指视图界面;C是指控制器。
在SpringMVC里实现webApplicationIntializer接口便可实现等同于web.xml的配置。

SpringMVC的常用注解:

  1. @Controller
    Dispatcher Servlet会自动扫面注解了此注解的类,并将web请求映射到注解了@RequestMapping的方法上。
  2. @RequestMapping
    该注解是用来映射web请求(访问路径和参数)、处理类和方法的。@RequestMapping支持Servlet的request和response作为参数,也支持对request和response的媒体类型进行配置。
  3. @ResponseBody
    @ResponseBody支持将返回值放在response体内,而不是返回一个页面 。
  4. @RequestBody
    @RequestBody允许request的参数在request体内,而不是直接链接在地址后面。
  5. @PathVariable
    @PathVariable用来接受路径参数。
  6. @RestController
    @RestController注解组合了@Controller和@ResponseBody。

例如:

@RequestMapping(value={"/user/{str}","/admin/{str}"},method = RequestMethod.POST,consumes="application/json", produces="application/json;charset=utf-8")
public @ResponseBody String demo(@PathVariable String str,HttpServletRequest request,HttpServletResponse response){ 
       return "";
 }

方法仅处理request Content-Type为“application/json”类型的请求,且编码为utf-8(客户端应该以utf-8解码),produces标识==>处理request请求中Accept头中包含了"application/json"的请求,同时consumes暗示了返回的内容类型为application/json;

MediaType
  MediaType,即是Internet Media Type,互联网媒体类型;也叫做MIME类型,在Http协议消息头中,使用Content-Type来表示具体请求中的媒体类型信息。

常见的媒体格式类型如下:

  • text/html : HTML格式
  • text/plain : 纯文本格式
  • text/xml : XML格式
  • image/gif : gif图片格式
  • image/jpeg : jpg图片格式
  • image/png : png格式

以application开头的媒体格式类型:

  • application/xhtml+xml : XHTML格式
  • application/xml : XML数据格式
  • application/atom+xml : Atom XML聚合格式
  • application/json : JSON数据格式
  • application/pdf : pdf格式
  • application/msword : Word文档格式
  • application/octet-stream : 二进制流数据(如常见的文件下载)
  • application/x-www-form-urlencoded : 中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)

另外一种媒体类型格式是上传文件使用的:

  • multipart/form-data : 需要在表单中进行文件上传时,就需要使用该格式

首先查看@RequestMapping注解

@Target({ElementType.METHOD, ElementType.TYPE})  
@Retention(RetentionPolicy.RUNTIME)  
@Documented  
@Mapping  
public @interface RequestMapping {  
      String[] value() default {};  
      RequestMethod[] method() default {};  
      String[] params() default {};  
      String[] headers() default {};  
      String[] consumes() default {};  
      String[] produces() default {};  
} 

value: 指定请求的实际地址, 比如 /action/info之类。
method: 指定请求的method类型, GET、POST、PUT、DELETE等
consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;
produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回
params: 指定request中必须包含某些参数值是,才让该方法处理
headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求
其中,consumes, produces使用content-type信息进行过滤信息;headers中可以使用content-type进行过滤和判断。

当你有如下Accept头,将遵守如下规则进行应用:
①Accept:text/html,application/xml,application/json
将按照如下顺序进行produces的匹配 ①text/html ②application/xml ③application/json
②Accept:application/xml;q=0.5,application/json;q=0.9,text/html
将按照如下顺序进行produces的匹配 ①text/html ②application/json ③application/xml
参数为媒体类型的质量因子,越大则优先权越高(从0到1)
③Accept:/,text/,text/html
将按照如下顺序进行produces的匹配 ①text/html ②text/
③*/*

Request部分

Header解释示例
Accept指定客户端能够接收的内容类型Accept: text/plain, text/html
Accept-Charset浏览器可以接受的字符编码集。Accept-Charset: iso-8859-5
Accept-Encoding指定浏览器可以支持的web服务器返回内容压缩编码类型。Accept-Encoding: compress, gzip
Accept-Language浏览器可接受的语言Accept-Language: en,zh
Accept-Ranges可以请求网页实体的一个或者多个子范围字段Accept-Ranges: bytes
AuthorizationHTTP授权的授权证书Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Cache-Control指定请求和响应遵循的缓存机制Cache-Control: no-cache
Connection表示是否需要持久连接。(HTTP 1.1默认进行持久连接)Connection: close
CookieHTTP请求发送时,会把保存在该请求域名下的所有cookie值一起发送给web服务器。Cookie: $Version=1; Skin=new;
Content-Length请求的内容长度Content-Length: 348
Content-Type请求的与实体对应的MIME信息Content-Type: application/x-www-form-urlencoded
Date请求发送的日期和时间Date: Tue, 15 Nov 2010 08:12:31 GMT
Expect请求的特定的服务器行为Expect: 100-continue
From发出请求的用户的EmailFrom: user@email.com
Host指定请求的服务器的域名和端口号Host: www.zcmhi.com
If-Match只有请求内容与实体相匹配才有效If-Match: “737060cd8c284d8af7ad3082f209582d”
If-Modified-Since如果请求的部分在指定时间之后被修改则请求成功,未被修改则返回304代码If-Modified-Since: Sat, 29 Oct 2010 19:43:31 GMT
If-None-Match如果内容未改变返回304代码,参数为服务器先前发送的Etag,与服务器回应的Etag比较判断是否改变If-None-Match: “737060cd8c284d8af7ad3082f209582d”
If-Range如果实体未改变,服务器发送客户端丢失的部分,否则发送整个实体。参数也为EtagIf-Range: “737060cd8c284d8af7ad3082f209582d”
If-Unmodified-Since只在实体在指定时间之后未被修改才请求成功If-Unmodified-Since: Sat, 29 Oct 2010 19:43:31 GMT
Max-Forwards限制信息通过代理和网关传送的时间Max-Forwards: 10
Pragma用来包含实现特定的指令Pragma: no-cache
Proxy-Authorization连接到代理的授权证书Proxy-Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Range只请求实体的一部分,指定范围Range: bytes=500-999
Referer先前网页的地址,当前请求网页紧随其后,即来路Referer: http://www.zcmhi.com/archives/71.html
TE客户端愿意接受的传输编码,并通知服务器接受接受尾加头信息TE: trailers,deflate;q=0.5
Upgrade向服务器指定某种传输协议以便服务器进行转换(如果支持)Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11
User-AgentUser-Agent的内容包含发出请求的用户信息User-Agent: Mozilla/5.0 (Linux; X11)
Via通知中间网关或代理服务器地址,通信协议Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
Warning关于消息实体的警告信息Warn: 199 Miscellaneous warning

Response部分

Header解释示例
Accept-Ranges表明服务器是否支持指定范围请求及哪种类型的分段请求Accept-Ranges: bytes
Age从原始服务器到代理缓存形成的估算时间(以秒计,非负)Age: 12
Allow对某网络资源的有效的请求行为,不允许则返回405Allow: GET, HEAD
Cache-Control告诉所有的缓存机制是否可以缓存及哪种类型Cache-Control: no-cache
Content-Encodingweb服务器支持的返回内容压缩编码类型。Content-Encoding: gzip
Content-Language响应体的语言Content-Language: en,zh
Content-Length响应体的长度Content-Length: 348
Content-Location请求资源可替代的备用的另一地址Content-Location: /index.htm
Content-MD5返回资源的MD5校验值Content-MD5: Q2hlY2sgSW50ZWdyaXR5IQ==
Content-Range在整个返回体中本部分的字节位置Content-Range: bytes 21010-47021/47022
Content-Type返回内容的MIME类型Content-Type: text/html; charset=utf-8
Date原始服务器消息发出的时间Date: Tue, 15 Nov 2010 08:12:31 GMT
ETag请求变量的实体标签的当前值ETag: “737060cd8c284d8af7ad3082f209582d”
Expires响应过期的日期和时间Expires: Thu, 01 Dec 2010 16:00:00 GMT
Last-Modified请求资源的最后修改时间Last-Modified: Tue, 15 Nov 2010 12:45:26 GMT
Location用来重定向接收方到非请求URL的位置来完成请求或标识新的资源Location: http://www.zcmhi.com/archives/94.html
Pragma包括实现特定的指令,它可应用到响应链上的任何接收方Pragma: no-cache
Proxy-Authenticate它指出认证方案和可应用到代理的该URL上的参数Proxy-Authenticate: Basic
refresh应用于重定向或一个新的资源被创造,在5秒之后重定向(由网景提出,被大部分浏览器支持)Refresh: 5; url=http://www.zcmhi.com/archives/94.html
Retry-After如果实体暂时不可取,通知客户端在指定时间之后再次尝试Retry-After: 120
Serverweb服务器软件名称Server: Apache/1.3.27 (Unix) (Red-Hat/Linux)
Set-Cookie设置Http CookieSet-Cookie: UserID=JohnDoe; Max-Age=3600; Version=1
Trailer指出头域在分块传输编码的尾部存在Trailer: Max-Forwards
Transfer-Encoding文件传输编码Transfer-Encoding:chunked
Vary告诉下游代理是使用缓存响应还是从原始服务器请求Vary: *
Via告知代理客户端响应是通过哪里发送的Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
Warning警告实体可能存在的问题Warning: 199 Miscellaneous warning
WWW-Authenticate表明客户端请求实体应该使用的授权方案WWW-Authenticate: Basic

SpringMCV 基本配置

@ControllerAdvice

  通过@ControllerAdvice,可以将对于控制器的全局配置放置在同一个位置上,注解了@Controller的类的方法都可以使用@ExceptionHandler、@InitBinder、@ModelAttribute注解到方法上这对所有注解了@RequestMapping的控制器内的方法有效。

注解作用
@ExceptionHandler用于全局处理控制器里的异常。
@InitBinder用来设置WebDataBinder,WebDataBinder用来自动绑定前台请求参数到Model中。
@ModelAttribute@ModelAttribute 作用是绑定键值对到全局Model里,所有注解@RequestMapping的方法都可获得此键值对。

文件上传

SpringMvc通过multipart resolver来上传文件,在Spring的控制器中,通过MultipartFile file来接受文件,通过MultipartFile[] files接受多个文件上传。
表单提交的话使用 enctype=“multipart/form-data”

@Bean
public MultipartResolver multipartResolver(){
     CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver();
     multipartResolver.setMaxUploadSize(1000000);
     return multipartResolver;
 }

SpringMVC的定制配置

  SpringMVC的定制配置需要实现一个WebMVCConfigurer类(spring4.0之前需要继承WebMvcConfiigurerAdapter,5.0之后不再需要),并在此类使用@EnableWebMvc注解,来开启对SpringMVC的配置支持。

1、静态资源映射

程序的静态文件(js、css、图片)等需要直接访问,我们可以在配置里实现addResourceHandlers方法实现。

 /*
 * 添加静态资源
 * @param registry
 */
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
            //对外暴露的访问路径
            .addResourceHandler("/views/**")
            //文件放置目录
            .addResourceLocations("classpath:/views/")
}
2、默认静态资源处理

例如:在webroot目录下有一个图片:1.png 我们知道Servelt规范中web根目录(webroot)下的文件可以直接访问的,但是由于DispatcherServlet配置了映射路径是:/ ,它几乎把所有的请求都拦截了,从而导致1.png 访问不到,这时注册一个DefaultServletHttpRequestHandler 就可以解决这个问题。其实可以理解为DispatcherServlet破坏了Servlet的一个特性(根目录下的文件可以直接访问),DefaultServletHttpRequestHandler是帮助回归这个特性的。

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
        configurer.enable("defaultServletName");
    }
3、拦截器配置

拦截器(Interceptor)实现对每一个请求处理前后相关的业务处理,类似与servlet的filter。
让Bean实现HandlerInterceptor接口或者继承HandlerInterceptorAdapter类来实现自定义拦截器。通过实现addInterceptors方法来注册自定义的拦截器。

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/**").excludePathPatterns("/js/**","/css/**","/images/**");
    }
4、快捷的ViewController

没有任何业务处理,只是简单的页面转向。

@RequestMapping("/index")
public String hello(){
   return "index";
}

我们可以在配置中重写addViewControllers来简化配置:

@Override
public void addViewControllers(ViewControllerRegistry registry){
            registry.addViewController("/index").setViewName("/index");
}

这样实现页面跳转会使代码更加简洁。

5、路径匹配参数设置

在SpringMVC中若是路径参数带有".“的话,”.“后的内容将被忽略,例如localhost:8080/login/user.admin,此时”.“后的admin将被忽略,通过实现configurePathMatch方法可不忽略”."。

@Override
public void configurePathMatch(PathMatchConfigurer configurer){
     configurer.setUseSuffixPatternMatch(false);
}
WebMvcConfigurer接口

见:https://www.jianshu.com/p/52f39b799fbb
在这里插入图片描述

SpringMVC测试

  基于RESTful风格的SpringMVC的测试,我们可以测试完整的Spring MVC流程,即从URL请求到控制器处理,再到视图渲染都可以测试。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={MyMvcConfig.class})
@WebAppConfiguration
public classDemoTest {
    @Autowired
    private WebApplicationContext wac;
    @Autowired
    private MockHttpSession sessioin;
    @Autowired
    private MockHttpServletRequest request;
    @Autowired
    private MockHttpServletResponse response;
    private MockMvc mockMvc;
    @Before
    public void setup() {
        this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();   //构造MockMvc
    }
    ...
}

注:
(1)@WebAppConfiguration:测试环境使用,用来表示测试环境使用的ApplicationContext将是WebApplicationContext类型的;value指定web应用的根;
(2)通过@Autowired WebApplicationContext wac:注入web环境的ApplicationContext容器;
(3)然后通过MockMvcBuilders.webAppContextSetup(wac).build()创建一个MockMvc进行测试;

一些常用的测试

1.测试普通控制器

mockMvc.perform(get("/user/{id}", 1)) //执行请求  
            .andExpect(model().attributeExists("user")) //验证存储模型数据  
            .andExpect(view().name("user/view")) //验证viewName  
            .andExpect(forwardedUrl("/WEB-INF/jsp/user/view.jsp"))//验证视图渲染时forward到的jsp  
            .andExpect(status().isOk())//验证状态码  
            .andDo(print()); //输出MvcResult到控制台

2.得到MvcResult自定义验证

MvcResult result = mockMvc.perform(get("/user/{id}", 1))//执行请求  
        .andReturn(); //返回MvcResult  
Assert.assertNotNull(result.getModelAndView().getModel().get("user")); //自定义断言   

3.验证请求参数绑定到模型数据及Flash属性

mockMvc.perform(post("/user").param("name", "zhang")) //执行传递参数的POST请求(也可以post("/user?name=zhang"))  
            .andExpect(handler().handlerType(UserController.class)) //验证执行的控制器类型  
            .andExpect(handler().methodName("create")) //验证执行的控制器方法名  
            .andExpect(model().hasNoErrors()) //验证页面没有错误  
            .andExpect(flash().attributeExists("success")) //验证存在flash属性  
            .andExpect(view().name("redirect:/user")); //验证视图  

4.文件上传

byte[] bytes = new byte[] {1, 2};  
mockMvc.perform(fileUpload("/user/{id}/icon", 1L).file("icon", bytes)) //执行文件上传  
        .andExpect(model().attribute("icon", bytes)) //验证属性相等性  
        .andExpect(view().name("success")); //验证视图  

5.JSON请求/响应验证

String requestBody = "{\"id\":1, \"name\":\"zhang\"}";  
    mockMvc.perform(post("/user")  
            .contentType(MediaType.APPLICATION_JSON).content(requestBody)  
            .accept(MediaType.APPLICATION_JSON)) //执行请求  
            .andExpect(content().contentType(MediaType.APPLICATION_JSON)) //验证响应contentType  
            .andExpect(jsonPath("$.id").value(1)); //使用Json path验证JSON 请参考http://goessner.net/articles/JsonPath/  
      
    String errorBody = "{id:1, name:zhang}";  
    MvcResult result = mockMvc.perform(post("/user")  
            .contentType(MediaType.APPLICATION_JSON).content(errorBody)  
            .accept(MediaType.APPLICATION_JSON)) //执行请求  
            .andExpect(status().isBadRequest()) //400错误请求  
            .andReturn();  
      
    Assert.assertTrue(HttpMessageNotReadableException.class.isAssignableFrom(result.getResolvedException().getClass()));//错误的请求内容体

6.异步测试

 //Callable  
MvcResult result = mockMvc.perform(get("/user/async1?id=1&name=zhang")) //执行请求  
        .andExpect(request().asyncStarted())  
        .andExpect(request().asyncResult(CoreMatchers.instanceOf(User.class))) //默认会等10秒超时  
        .andReturn();  
  
mockMvc.perform(asyncDispatch(result))  
        .andExpect(status().isOk())  
        .andExpect(content().contentType(MediaType.APPLICATION_JSON))  
        .andExpect(jsonPath("$.id").value(1));  

7.全局配置

mockMvc = webAppContextSetup(wac)  
            .defaultRequest(get("/user/1").requestAttr("default", true)) //默认请求 如果其是Mergeable类型的,会自动合并的哦mockMvc.perform中的RequestBuilder  
            .alwaysDo(print())  //默认每次执行请求后都做的动作  
            .alwaysExpect(request().attribute("default", true)) //默认每次执行后进行验证的断言  
            .build();  
      
    mockMvc.perform(get("/user/1"))  
            .andExpect(model().attributeExists("user"));  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值