一、项目的创建
1、创建webapp项目
2、pom文件的配置
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId><!--全套关于Servlet的依赖-->
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId><!--添加SpringMVC的依赖-->
<version>5.2.5.RELEASE</version>
</dependency
3、相关注解
//创建一个普通类
@Controller //控制器注释
@RequestMapping("/common")//模块名称(类公共地址)
class MyController{
//value={"/doSom.do","",""},自定义接收的请求地址类型
//method = RequestMethod.POST,POST,GET等为枚举类型,这里是自定义接收请求的方式
@RequestMapping(value={"/doSom.do","",""},method = RequestMethod.POST)
public ModelAndView doSome(){
ModeAndView mv = new ModelAndView();
//用请求作用域对象添加KEY和VALUE
mv.addObject("key","StringValues");
......
//请求转发
mv.setViewName("show");
}
}
4、web.xml文件配置
Servvlet配置
<servlet>
<servlet-name>disPatcherServlet(自定义或不自定义类名)</servlet-name>
<servlet-class>org.springframework.web.servlet.DisPatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocaltion</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
<load-on-start>1</load-on-start>
</servlet>
<servlet-mapping>
<servlet-name>disPatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
字符过滤器设置
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<!--
框架源码参数
private String encoding;
private boolean forceRequestEncoding;
private boolean forceResponseEncoding;
-->
指定字符集
<init-param>
<init-name>encoding</init-name>
<param-value>utf-8</param-value>
</init-param>
强制设置请求编码
<init-param>
<param-name>forceRequestEncoding</param-name>
<param-value>true</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>
5、applicationContext.xml配置
组件扫描器
<context:component-scanner base-package="com.bjpowernode.controller"/>
配置转发地址( mv.setViewName("show");)
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/view/"/>
<property name="suffix" value=".jsp"/>
</bean>
6、jsp文件
index.jsp
<a href="doSome.do">点击这个</a>
<a href="other.do">这是Other</a>
......
show.jsp
<center>
<h4>${msg}</h4>
<h4>${msgShow}</h4>
</center>
showOther.jsp
<center>
<h1>this is other</h1>
<h4>${msg}</h4>
<h4>${msgShow}</h4>
</center>
7、目录结构