增加 springmvc 示例

This commit is contained in:
YunaiV
2019-11-17 23:47:05 +08:00
parent 4b28266aa2
commit d812f7545d
7 changed files with 181 additions and 5 deletions

View File

@@ -26,6 +26,19 @@
<scope>test</scope>
</dependency>
<!-- 引入 jackson 对 xml 的转换器,实现对 XML 的序列化 -->
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<!-- 引入 Fastjson ,实现对 JSON 的序列化 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
</dependencies>
</project>

View File

@@ -3,6 +3,9 @@ package cn.iocoder.springboot.lab23.springmvc.config;
import cn.iocoder.springboot.lab23.springmvc.core.interceptor.FirstInterceptor;
import cn.iocoder.springboot.lab23.springmvc.core.interceptor.SecondInterceptor;
import cn.iocoder.springboot.lab23.springmvc.core.interceptor.ThirdInterceptor;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
@@ -10,6 +13,11 @@ import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@@ -18,7 +26,10 @@ import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
@Configuration
public class SpringMVCConfiguration implements WebMvcConfigurer {
@@ -96,4 +107,68 @@ public class SpringMVCConfiguration implements WebMvcConfigurer {
});
}
// @Override
// public void addCorsMappings(CorsRegistry registry) {
// // 添加全局的 CORS 配置
// registry.addMapping("/**") // 匹配所有 URL ,相当于全局配置
// .allowedOrigins("*") // 允许所有请求来源
// .allowCredentials(true) // 允许发送 Cookie
// .allowedMethods("*") // 允许所有请求 Method
// .allowedHeaders("*") // 允许所有请求 Header
//// .exposedHeaders("*") // 允许所有响应 Header
// .maxAge(1800L); // 有效期 1800 秒2 小时
// }
@Bean
public FilterRegistrationBean<CorsFilter> corsFilter() {
// 创建 UrlBasedCorsConfigurationSource 配置源,类似 CorsRegistry 注册表
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 创建 CorsConfiguration 配置,相当于 CorsRegistration 注册信息
CorsConfiguration config = new CorsConfiguration();
config.setAllowedOrigins(Collections.singletonList("*")); // 允许所有请求来源
config.setAllowCredentials(true); // 允许发送 Cookie
config.addAllowedMethod("*"); // 允许所有请求 Method
config.setAllowedHeaders(Collections.singletonList("*")); // 允许所有请求 Header
// config.setExposedHeaders(Collections.singletonList("*")); // 允许所有响应 Header
config.setMaxAge(1800L); // 有效期 1800 秒2 小时
source.registerCorsConfiguration("/**", config);
// 创建 FilterRegistrationBean 对象
FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(
new CorsFilter(source)); // 创建 CorsFilter 过滤器
bean.setOrder(0); // 设置 order 排序。这个顺序很重要哦,为避免麻烦请设置在最前
return bean;
}
// @Override
// public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// // 增加 XML 消息转换器
// Jackson2ObjectMapperBuilder xmlBuilder = Jackson2ObjectMapperBuilder.xml();
// xmlBuilder.indentOutput(true);
// converters.add(new MappingJackson2XmlHttpMessageConverter(xmlBuilder.build()));
// }
// @Override
// public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// // 增加 XML 消息转换器
// Jackson2ObjectMapperBuilder xmlBuilder = Jackson2ObjectMapperBuilder.xml();
// xmlBuilder.indentOutput(true);
// converters.add(new MappingJackson2XmlHttpMessageConverter(xmlBuilder.build()));
// }
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
// 创建 FastJsonHttpMessageConverter 对象
FastJsonHttpMessageConverter fastJsonHttpMessageConverter = new FastJsonHttpMessageConverter();
// 自定义 FastJson 配置
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setCharset(Charset.defaultCharset()); // 设置字符集
fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect); // 剔除循环引用
fastJsonHttpMessageConverter.setFastJsonConfig(fastJsonConfig);
// 设置支持的 MediaType
fastJsonHttpMessageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.APPLICATION_JSON,
MediaType.APPLICATION_JSON_UTF8));
// 添加到 converters 中
converters.add(0, fastJsonHttpMessageConverter); // 注意,添加到最开头,放在 MappingJackson2XmlHttpMessageConverter 前面
}
}

View File

@@ -0,0 +1,23 @@
package cn.iocoder.springboot.lab23.springmvc.controller;
import cn.iocoder.springboot.lab23.springmvc.vo.ProductVO;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
/**
* 产品 Controller
*/
@Deprecated
@RestController
@RequestMapping("/products")
public class ProductController {
@PostMapping(value = "/add",
consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE},
produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}
)
public ProductVO add(@RequestBody ProductVO product) {
return product;
}
}

View File

@@ -6,10 +6,8 @@ import cn.iocoder.springboot.lab23.springmvc.core.vo.CommonResult;
import cn.iocoder.springboot.lab23.springmvc.vo.UserVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import java.util.UUID;
@@ -18,6 +16,7 @@ import java.util.UUID;
*/
@RestController
@RequestMapping("/users")
//@CrossOrigin(value = "*")
public class UserController {
private Logger logger = LoggerFactory.getLogger(getClass());
@@ -52,6 +51,20 @@ public class UserController {
return CommonResult.success(user);
}
/**
* 获得指定用户编号的用户
*
* 测试个问题
*
* @param id 用户编号
* @return 用户
*/
@PostMapping("/get")
public UserVO get3(@RequestParam("id") Integer id) {
// 查询并返回用户
return new UserVO().setId(id).setUsername(UUID.randomUUID().toString());
}
/**
* 测试抛出 NullPointerException 异常
*/
@@ -85,4 +98,14 @@ public class UserController {
throw new ServiceException(ServiceExceptionEnum.USER_NOT_FOUND);
}
@PostMapping(value = "/add",
// ↓ 增加 "application/xml"、"application/json" ,针对 Content-Type 请求头
consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE},
// ↓ 增加 "application/xml"、"application/json" ,针对 Accept 请求头
produces = {MediaType.APPLICATION_XML_VALUE, MediaType.APPLICATION_JSON_VALUE}
)
public UserVO add(@RequestBody UserVO user) {
return user;
}
}

View File

@@ -1,7 +1,7 @@
package cn.iocoder.springboot.lab23.springmvc.controller2;
import cn.iocoder.springboot.lab23.springmvc.vo.UserVO;
import cn.iocoder.springboot.lab23.springmvc.core.web.GlobalResponseBodyHandler;
import cn.iocoder.springboot.lab23.springmvc.vo.UserVO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@@ -15,6 +15,7 @@ import java.util.UUID;
*/
@RestController
@RequestMapping("/test")
//@CrossOrigin(origins = "*", allowCredentials = "true") // 允许所有来源,允许发送 Cookie
public class TestController {
/**
@@ -23,6 +24,7 @@ public class TestController {
* @return 用户
*/
@GetMapping("/get")
// @CrossOrigin(allowCredentials = "false") // 允许所有来源,不允许发送 Cookie
public UserVO get() {
return new UserVO().setId(1).setUsername(UUID.randomUUID().toString());
}

View File

@@ -21,4 +21,5 @@ public class TestServletContextListener02 implements ServletContextListener {
public void contextDestroyed(ServletContextEvent sce) {
}
}

View File

@@ -0,0 +1,39 @@
package cn.iocoder.springboot.lab23.springmvc.vo;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
/**
* 产品 VO
*/
public class ProductVO {
/**
* 商品编号
*/
@JacksonXmlProperty(localName = "id")
private Integer id;
/**
* 商品标题
*/
@JacksonXmlProperty(localName = "title")
private String title;
public Integer getId() {
return id;
}
public ProductVO setId(Integer id) {
this.id = id;
return this;
}
public String getTitle() {
return title;
}
public ProductVO setTitle(String title) {
this.title = title;
return this;
}
}