Home | 简体中文 | 繁体中文 | 杂文 | Github | 知乎专栏 | Facebook | Linkedin | Youtube | 打赏(Donations) | About
知乎专栏

第 41 章 Spring MVC

目录

41.1. @EnableWebMvc
41.1.1. CORS 跨域请求
41.1.2. Spring MVC CORS with WebMvcConfigurerAdapter
41.2. @Controller
41.2.1. @RequestMapping
41.2.2. @GetMapping
41.2.3. @PostMapping
41.2.4. @RequestBody
41.2.5. RequestMapping with Request Parameters - @RequestParam
41.2.6. @RequestHeader - 获取 HTTP Header 信息
41.2.7. RequestMapping with Path Variables - @PathVariable
41.2.8. @MatrixVariable注解,RFC3986定义URI的路径(Path)中可包含name-value片段
41.2.9. @ModelAttribute
41.2.10. @ResponseBody
41.2.11. @ResponseStatus 设置 HTTP 状态
41.2.12. @CrossOrigin
41.2.13. @CookieValue - 获取 Cookie 值
41.2.14. @SessionAttributes
41.2.15. ModelAndView
41.2.16. HttpServletRequest / HttpServletResponse
41.2.17. StreamingResponseBody 输出 Raw Data
41.3. @RestController
41.3.1. 返回迭代器
41.3.2. 上传文件
41.3.3. 返回实体
41.3.4. JSON
41.3.5. 处理原始 RAW JSON 数据
41.3.6. 返回 JSON 对象 NULL 专为 "" 字符串
41.3.7. XML
41.3.8. 兼容传统 json 接口
41.3.9. 上传文件
41.3.10. Spring boot with csv
41.3.11. Json 处理
41.3.12. synchronized
41.3.13. SSE Streaming in Spring MVC
41.3.14. StreamingResponseBody
41.4. View
41.4.1. 配置静态文件目录
41.4.2. 添加静态文件目录
41.4.3. Using Spring’s form tag library
41.4.4. Thymeleaf
41.4.5. FreeMarker
41.4.6. i18n 国际化
41.5. 校验器(Validator)
41.5.1. 常规用法
41.5.2. 自定义注解
41.6. Interceptor/Filter 拦截器/过滤
41.6.1. Session 拦截
41.6.2. Token 拦截
41.6.3. 过滤器
41.6.4. 拦截器获取PathVariable变量
41.7. String boot with RestTemplate
41.7.1. RestTemplate Example
41.7.2. GET 操作
41.7.3. POST 操作
41.7.4. PUT 操作
41.7.5. Delete 操作
41.7.6. 上传文件
41.7.7. HTTP Auth
41.7.8. PKCS12
41.7.9. Timeout 超时设置
41.8. RestClient
41.8.1. 创建 RestClient
41.8.2. Get 操作
41.8.3. Post Json
41.8.4. HTTP Authorization Basic
41.8.5. onStatus
41.8.6. 下载二进制流

Spring MVC 有两种启动模式,一种是传统Tomcat,需要配置很多XML文件。另一种方式是采用 Spring Boot 需要些一个Java程序,不需要写xml文件,这个程序会帮助你处理启动所需的一切,并且采用嵌入方式启动 Tomcat 或者 Jetty.

两种方式各有优缺点,Tomcat 方式配置繁琐,但是可以使用虚拟机,同一个IP地址使用不同域名访问,出现不同的内容。而Spring Boot一个应用一个容器一个端口,比不得不通过端口来区分应用。

41.1. @EnableWebMvc

		
package cn.netkiller.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Configuration
@EnableWebMvc
public class WebMvcConfig extends WebMvcConfigurerAdapter {

	@Override
	public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
		configurer.enable();
	}

	@Bean
	public InternalResourceViewResolver viewResolver() {
		InternalResourceViewResolver resolver = new InternalResourceViewResolver();
		resolver.setPrefix("WEB-INF/jsp/");
		resolver.setSuffix(".jsp");
		return resolver;
	}

}
		
	

41.1.1. CORS 跨域请求

			
@Configuration
public class CorsConfiguration
{
    @Bean
    public WebMvcConfigurer corsConfigurer()
    {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}		
			
		
			
 	@Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**").allowedOrigins("*");
            }
        };
    }			
			
		

41.1.2. Spring MVC CORS with WebMvcConfigurerAdapter

			
@Configuration
@EnableWebMvc
public class CorsConfiguration extends WebMvcConfigurerAdapter
{
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedMethods("GET", "POST");
    }
}
			
		
			
@Configuration
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter {
	@Override
	public void addCorsMappings(CorsRegistry registry) {
	  registry.addMapping("/info/**")
	   	  .allowedOrigins("http://localhost:8080", "http://localhost:8000")
		  .allowedMethods("POST", "GET",  "PUT", "OPTIONS", "DELETE")
		  .allowedHeaders("X-Auth-Token", "Content-Type")
		  .exposedHeaders("custom-header1", "custom-header2")
		  .allowCredentials(false)
		  .maxAge(4800);
	}
}