1.框架搭建过程
a.新建Java Enterprise项目
b.添加Maven项目所需jar包
<?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.example</groupId>
<artifactId>SpringMVC-dome01</artifactId>
<version>1.0-SNAPSHOT</version>
<name>SpringMVC-dome01</name>
<packaging>war</packaging>
<properties>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<junit.version>5.7.0</junit.version>
</properties>
<dependencies>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</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>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.3.9</version>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
<version>3.0.11.RELEASE</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>3.3.0</version>
</plugin>
</plugins>
</build>
</project>
c.编写web.xml文件
<?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>
<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>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
d.在sources目录下新建springMVC.xml文件,开启组件扫描
<?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"
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">
<!--扫描控制层组件-->
<context:component-scan base-package="com.example.SpringMVC_demo1.Controllers"></context:component-scan>
</beans>
e.新建Controller层
@Controller
public class controllers {
@RequestMapping("/")
public String index(){
return "index";
}
}
f.在sources目录下在编写springMVC.xml文件,用于组合返回值
<?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"
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">
<!--扫描控制层组件-->
<context:component-scan base-package="com.example.SpringMVC_demo1.Controllers"></context:component-scan>
<!-- 配置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>
</beans>
g.html页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>hello word</div>
</body>
</html>
2. RequestMapping(此注解的类上必须有@Controller注解)
1.@RequestMapping注解标识的位置
标识在一个类上标识页面访问需要加上此路径
@Controller
@RequestMapping("/Test")
public class Controller2 {
//http://localhost:8080/SpringMVC_demo1/Test/test
@RequestMapping("/test")
public String index(){
return "index";
}
}
只标识在一个方法上表示访问此路径
@Controller
public class Controller1 {
//http://localhost:8080/SpringMVC_demo1/
@RequestMapping("/")
public String index(){
return "index";
}
}
2.@RequestMapping注解的value属性
或的关系只要匹配一个就可以
//http://localhost:8080/SpringMVC_demo1/targer1
//http://localhost:8080/SpringMVC_demo1/target
@RequestMapping(value={"/target","/targer1"})
public String target(){
return "target";
}
3.@RequestMapping注解的Method属性
a.method里面的值为何种请求方式,只能接受此种请求方式,若是没有提交方式则两种都可以
<form th:action="@{/target1}" method="get">
<button name="tijaio"> 提交</button>
</form>
@RequestMapping(value = {"/target1"},method = {RequestMethod.GET,RequestMethod.POST})
public String target1(){
return "target";
}
b.@GetMapping注解,@PostMapping注解,@PutMapping注解,@DeleteMapping注解
不需要再@RequestMapping注解中设置nethod值,用以上注解只能为此请求方式,但需要设置value值
<form th:action="@{/target2}" method="get">
<input type="submit" value="提交2">
</form><br>
@GetMapping(value = {"/target2","target3"})
public String target2(){
return "target";
}
4.RequestMapping注解的params属性
<form th:action="@{/target4}" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password">
<input type="submit" value="提交4">
</form><br>
//@RequestMapping(value ="/target4",method = RequestMethod.GET,params = {"username"})参数中必须带有username属性
//@RequestMapping(value ="/target4",method = RequestMethod.GET,params = {"!username"})参数中必须不带有username属性
//@RequestMapping(value ="/target4",method = RequestMethod.GET,params = {"username=admin"})参数username属性值必须是admin
@RequestMapping(value ="/target4",method = RequestMethod.GET,params = {"username!=admin"})//参数username属性值必须不是admin
public String target3(){
return "target";
}
5.RequestMapping注解的headers属性
<a th:href="@{/target5}">点击我可以跳转</a>
//@RequestMapping(value = "/target5",headers = {"!header"})
//@RequestMapping(value = "/target5",headers = {"header"})
//@RequestMapping(value = "/target5",headers = {"Host!=localhost:8080"})
@RequestMapping(value = "/target5",headers = {"Host=localhost:8080"})
public String target5(){
return "target";
}
6.SpringMVC支持ant风格的路径(特殊的除外)
?:单个字符 @RequestMapping("/a?a/test")
@RequestMapping("/target?6")
public String target6(){
return "target";
}
*:任意0个或多个字符 @RequestMapping("/a*a/test")
@RequestMapping("/target*7")
public String target7(){
return "target";
}
**:表示一层或多层 @RequestMapping("/**/test") 注:只能用于/**/XXX的形式不然和*作用一样
@RequestMapping("/**/target8")
public String target8(){
return "target";
}
7.SpringMVC支持路径中的占位符
<a th:href="@{/target9/1/wxc}">点击我可以跳转</a>
@RequestMapping(value = "/target9/{id}/{username}")
public String target9(@PathVariable("id") Integer id,@PathVariable("username") String username){
System.out.println(id + ":" + username);
return "target";
}
3.SpringMVC获取参数
1.原生Servlet请求方式
<form th:action="@{/target10}" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password">
<input type="submit" value="提交4">
</form><br>
@RequestMapping(value = "/target10")
public String target10(HttpServletRequest httpServletRequest){
String username = httpServletRequest.getParameter("username");
System.out.println(username);
return "target";
}
2.通过控制器方法的形参获取请求参数
a.SpringMVC无复选框时,获取参数的方法,只需要保证前端form表单中name属性值或a标签中传参值和后端方法传参数的值对应即可
<form th:action="@{/target11}" method="post">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password">
<input type="submit" value="提交11">
</form><br>
<a th:href="@{/target11(username='admin',password=123456)}">点击我可以跳转</a><br>
@RequestMapping(value = "/target11")
public String target11(String username,String password){
System.out.println(username + ":" + password);
return "target";
}
b.SpringMVC有复选框时,获取参数的方法,只需要保证前端form表单中name属性值和后端方法传参数的值对应即可,复选框的形式以数组的形式传参
<form th:action="@{/target12}" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password">
兴趣爱好:<input type="checkbox" name="check" value="足球">足球
<input type="checkbox" name="check" value="篮球">篮球
<input type="checkbox" name="check" value="排球">排球
<input type="submit" value="提交12">
</form><br>
@RequestMapping(value = "/target12")
public String target12(String username,String password,String[] check){
System.out.println(username + ":" + password + Arrays.toString(check));
return "target";
}
3.通过@RequestParam注解传参,前端和后端name值不对应时
<a th:href="@{/target13(username='admin12',password=123456)}">点击我可以跳转</a>
@RequestMapping(value = "/target13")
public String target13(@RequestParam(value = "username") String username, @RequestParam(value = "password") String password){
System.out.println(username + ":" + password);
return "target";
}
RequestParam三个属性,value="前端name属性或a标签中的属性名",required=false(前端可以不传递值使用defaultValue中的默认值),defaultValue="默认值(不是前端的name属性名,是直接赋给后面的属性)"
<a th:href="@{/target13}">点击我可以跳转</a>
@RequestMapping(value = "/target13")
public String target13(@RequestParam(value = "username", required = false, defaultValue = "username") String username, @RequestParam(value = "password",required = false,defaultValue = "password") String password){
System.out.println(username + ":" + password);
return "target";
}
4.@RequestHeader注解传参,根据请求信息头进行传参
<a th:href="@{/target14}">点击我可以跳转</a><br>
@RequestMapping(value = "/target14")
public String target14(@RequestHeader(value = "Host") String localhost){
System.out.println(localhost);
return "target";
}
@RequestHeader三个属性和@RequesParam属性值相同
5.@CookidValue注解传参
@CookieValue是将cookie数据和控制器方法的形参创建映射关系
@CookieValue注三个属性和@RequesParam属性值相同
6.通过Pojo获取请求参数
<form th:action="@{/target15}" method="get">
用户名:<input type="text" name="username"><br>
密码:<input type="password" name="password"><br>
性别:<input type="radio" name="sex" value="男">男
<input type="radio" name="sex" value="女">女<br>
年龄:<input type="text" name="age"><br>
<input type="submit" value="提交15">
</form><br>
@RequestMapping(value = "/target15")
public String target15(User user){
System.out.println(user.toString());
return "target";
}
4.解决Post请求方式时乱码问题
通过在web.xml文件中配置filter过滤器的方式解决Post乱码问题
<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>
5.域对象共享数据
1.通过ServletAPI向request域对象共享数据
<a th:href="@{/target16}">点击我可以跳转</a><br>
@RequestMapping("/target16")
public String target16(HttpServletRequest request){
request.setAttribute("key","hello");
return "target";
}
<p th:text="${key}"></p>
2.使用ModelAndView向request域对象共享数据
<a th:href="@{/target17}">点击我可以跳转17</a><br>
@RequestMapping("/target17")
public ModelAndView target17(){
ModelAndView modelAndView=new ModelAndView();
modelAndView.addObject("key17","helloword");
modelAndView.setViewName("target");
return modelAndView;
}
3.使用Model向request域对象共享数据
<a th:href="@{/target18}">点击我可以跳转18</a><br>
@RequestMapping("/target18")
public String target18(Model model){
model.addAttribute("key18","hellokey18");
return "target";
}
<p th:text="${key18}">18</p>
4.使用Map向request域对象中共享数据
<a th:href="@{/target19}">点击我可以跳转19</a><br>
@RequestMapping("/target19")
public String target19(Map<String,Object> map){
map.put("key19","hellokey19");
return "target";
}
<p th:text="${key19}">19</p>
5.使用ModelMap向request域对象共享数据
<a th:href="@{/target20}">点击我可以跳转20</a><br>
@RequestMapping("/target20")
public String target20(ModelMap modelMap){
modelMap.addAttribute("key20","hellokey20");
return "target";
}
<p th:text="${key20}">20</p>
6.向session域共享数据
<a th:href="@{/target21}">点击我可以跳转21</a><br>
@RequestMapping("/target21")
public String target21(HttpSession httpSession){
httpSession.setAttribute("key21","hellokey21");
return "target";
}
<p th:text="${session.key21}">21</p>
7.向ajpplication域中共享数据
<a th:href="@{/target22}">点击我可以跳转22</a><br>
@RequestMapping("/target22")
public String target22(HttpSession httpSession){
ServletContext application = httpSession.getServletContext();
application.setAttribute("key22","helokey22");
return "target";
}
<p th:text="${application.key22}">22</p>
6.SpringMVC的视图
1.Thymeleafview(无前缀无后缀,使用Xml文件中Thymeleaf解析方式),index就是Thymeleaf解析
@RequestMapping("/")
public String index(){
return "index";
}
2.转发视图(地址栏不变)forward: 为前缀,转发至另一个Controller下的RequestMapping请求
<a th:href="@{/target23}">点击我可以跳转23</a><br>
@RequestMapping("/target22")
public String target22(HttpSession httpSession){
ServletContext application = httpSession.getServletContext();
application.setAttribute("key22","helokey22");
return "target";
}
@RequestMapping("/target23")
public String target23(){
return "forward:/target22";
}
<p th:text="${application.key22}">22</p>
3.重定向视图(地址栏改变)redirect: 为前缀,转发至另一个Controller下的RequestMapping请求
<a th:href="@{/target24}">点击我可以跳转24</a><br>
@RequestMapping("/target22")
public String target22(HttpSession httpSession){
ServletContext application = httpSession.getServletContext();
application.setAttribute("key22","helokey22");
return "target";
}
@RequestMapping("/target24")
public String target24(){
return "redirect:/target22";
}
<p th:text="${application.key22}">22</p>
4.视图控制器,View-Controller,通过映射的方式,仅仅作用于服务器与前端界面之间的跳转,不传参等等操作
在SpringMVC.xml文件中配置
引入mvc命名空间
<?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 https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--Path:设置处理的请求地址
view-name:设置请求地址所对应的视图名称-->
<mvc:view-controller path="/" view-name="index"></mvc:view-controller>
<!--当SpringMVC中设置任何一个view-controller时,
其他控制器中的请求映射将全部失效,
此时需要在SpringMVC的核心配置文件中设置开启mvc注解驱动的标签-->
<mvc:annotation-driven />