HelloWorld

  • 依赖:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>

<groupId>com.cuc.mvc</groupId>
<artifactId>springMVC-demo1</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<dependencies>
<!-- SpringMVC -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.1</version>
</dependency>

<!-- 日志 -->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>

<!-- ServletAPI -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>

<!-- Spring5和Thymeleaf整合包 -->
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.12.RELEASE</version>
</dependency>
</dependencies>


</project>
  • SpringMVC配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!--  扫描组件  -->
<context:component-scan base-package="com.cuc.mvc.controller" />


<!-- 前后端分离就不需要了 -->
<!-- 配置Thymeleaf视图解析器 -->
<bean id="viewResolver" class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
<property name="order" value="1"/>
<property name="characterEncoding" value="UTF-8"/>
<property name="templateEngine">
<bean class="org.thymeleaf.spring5.SpringTemplateEngine">
<property name="templateResolver">
<bean class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">

<!-- 视图前缀 -->
<property name="prefix" value="/WEB-INF/templates/"/>

<!-- 视图后缀 -->
<property name="suffix" value=".html"/>
<property name="templateMode" value="HTML5"/>
<property name="characterEncoding" value="UTF-8" />
</bean>
</property>
</bean>
</property>
</bean>

<!-- 如需访问jsp,则将视图解析器替换成以下 -->
<!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
<!-- <property name="prefix" value="/WEB-INF/templates/" />-->
<!-- <property name="suffix" value=".jsp" />-->
<!--</bean>-->
  • web.xml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!--  配置SpringMVC前端控制器。对浏览器发送的请求进行统一处理  -->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--配置SpringMVC配置文件的位置和名称-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<!--将前端控制器DispatcherServlet初始化时间提前到服务器启动时-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- /所匹配的请求可以是/login或.html或.js或.css方式的请求路径
但是不能匹配.jsp请求路径的请求
-->
<url-pattern>/</url-pattern>
</servlet-mapping>
  • Controller
1
2
3
4
5
6
7
8
9
@Controller
public class HelloController {

@RequestMapping("/")
public String index(){
// 返回视图名称
return "index"; // == /WEB-INF/templates/index.html
}
}

@RequestMapping

标识位置

可以使用在类上或方法上

1
2
3
4
5
6
7
8
9
@Controller
@RequestMapping("/hello")
public class HelloController {

@RequestMapping("/index") // 此时访问路径为 /hello/index
public String index(){
return "index";
}
}

属性

参数 解释
name string
value string[]
path string[]
method RequestMethod[]
params string[]
headers string[]
consumes string[]
produces string[]
1
2
3
4
5
// @RequestMapping(value = {"/success1","/success2"} 可以有多个值,请求地址符合其中一个就行
@RequestMapping("/success") // value 可以省略,只写值
public String toSuccess(){
return "success";
}
1
2
3
4
5
6
// method不设置代表任何请求方式都能匹配
// method可以设置多个值
@RequestMapping(value = "/test1",method = {RequestMethod.POST})
public String byPost(){
return "success";
}
1
2
3
4
5
6
7
8
9
// params
// username:代表必须要有username请求参数
// !username:代表不能带有username参数
// username=admin:代表必须要有username请求参数且值必须为admin
// username!=admin:代表必须要有username请求参数且值不能为admin
@GetMapping(value = "/test4",params = {"username","password!=123456"})
public String test4(){
return "success";
}
1
2
// headers规则跟params一样
// eg: headers = {"Host=localhost:8081"}

派生注解

  • @GetMapping
  • @PostMapping
  • @PutMapping
  • @DeleteMapping
1
2
3
4
5
// 只能处理get请求
@GetMapping("/test2")
public String test2(){
return "success";
}

ant风格路径

1
2
3
4
5
6
7
8
// ant风格路径
// ?: ?位置可以是任意的单个字符
// *: 表示任意0或多个字符
// **: 表示任意层目录 (只能使用/**/xxx的方式)
@RequestMapping("/**/*te?t5")
public String test5(){
return "success";
}

占位符

1
2
3
4
5
6
7
// 占位符使用
@RequestMapping("/test6/{id}/{username}")
public String test6(@PathVariable("id")Integer id,@PathVariable("username")String username){
System.out.println("id:"+id);
System.out.println("username:"+username);
return "success";
}

SpringMVC获取请求参数

ServletAPI(原生写法)

1
2
3
4
5
6
7
8
9
10
11
@RequestMapping("/servletAPI")
// 原生写法
public String servletAPI(HttpServletRequest request){
// 在客户端创建cookie,后面控制器形参测试@CookieValue
HttpSession session = request.getSession();

String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username:"+username+",password:"+password);
return "success";
}

控制器形参

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// 可以使用@RequestParam来处理映射关系
// 参数(value、required 默认为true:即如果没有传递user_name参数会报错、defaultValue:当没有user_name参数传递过来或者为空时,则默认为root)
@RequestMapping("/test1")
public String test1(

@RequestParam(value = "user_name",required = false,defaultValue = "root") String username,
String password,
// 当有多个相同名称为hobby参数传递过来时,各个参数值会被,隔开
// 如果 String 改成 String[],则会被各个参数值会被存进数组
String hobby,
// 获取请求头参数,属性跟@RequestParam相同(value、required、defaultValue)
@RequestHeader("Host") String host,
@CookieValue("JSESSIONID") String JSESSIONID) // 同理
{

System.out.println("username:"+username+",password:"+password+",hobby:"+hobby);
System.out.println("host:"+host);
System.out.println("JSESSIONID:"+JSESSIONID);
return "success";
}

image-20220703214750630

实体类形参

1
2
3
4
5
6
@RequestMapping("/test2")
// 通过POJO获取请求参数
public String test2(User user){
System.out.println(user);
return "success";
}

解决中文乱码

web.xml中配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!--配置过滤器,解决中文乱码-->
<!--如果配置之前有请求过数据,则会失效,所以最好配置在最上方-->
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--设置请求编码-->
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<!--设置响应编码-->
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

域对象共享数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
@Controller
@RequestMapping("/scope")
public class ScopeController {

@RequestMapping("/test1")
// 使用servletAPI向request共享数据
public String test1(HttpServletRequest request){
request.setAttribute("requestScope","servletAPI");
return "getScopeValue";
}

@RequestMapping("/test2")
// 使用ModelAndView向request域共享数据
public ModelAndView test2(){
ModelAndView mav = new ModelAndView();
// 处理数据模型,即向request域共享数据
mav.addObject("requestScope","ModelAndView");
// 设置视图名称
mav.setViewName("getScopeValue");
return mav;
}

@RequestMapping("/test3")
// 使用model向request共享数据
public String test3(Model model){
model.addAttribute("requestScope","Model");
return "getScopeValue";
}

@RequestMapping("/test4")
// 使用map向request共享数据
public String test4(Map<String,Object> map){
map.put("requestScope","map");
return "getScopeValue";
}

@RequestMapping("/test5")
// 使用ModelMap向request共享数据
public String test5(ModelMap modelMap){
modelMap.addAttribute("requestScope","ModelMap");
return "getScopeValue";
}

@RequestMapping("/test6")
// 使用servletAPI向session共享数据
public String test6(HttpSession session){
session.setAttribute("sessionScope","session");
return "getScopeValue";
}

@RequestMapping("/test7")
// 使用servletAPI向application共享数据
public String test7(HttpSession session){
ServletContext application = session.getServletContext();
application.setAttribute("applicationScope","application");
return "getScopeValue";
}
}

SpringMVC视图

相关操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@Controller
@RequestMapping("/view")
public class ViewController {

@RequestMapping("/test1")
public String test1(){
// 当返回的视图名称没有前缀时,会被配置文件里的视图解析器解析成ThymeleafView视图
return "success";
}

@RequestMapping("/test2")
public String test2(){
// 加上了转发前缀,不会被Thymeleaf视图解析器解析
return "forward:/view/test1"; // 转发到/view/test1路由 如果不加forward:,会被解析成html路径
}

@RequestMapping("/test3")
public String test3(){
return "redirect:/view/test1"; // 重定向到/view/test1路由
}
}

视图控制器

1
2
3
4
5
6
7
8
9
<!--当访问的路由没有多余处理,只返回一个页面时可以使用-->
<!--这里index同样会被视图解析器解析-->
<mvc:view-controller path="/" view-name="index" />

<!-- 如果只配置了视图控制器,控制层中的路由将全部失效,所以还需配置mvc注解驱动 -->
<!-- 功能还有很多,例如将java对象转成json对象同样需要配置驱动 -->

<!--开启mvc注解驱动-->
<mvc:annotation-driven />

RESTFul

解决PUT、DELETE请求问题

web.xml配置:

1
2
3
4
5
6
7
8
9
10
<!--配置HiddenHttpMethodFilter-->
<!--使可以put和delete提交-->
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
@Controller
@RequestMapping("/rest")
public class UserController {

/**
* 使用RESTFul模拟用户资源的增删改查
* /user GET 查询所有用户信息
* /user/1 GET 根据id查找用户信息
* /user POST 添加用户信息
* /user/1 DELETE 删除用户信息
* /user PUT 更新用户信息
*/

@RequestMapping(value = "/user", method = RequestMethod.GET)
public String getAllUser(){
System.out.println("所有用户信息");
return "success";
}

@RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
public String getUserById(@PathVariable("id")Integer id){
System.out.println("id为"+id+"的用户信息");
return "success";
}

@RequestMapping(value = "/user", method = RequestMethod.POST)
public String addUser(User user){
System.out.println("添加用户:"+user.toString());
return "success";
}

@RequestMapping(value = "/user", method = RequestMethod.PUT)
public String updateUser(User user){
System.out.println("更新用户信息:"+user.toString());
return "success";
}

}

处理静态资源

springmvc配置文件:

1
2
3
4
5
6
7
8
<!--开放对静态资源的访问-->
<!--当DispatcherServlet(前端控制器)匹配不到请求的路径时,则使用默认请求方式-->
<mvc:default-servlet-handler />

<!--必须开启mvc注解驱动,否则所有请求都使用默认请求方式 -->

<!--开启mvc注解驱动-->
<mvc:annotation-driven />

HttpMessageConverter

HttpMessageConverter,报文信息转换器,将请求报文转换为Java对象,或将Java对象转换为响应报文

HttpMessageConverter提供了两个注解和两个类型:@RequestBody@ResponseBodyRequestEntityResponseEntity

依赖

1
2
3
4
5
6
<!--json依赖-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.12.1</version>
</dependency>

操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
@Controller
public class HttpController {

@RequestMapping("/test1")
// 获取请求体
public String test1(@RequestBody String requestBody){
System.out.println("RequestBody:"+requestBody);
return "success";
}

@RequestMapping("/test2")
// 获取整个请求报文
public String test2(RequestEntity<String> requestEntity){
System.out.println("请求头:"+requestEntity.getHeaders());
System.out.println("请求体:"+requestEntity.getBody());
return "success";
}

@RequestMapping("/test3")
// 原生设置响应体
public void test3(HttpServletResponse response) throws IOException {
response.getWriter().print("hello,response");
}


@RequestMapping("/test4")
@ResponseBody
// 返回的数据直接作为响应体
public String test4(){
return "hello,ResponseBody";
}


@RequestMapping("/test5")
@ResponseBody
// 返回json对象(1、需引入json依赖 2、开启mvc注解驱动 3、使用@ResponseBody注解)
public User test5(){
return new User(1001,"admin","123",12,"男");
}

@RequestMapping("/test6")
@ResponseBody
// axios
public String test6(String username,String password){
System.out.println("username:"+username+",password:"+password);
return "axios请求成功";
}

// ResponseEntity文件下载会用到
}

@RestController注解

@RestController注解是SpringMVC提供的一个复合注解,标识在控制器的类上,相当于为类添加@Controller注解,并且为类中的每个方法添加@ResponseBody注解

文件上传与下载

文件下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@RequestMapping("/downLoad")
// ResponseEntity下载文件
public ResponseEntity<byte[]> downLoad(HttpSession session) throws IOException {
//获取ServletContext对象
ServletContext servletContext = session.getServletContext();
//获取服务器中文件的真实路径
String realPath = servletContext.getRealPath("/static/img/1.jpg");
//创建输入流
InputStream is = new FileInputStream(realPath);
//创建字节数组
byte[] bytes = new byte[is.available()];
//将流读到字节数组中
is.read(bytes);
//创建HttpHeaders对象设置响应头信息
MultiValueMap<String, String> headers = new HttpHeaders();
//设置要下载方式以及下载文件的名字
headers.add("Content-Disposition", "attachment;filename=1.jpg");
//设置响应状态码
HttpStatus statusCode = HttpStatus.OK;
//创建ResponseEntity对象
ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(bytes, headers, statusCode);
//关闭输入流
is.close();
return responseEntity;
}

文件上传

依赖

1
2
3
4
5
6
<!--文件上传依赖-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>

配置文件上传解析器

springmvc配置文件:

1
2
<!--必须通过文件解析器的解析才能将文件转换为MultipartFile对象-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />

实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@RequestMapping("/upLoad")
// 文件上传
public String upLoad(MultipartFile photo, HttpSession session) throws IOException {

//获取上传的文件的文件名
String fileName = photo.getOriginalFilename();
//处理文件重名问题
String hzName = fileName.substring(fileName.lastIndexOf("."));
fileName = UUID.randomUUID().toString() + hzName;
//获取服务器中photo目录的路径
ServletContext servletContext = session.getServletContext();
String photoPath = servletContext.getRealPath("photo"); // 为什么会上传到target里面去
File file = new File(photoPath);
if(!file.exists()){
file.mkdir();
}
String finalPath = photoPath + File.separator + fileName;
//实现上传功能
photo.transferTo(new File(finalPath));
return "success";
}

拦截器

用于拦截控制器方法的执行,SpringMVC中的拦截器需要实现HandlerInterceptor或者继承HandlerInterceptorAdapter

  • springmvc配置文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!--配置拦截器-->
<mvc:interceptors>
<!--使用这种方式所有请求都会被拦截-->
<!--<bean class="com.cuc.mvc.interceptors.FirstInterceptor" />-->

<!--需在拦截器类注解,同样对所有请求进行拦截-->
<!--<ref bean="firstInterceptor" />-->

<mvc:interceptor>
<!--拦截路径-->
<!-- /** 表示拦截所有请求 /* 只能拦截一层目录 例如 /a 或 /b,而类似 /a/b 大于一层目录则不能拦截 -->
<!-- /interceptor/* 只能拦截形如 /interceptor/test,/interceptor 则不能拦截到 -->
<!-- /interceptor/** 则能够拦截 /interceptor -->
<mvc:mapping path="/interceptor/*"/>
<!--不拦截路径-->
<!--<mvc:exclude-mapping path="/"/>-->
<ref bean="firstInterceptor" />
</mvc:interceptor>

<!--测试拦截器执行顺序,只跟配置顺序有关-->
<mvc:interceptor>
<mvc:mapping path="/interceptor/*"/>
<ref bean="secondInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
  • 拦截器类
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Component
public class FirstInterceptor implements HandlerInterceptor {

@Override
// 控制器方法执行前执行
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("FirstInterceptor-->preHandle");
return true; // 返回false拦截
}

@Override
// 控制器方法执行后执行
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("FirstInterceptor-->postHandle");
}

@Override
// 视图渲染后执行
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("FirstInterceptor-->afterCompletion");
}
}

// SecondInterceptor一样
  • 执行顺序

image-20220704225754950

异常处理

SpringMVC提供了一个处理控制器方法执行过程中所出现异常的接口:HandlerExceptionResolver

它的实现类有:DefaultHandlerExceptionResolverSimpleMappingExceptionResolver

基于配置文件

  • springmvc配置文件
1
2
3
4
5
6
7
8
9
10
11
<!--配置异常处理-->
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<!--数学运算异常,跳到error页面-->
<prop key="java.lang.ArithmeticException">error</prop>
</props>
</property>
<!--默认将错误信息共享在request域中,ex为键,当前异常为值-->
<property name="exceptionAttribute" value="ex" />
</bean>
  • 控制器类
1
2
3
4
5
6
7
8
9
10
@ControllerAdvice
@RequestMapping("/exception")
public class ExceptionController {

@RequestMapping("/test2")
public void test2(){
int i = 10/0;
}

}

基于注解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@ControllerAdvice
@RequestMapping("/exception")
public class ExceptionController {

// 如果出现了value值里面的异常,则转发到error页面
@ExceptionHandler(value = {ArithmeticException.class,NullPointerException.class})
public String test1(Exception ex, Model model){
// ex为获取到的异常信息
model.addAttribute("ex",ex);
return "error";
}

@RequestMapping("/test2")
public void test2(){
int i = 10/0;
}

}

注解配置SpringMVC

使用配置类和注解代替web.xml和SpringMVC配置文件的功能

替代Spring

1
2
3
4
5
@Configuration
public class SpringConfig {
...
}

替代SpringMVC配置文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/**
* 用来代替SpringMVC的配置文件
*/
// 将当前类设置为配置类
@Configuration
// 开启组件扫描
@ComponentScan("com.cuc.mvc.controller")
// mvc注解驱动
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

//配置生成模板解析器
@Bean
public ITemplateResolver templateResolver() {
WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
// ServletContextTemplateResolver需要一个ServletContext作为构造参数,可通过WebApplicationContext 的方法获得
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(
webApplicationContext.getServletContext());
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setCharacterEncoding("UTF-8");
templateResolver.setTemplateMode(TemplateMode.HTML);
return templateResolver;
}

//生成模板引擎并为模板引擎注入模板解析器
@Bean
public SpringTemplateEngine templateEngine(ITemplateResolver templateResolver) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
return templateEngine;
}

//生成视图解析器并为解析器注入模板引擎
@Bean
public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setCharacterEncoding("UTF-8");
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
}

// default-servlet-handler
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}

// 拦截器
@Override
public void addInterceptors(InterceptorRegistry registry) {
TestInterceptor testInterceptor = new TestInterceptor();
registry.addInterceptor(testInterceptor).addPathPatterns("/**");
}

// view-controller
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/hello").setViewName("hello");
}

// 文件解析器
@Bean
public MultipartResolver multipartResolver(){
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
return commonsMultipartResolver;
}

// 异常解析器 或者 使用bean进行配置
@Override
public void configureHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
SimpleMappingExceptionResolver exceptionResolver = new SimpleMappingExceptionResolver();
Properties prop = new Properties();
prop.setProperty("java.lang.ArithmeticException","error");
exceptionResolver.setExceptionMappings(prop);
exceptionResolver.setExceptionAttribute("ex");
resolvers.add(exceptionResolver);
}
}

替代web.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// web工程的初始化类,用来代替web.xml
public class WebInit extends AbstractAnnotationConfigDispatcherServletInitializer {

/**
* 指定Spring的配置类
*/
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[]{SpringConfig.class};
}


/**
* 指定SpringMVC的配置类
*/
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class[]{WebConfig.class};
}


/**
* 指定DispatcherServlet的映射规则,即url-pattern
*/
@Override
protected String[] getServletMappings() {
return new String[]{"/"};
}

/**
* 注册过滤器
*/
@Override
protected Filter[] getServletFilters() {

// 编码过滤器
CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
characterEncodingFilter.setEncoding("utf-8");
characterEncodingFilter.setForceResponseEncoding(true);

// 使可以put和delete提交
HiddenHttpMethodFilter hiddenHttpMethodFilter = new HiddenHttpMethodFilter();

return new Filter[]{characterEncodingFilter,hiddenHttpMethodFilter};
}
}