Spring MVC 返回的数据对象转Json的纯注解配置
1、pom.xml中引入jackson相关包
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.5</version> </dependency>
最终引入的Jar包:
2、WebMvcConfig中配置Jackson的Bean
@Configuration @EnableWebMvc @ComponentScan(basePackages = "com.zx.test.shiro.controller", includeFilters = @Filter(classes = Controller.class), useDefaultFilters = false) public class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void configureMessageConverters(List<HttpMessageConverter<?>> converters) { super.configureMessageConverters(converters); MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter(); jsonConverter.setDefaultCharset(Charset.forName("UTF-8")); converters.add(jsonConverter); } }
3、Controller代码
@RestController public class LoginController { @RequestMapping(value = "/login") public ResponseBaseDto login(@RequestParam("userName") String userName, @RequestParam("password") String password) { Subject subject = SecurityUtils.getSubject(); UsernamePasswordToken token = new UsernamePasswordToken(userName, password); try { subject.login(token); } catch (UnknownAccountException e) { e.printStackTrace(); return new ResponseBaseDto("001", "用户名或密码错误"); } catch (IncorrectCredentialsException e) { e.printStackTrace(); return new ResponseBaseDto("001", "用户名或密码错误"); } return new ResponseBaseDto("000"); } }
效果
4、未配置的错误异常
相关推荐
yupi0 2020-10-10
spring 2020-08-18
编程点滴 2020-07-29
幸运小侯子 2020-07-05
itjavashuai 2020-07-04
qingjiuquan 2020-06-29
shushan 2020-06-25
小鱿鱼 2020-06-22
咻pur慢 2020-06-18
melonjj 2020-06-17
qingjiuquan 2020-06-13
neweastsun 2020-06-05
小鱿鱼 2020-06-05
mxcsdn 2020-05-31
吾日五省我身 2020-05-27
牧场SZShepherd 2020-05-27
sweetgirl0 2020-05-14