SpringMVC配置类配置静态资源处理器、视图解析器、JSON解析器等

接上文 《通过Java的Spring配置类整合SSM框架》

0. 前置条件

SpringMVCConfig继承WebMvcConfigurationSupport,便可以重写一系列webmvc的方法。

public class SpringMVCConfig extends WebMvcConfigurationSupport

1. 静态资源处理器配置

因为配置的问题,目前静态资源现在会被DispatcherServlet拦截,导致无法被读取。

按以往xml配置,咱们都用ResourceHandler来处理静态资源。这里也一样的。

/**
 * 这个配置类的作用相当于 springMVC-config.xml
 */
@Configuration
@ComponentScan(basePackages = "org.sjh", useDefaultFilters = false,
        includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Controller.class),
                @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Configuration.class)})
public class SpringMVCConfig extends WebMvcConfigurationSupport {
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("classpath:/");
    }
}

验证配置是否成功:

在resources中添加文件01.html,文件内容如下

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <h1>01.html</h1>
</body>
</html>

部署后输入URLhttp://localhost:8080/01.html

结果如下,配置成功

截屏2021-07-30 下午11.14.00

2. 视图解析器

在以前的配置中,我们用ViewResolvers来解析视图。同样的,在配置类里注册ViewResolvers即可。

步骤:

  1. 在webapp中创建jsp文件夹,并创建hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>hello.jsp</h1>
</body>
</html>
  1. 添加jsp依赖
<dependency>
  <groupId>javax.servlet.jsp</groupId>
  <artifactId>javax.servlet.jsp-api</artifactId>
  <version>2.3.3</version>
</dependency>
  1. 在SpringMVCConfig类中注册ViewResolvers。

注册jsp比较简单,就只有两个参数,第一个是前缀,第二个是后缀

@Override
protected void configureViewResolvers(ViewResolverRegistry registry) {
    registry.jsp("/jsp/", ".jsp");
}
  1. 测试

修改HelloController.java代码如下。期望是,访问hello地址后,可以返回hello.jsp页面。

@Controller
public class HelloController {
    @Autowired
    HelloService helloService;

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return helloService.hello();
    }

    @GetMapping("/hello2")
    public String hello2() {
        return "hello";
    }
}

启动Tomcat后输入URLhttp://localhost:8080/hello2

返回结果,测试成功

截屏2021-07-30 下午11.28.23

上面这种代码比较简单,没有传入任何参数,因此使用配置类直接映射也是可以的

在SpringMVCConfig.java中注册

@Override
protected void addViewControllers(ViewControllerRegistry registry) {
    registry.addViewController("hello3").setViewName("hello");
}

当输入URLhttp://localhost:8080/hello3 后,仍然会返回hello.jsp

3. JSON解析器(以Jackson为例)

3.1 返回简单json

在Controller中添加方法

@ResponseBody
@GetMapping("/hello4")
public List<String> getNames() {
    List<String> names = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        names.add("name" + i);
    }
    return names;
}

输入URL http://localhost:8080/hello4 ,返回简单json列表

截屏2021-07-31 上午12.39.58

3.2 返回复杂json

返回简单的json,不用json解析器还是能应付的。但是如果返回的是复杂json,例如实体类的列表,而且还有日期等比较复杂的信息。这时候就需要json的解析器。Java里常用的json解析器有Jackson,Gson和fastjson。

加入json依赖

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.12.4</version>
</dependency>

先构造一个实体类User,局部代码

public class User {
    private String name;
    private Date birthday;

MVC配置类添加方法,定义日期格式。

@Override
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
  ObjectMapper objectMapper = new ObjectMapper();
  objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
  MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(objectMapper);
  converters.add(converter);
}

定义controller方法,当访问路径/hello4,将会返回json数据。

@ResponseBody
@GetMapping("/hello4")
public List<User> getNames() {
    List<User> names = new ArrayList<>();
    for (int i = 0; i < 10; i++) {
        names.add(new User("name" + i, new Date()));
    }
    return names;
}

测试:

URL http://localhost:8080/hello4

截屏2021-07-31 上午10.10.19

  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值