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

第 66 章 Spring MVC

目录

66.1. @EnableWebMvc
66.1.1. CORS 跨域请求
66.1.2. Spring MVC CORS with WebMvcConfigurerAdapter
66.2. @Controller
66.2.1. @RequestMapping
66.2.2. @GetMapping
66.2.3. @PostMapping
66.2.4. @RequestBody
66.2.5. RequestMapping with Request Parameters - @RequestParam
66.2.6. @RequestHeader - 获取 HTTP Header 信息
66.2.7. RequestMapping with Path Variables - @PathVariable
66.2.8. @MatrixVariable注解,RFC3986定义URI的路径(Path)中可包含name-value片段
66.2.9. @ModelAttribute
66.2.10. @ResponseBody
66.2.11. @ResponseStatus 设置 HTTP 状态
66.2.12. @CrossOrigin
66.2.13. @CookieValue - 获取 Cookie 值
66.2.14. @SessionAttributes
66.2.15. ModelAndView
66.2.16. HttpServletRequest / HttpServletResponse
66.3. @RestController
66.3.1. 返回迭代器
66.3.2. 上传文件
66.3.3. 返回实体
66.3.4. JSON
66.3.5. 处理原始 RAW JSON 数据
66.3.6. 返回 JSON 对象 NULL 专为 "" 字符串
66.3.7. XML
66.3.8. 兼容传统 json 接口
66.3.9. 上传文件
66.3.10. Spring boot with csv
66.3.11. Json 处理
66.3.12. synchronized
66.3.13. Spring boot with Emitter
66.4. View
66.4.1. 配置静态文件目录
66.4.2. 添加静态文件目录
66.4.3. Using Spring’s form tag library
66.4.4. Thymeleaf
66.4.5. FreeMarker
66.4.6. i18n 国际化
66.5. 校验器(Validator)
66.5.1. 常规用法
66.5.2. 自定义注解
66.6. Interceptor/Filter 拦截器/过滤
66.6.1. Session 拦截
66.6.2. Token 拦截
66.6.3. 过滤器
66.6.4. 拦截器获取PathVariable变量
66.7. String boot with RestTemplate
66.7.1. RestTemplate Example
66.7.2. GET 操作
66.7.3. POST 操作
66.7.4. PUT 操作
66.7.5. Delete 操作
66.7.6. 上传文件
66.7.7. HTTP Auth
66.7.8. PKCS12
66.7.9. Timeout 超时设置
66.8. RestClient
66.8.1. 创建 RestClient
66.8.2. Get 操作
66.8.3. Post Json
66.8.4. HTTP Authorization Basic
66.8.5. onStatus
66.8.6. 下载二进制流

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

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

66.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;
	}

}
		
	

66.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("*");
            }
        };
    }			
			
		

66.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);
	}
}