SpringMVC环境搭建

  1. 导入jar包

image-20191221152428789

  1. 配置web.xml文件

    image-20191221184917575

  2. 配置SpringMVC配置文件

    image-20191221195312998

  3. 编写控制器Controller

    image-20191221200527283

字符编码过滤器

  • filter-class:org.springframework.web.filter.CharacterEncodingFilter
  • url-pattern配置为/*从而拦截一切请求,对其进行设置字符编码
  • 设置初始化参数encoding的值,配置字符编码格式

视图解析器

  • SpringMVC 会提供默认视图解析器.
  • 程序员自定义视图解析器 prefix-前缀 suffix-后缀
  • 如果希望不执行自定义视图解析器,在方法返回值前面添加forward:或 redirect:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--配置前端控制器-->
<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>
<!--自启动-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!--拦截除了jsp外的所有请求-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
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
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--扫描注解-->
<context:component-scan base-package="com.kylin.controller"></context:component-scan>
<!--注解驱动-->
<!-- org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping -->
<!-- org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter -->
<mvc:annotation-driven></mvc:annotation-driven>
<!--释放静态资源-->
<!---->
<mvc:resources mapping="/js/**" location="/js/"></mvc:resources>
<mvc:resources mapping="/css/**" location="/css/"></mvc:resources>
<mvc:resources mapping="/images/**" location="/images/"></mvc:resources>
<!--配置前端控制器-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/"></property>
</bean>
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Controller 
public class DemoController {
@RequestMapping("/demo")
public String demo(){
System.out.println("执行 demo");
return "main.jsp";
}

@RequestMapping("/demo2")
public String demo2(){
System.out.println("demo2");
return "main1.jsp";
}
}