我们的开发架构一般都是基于两种开发模式:一种是C/S架构,也就是客户端/服务器模式,另一种是B/S架构,也就是浏览器/服务器模式。在JavaEE开发中,几乎全部是基于B/S架构的开发。那么在B/S架构中,系统标准的三层架构包括:表现层、业务层、持久层。三层架构在我们的实际开发中使用的非常多。
三层架构中,每一层都各司其职。
表现层:
业务层:
持久层:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.23</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.7.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.19</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>provided</scope>
</dependency>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<!-- 配置SpringMVC的前端控制器,拦截所有请求 -->
<servlet>
<servlet-name>dispatcherServlet</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>
<!-- 配置Servlet的启动顺序 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping(value = "/hello")
public String hello(){
System.out.println("==========HelloController.hello============");
return "success";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 开启组件扫描 -->
<context:component-scan base-package="com.sunxiaping" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置SpringMVC的注解驱动 -->
<mvc:annotation-driven/>
</beans>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>SpringMVC的入门</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/hello">访问SpringMVC的入门</a>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
成功
</body>
</html>
<mvc:annotation-drivern/>
自动加载RequestMappingHandlerMapping(处理器映射器)和RequestMappingHandlerAdapter(处理器适配器),可以在SpringMVC的配置文件中使用<mvc:annotation-drivern/>
替代处理器映射器和处理器适配器的配置。package org.springframework.web.bind.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.springframework.core.annotation.AliasFor;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Mapping
public @interface RequestMapping {
String name() default "";
@AliasFor("path")
String[] value() default {};
@AliasFor("value")
String[] path() default {};
RequestMethod[] method() default {};
String[] params() default {};
String[] headers() default {};
String[] consumes() default {};
String[] produces() default {};
}
出现位置:
属性:
不常用
):用于指定限制请求参数的条件。它支持简单的表达式,要求请求参数的key和value必须和配置的一模一样。//表示请求参数中必须有accountName
@RequestMapping(value = "findAccount", method = {RequestMethod.GET},params = {"accountName"})
//表示请求参数中必须有money,但是money的参数值不能是100
@RequestMapping(value = "findAccount", method = {RequestMethod.GET},params = {"money!=100"})
不常用
):用于指定限制请求消息头的条件。示例:@RequestMapping
注解中的method属性
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
public class AccountController {
/**
* method = {RequestMethod.POST} 指定请求的类型是POST类型
*
* @return
*/
@RequestMapping(value = "saveAccount", method = {RequestMethod.POST})
public String saveAccount() {
System.out.println("保存账户信息");
return "success";
}
/**
* method = {RequestMethod.GET} 指定请求的类型是GET类型
*
* @return
*/
@RequestMapping(value = "findAccount", method = {RequestMethod.GET},headers = {"content-type=text/*"})
public String findAccount() {
return "success";
}
}
我们知道,表单中的请求参数都是基于key=value的形式的。
SpringMVC绑定请求参数的过程是把表单提交请求参数,作为控制器中方法参数进行绑定的。
示例:
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>SpringMVC的入门</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/account/findAccount?id=1">请求参数的绑定</a>
</body>
</html>
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/account")
public class AccountController {
@RequestMapping(value = "/findAccount", method = {RequestMethod.GET})
public String findAccount(Integer id) {
System.out.println("id = " + id);
return "success";
}
}
基本类型参数:包括基本数据类型和String类型。
POJO类型参数:包括实体类以及关联的实体类。
数组和集合类型参数:包括List结构和Map结构的集合,也包括数组。
ServletAPI对象作为请求参数。
SpringMVC绑定请求参数是自动实现的,如果要想使用,必须遵循使用要求。
HttpServletRequest
、HttpServletResponse
、HttpSession
、java.security.Principal
、Locale
、InputStream
、OutputStream
、Reader
、Writer
。<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>SpringMVC的入门</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/account/findAccount?id=1">请求参数的绑定</a>
</body>
</html>
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/account")
public class AccountController {
@RequestMapping(value = "/findAccount", method = {RequestMethod.GET})
public String findAccount(Integer id) {
System.out.println("id = " + id);
return "success";
}
}
index.jsppackage com.sunxiaping.domain;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
public class Account implements Serializable {
private String name;
private Double money;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"name=‘" + name + ‘\‘‘ +
", money=" + money +
‘}‘;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>SpringMVC的入门</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/account/saveAccount" method="post">
账户名称:<input type="text" name="name" value=""/><br/>
账户余额:<input type="text" name="money" value=""/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
package com.sunxiaping.web;
import com.sunxiaping.domain.Account;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/account")
public class AccountController {
/**
* 保存账户信息
*
* @param account
* @return
*/
@RequestMapping(value = "/saveAccount", method = {RequestMethod.POST})
public String saveAccount(Account account) {
System.out.println("account = " + account);
return "success";
}
}
package com.sunxiaping.domain;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
public class Address implements Serializable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Address{" +
"name=‘" + name + ‘\‘‘ +
‘}‘;
}
}
package com.sunxiaping.domain;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
public class Account implements Serializable {
private String name;
private Double money;
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Account{" +
"name=‘" + name + ‘\‘‘ +
", money=" + money +
", address=" + address +
‘}‘;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>SpringMVC的入门</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/account/saveAccount" method="post">
账户名称:<input type="text" name="name" value=""/><br/>
账户余额:<input type="text" name="money" value=""/><br/>
账户的地址:<input type="text" name="address.name" value=""/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
package com.sunxiaping.web;
import com.sunxiaping.domain.Account;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/account")
public class AccountController {
/**
* 保存账户信息
*
* @param account
* @return
*/
@RequestMapping(value = "/saveAccount", method = {RequestMethod.POST})
public String saveAccount(Account account) {
System.out.println("account = " + account);
return "success";
}
}
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<!-- 配置编码过滤器 -->
<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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置SpringMVC的前端控制器,拦截所有请求 -->
<servlet>
<servlet-name>dispatcherServlet</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>
<!-- 配置Servlet的启动顺序 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 开启组件扫描 -->
<context:component-scan base-package="com.sunxiaping" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置SpringMVC的注解驱动 -->
<mvc:annotation-driven/>
<!-- 设置静态资源不过滤 -->
<mvc:resources mapping="/css/" location="/css/**"/>
<mvc:resources mapping="/img/" location="/img/**"/>
<mvc:resources mapping="/js/" location="/js/**"/>
</beans>
package com.sunxiaping.domain;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
public class Address implements Serializable {
/**
* 地址名称
*/
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Address{" +
"name=‘" + name + ‘\‘‘ +
‘}‘;
}
}
package com.sunxiaping.domain;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
public class Account implements Serializable {
/**
* 账户名称
*/
private String name;
/**
* 账户余额
*/
private Double money;
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Account{" +
"name=‘" + name + ‘\‘‘ +
", money=" + money +
", address=" + address +
‘}‘;
}
}
package com.sunxiaping.domain;
import java.io.Serializable;
import java.util.List;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
public class User implements Serializable {
private String username;
private String password;
private Integer age;
private List<Account> accountList;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public List<Account> getAccountList() {
return accountList;
}
public void setAccountList(List<Account> accountList) {
this.accountList = accountList;
}
@Override
public String toString() {
return "User{" +
"username=‘" + username + ‘\‘‘ +
", password=‘" + password + ‘\‘‘ +
", age=" + age +
", accountList=" + accountList +
‘}‘;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>请求参数的绑定</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/saveUser" method="post">
用户名称:<input type="text" name="username" value=""/><br/>
用户密码:<input type="password" name="password" value=""/><br/>
年龄:<input type="text" name="age" value=""/><br/>
账户1的名称:<input type="text" name="accountList[0].name" value=""/><br/>
账户1的余额:<input type="text" name="accountList[0].money" value=""/><br/>
账户2的名称:<input type="text" name="accountList[1].name" value=""/><br/>
账户2的余额:<input type="text" name="accountList[1].money" value=""/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
package com.sunxiaping.web;
import com.sunxiaping.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
/**
* 增加用户信息
*
* @param user
* @return
*/
@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public String saveUser(User user) {
System.out.println("user = " + user);
return "success";
}
}
package com.sunxiaping.domain;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
public class Address implements Serializable {
/**
* 地址名称
*/
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Address{" +
"name=‘" + name + ‘\‘‘ +
‘}‘;
}
}
package com.sunxiaping.domain;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
public class Account implements Serializable {
/**
* 账户名称
*/
private String name;
/**
* 账户余额
*/
private Double money;
private Address address;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
@Override
public String toString() {
return "Account{" +
"name=‘" + name + ‘\‘‘ +
", money=" + money +
", address=" + address +
‘}‘;
}
}
package com.sunxiaping.domain;
import java.io.Serializable;
import java.util.Map;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
public class User implements Serializable {
private String username;
private String password;
private Integer age;
private Map<String,Account> accountMap;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Map<String, Account> getAccountMap() {
return accountMap;
}
public void setAccountMap(Map<String, Account> accountMap) {
this.accountMap = accountMap;
}
@Override
public String toString() {
return "User{" +
"username=‘" + username + ‘\‘‘ +
", password=‘" + password + ‘\‘‘ +
", age=" + age +
", accountMap=" + accountMap +
‘}‘;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>请求参数的绑定</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/saveUser" method="post">
用户名称:<input type="text" name="username" value=""/><br/>
用户密码:<input type="password" name="password" value=""/><br/>
年龄:<input type="text" name="age" value=""/><br/>
账户1的名称:<input type="text" name="accountMap.one.name" value=""/><br/>
账户1的余额:<input type="text" name="accountMap[‘one‘].money" value=""/><br/>
账户2的名称:<input type="text" name="accountMap[‘two‘].name" value=""/><br/>
账户2的余额:<input type="text" name="accountMap[‘two‘].money" value=""/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
package com.sunxiaping.web;
import com.sunxiaping.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
/**
* 增加用户信息
*
* @param user
* @return
*/
@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public String saveUser(User user) {
System.out.println("user = " + user);
return "success";
}
}
String parameter = request.getParameter("");
String[] parameterValues = request.getParameterValues("");
ServletInputStream inputStream = request.getInputStream();
package com.sunxiaping.converter;
import org.springframework.core.convert.converter.Converter;
import org.springframework.util.StringUtils;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 字符串转Date类型的转换器
*
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
public class StringToDateConverter implements Converter<String, Date> {
/**
* 把字符串转换成日期对象
*
* @param source
* @return
*/
@Override
public Date convert(String source) {
if (StringUtils.isEmpty(source)) {
throw new NullPointerException("请传入参数");
}
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
try {
return df.parse(source);
} catch (ParseException e) {
throw new RuntimeException("类型转换错误");
}
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
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/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 开启组件扫描 -->
<context:component-scan base-package="com.sunxiaping" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置自定义类型转换器 -->
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.sunxiaping.converter.StringToDateConverter"></bean>
</set>
</property>
</bean>
<!-- 配置SpringMVC的注解驱动 -->
<mvc:annotation-driven conversion-service="conversionService"/>
</beans>
package com.sunxiaping.domain;
import java.io.Serializable;
import java.util.Date;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
public class User implements Serializable {
private String username;
private String password;
private Integer age;
private Date birthday;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "User{" +
"username=‘" + username + ‘\‘‘ +
", password=‘" + password + ‘\‘‘ +
", age=" + age +
", birthday=" + birthday +
‘}‘;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>请求参数的绑定</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/saveUser" method="post">
用户名称:<input type="text" name="username" value=""/><br/>
用户密码:<input type="password" name="password" value=""/><br/>
年龄:<input type="text" name="age" value=""/><br/>
生日:<input type="text" name="birthday" value=""/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
package com.sunxiaping.web;
import com.sunxiaping.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
/**
* 增加用户信息
*
* @param user
* @return
*/
@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public String saveUser(User user, HttpServletRequest request) {
System.out.println("user = " + user);
return "success";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>常用注解</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/user/test?name=aaa">@RequestParam注解</a>
</body>
</html>
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
@RequestMapping(value = "/test", method = RequestMethod.GET)
public String test(@RequestParam(value = "name", required = false) String username) {
System.out.println("username = " + username);
return "success";
}
}
作用:
属性:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>常用注解</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/saveUser" method="post">
用户名称:<input type="text" name="username" value=""/><br/>
用户密码:<input type="password" name="password" value=""/><br/>
年龄:<input type="text" name="age" value=""/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
/**
* 增加用户信息
*
* @param user
* @return
*/
@RequestMapping(value = "/saveUser", method = RequestMethod.POST)
public String saveUser(@RequestBody String user) {
System.out.println("user = " + user);
return "success";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>常用注解</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/user/delete/1">删除用户信息</a>
</body>
</html>
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
@RequestMapping(value = "/delete/{id}")
public String delete(@PathVariable(value = "id") Integer id) {
System.out.println("id = " + id);
return "success";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>常用注解</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/user/testRequestHeader">testRequestHeader</a>
</body>
</html>
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
@RequestMapping(value = "/testRequestHeader")
public String testRequestHeader(@RequestHeader(value = "Accept-Encoding") String encoding) {
System.out.println("encoding = " + encoding);
return "success";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>常用注解</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/user/testCookieValue">testCookieValue</a>
</body>
</html>
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
@RequestMapping(value = "/testCookieValue")
public String testCookieValue(@CookieValue(value = "JSESSIONID") String jSessionId) {
System.out.println("jSessionId = " + jSessionId);
return "success";
}
}
package com.sunxiaping.domain;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
public class User implements Serializable {
/**
* 主键
*/
private Integer id;
/**
* 账号 不能修改
*/
private String username;
/**
* 密码
*/
private String password;
/**
* 昵称
*/
private String nickname;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username=‘" + username + ‘\‘‘ +
", password=‘" + password + ‘\‘‘ +
", nickname=‘" + nickname + ‘\‘‘ +
‘}‘;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>常用注解</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/user/updateUser" method="post">
用户主键:<input type="text" name="id" value="1"/><br/>
用户昵称:<input type="text" name="nickname" value=""/><br/>
用户密码:<input type="password" name="password" value=""/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
package com.sunxiaping.web;
import com.sunxiaping.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
@ModelAttribute(value = "user")
public User findById(Integer id) {
User user = new User();
user.setId(id);
user.setUsername("admin");
user.setPassword("123456");
user.setNickname("管理员");
return user;
}
@RequestMapping(value = "/updateUser", method = RequestMethod.POST)
public String updateUser(User user) {
System.out.println("user = " + user);
return "success";
}
}
Controller中的方法返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址。
示例:
package com.sunxiaping.web;
import com.sunxiaping.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
/**
* 指定逻辑视图名,经过视图解析器解析为JSP的物理路径 /WEB-INF/views/success.jsp
*
* @param user
* @return
*/
@RequestMapping(value = "/updateUser", method = RequestMethod.POST)
public String updateUser(User user) {
System.out.println("user = " + user);
return "success";
}
}
当方法的返回值是voide类型的时候,SpringMVC会把方法名作为前缀,到指定的位置查找JSP。
示例:
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>返回值类型</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/user/testVoid">testVoid</a>
</body>
</html>
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
/**
* 当方法返回时void的时候,SpringMVC会把方法名作为前缀,到指定的位置查找JSP
*/
@RequestMapping(value = "/testVoid")
public void testVoid() {
System.out.println("返回的类型是void");
}
}
ModelAndView是SpringMVC为我们提供的一个对象,该对象也可以用作控制器方法的返回值。
示例:
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/user/testModelAndView">testModelAndView</a>
</body>
</html>
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
* 2020-07-26 6:32
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
@RequestMapping(value = "/testModelAndView",method = RequestMethod.GET)
public ModelAndView testModelAndView(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("success");
modelAndView.addObject("helloWorld", "你好,世界");
return modelAndView;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
success ${helloWorld}
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>返回值类型</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/user/testVoid">testVoid</a>
</body>
</html>
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
/**
* 使用原生Servlet API实现转发
*/
@RequestMapping(value = "/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("返回的类型是void");
request.getRequestDispatcher("/WEB-INF/views/success.jsp").forward(request, response);
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>返回值类型</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/user/testVoid">testVoid</a>
</body>
</html>
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
/**
* 使用原生Servlet API实现转发
*/
@RequestMapping(value = "/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("返回的类型是void");
response.sendRedirect(request.getContextPath() + "/success.jsp");
}
}
一般情况下,控制器方法返回字符串类型的值会被当成逻辑视图名处理。
如果返回的字符串中带有forward:
或redirect:
前缀,SpringMVC会对它们进行特殊处理,将forward:
和redirect:
当成指示符,其后的字符串作为URL来处理。
示例:
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/user/test">test</a>
</body>
</html>
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
* 2020-07-26 6:32
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
@GetMapping(value = "/test")
public String test(){
return "forward:/WEB-INF/views/success.jsp";
}
}
@ResponseBody注解用于将Controller方法的返回对象,通过HttpMessageConverter接口转换为指定格式的数据如JSON、XML等,通过Response响应给客户端。
示例:
导入jackson的jar包的Maven坐标:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.8</version>
</dependency>
<mvc:annotation-drivern/>
:<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
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">
<!-- 开启组件扫描 -->
<context:component-scan base-package="com.sunxiaping" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置SpringMVC的注解驱动 -->
<mvc:annotation-driven/>
</beans>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/user/findAll">findAll</a>
</body>
</html>
package com.sunxiaping.domain;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
* 2020-07-26 12:59
*/
public class User implements Serializable {
private String username;
private String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"username=‘" + username + ‘\‘‘ +
", password=‘" + password + ‘\‘‘ +
‘}‘;
}
}
package com.sunxiaping.web;
import com.sunxiaping.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
* 2020-07-26 6:32
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
@GetMapping(value = "/findAll")
@ResponseBody
public List<User> findAll() {
List<User> userList = new ArrayList<>();
userList.add(new User("abc", "123"));
userList.add(new User("bcd", "456"));
return userList;
}
}
multipart/form-data
。POST
。 <input type="file"/>
。<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
CommonsMultipartResolver
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
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">
<!-- 开启组件扫描 -->
<context:component-scan base-package="com.sunxiaping" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 需要配置CommonsMultipartResolver -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="utf-8"/>
<property name="maxUploadSize" value="#{1024*1024}"/>
</bean>
<!-- 配置SpringMVC的注解驱动 -->
<mvc:annotation-driven/>
</beans>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/springmvc/fileUpload" enctype="multipart/form-data" method="post">
上传文件<input type="file" name="file"/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
* 2020-07-26 14:06
*/
@Controller
@RequestMapping(value = "/springmvc")
public class FileUploadController {
@PostMapping(value = "/fileUpload")
public String fileUpload(MultipartFile file) {
System.out.println(file);
String originalFilename = file.getOriginalFilename();
System.out.println("上传文件名 = " + originalFilename);
String name = file.getName();
System.out.println("input标签中name属性的值 = " + name);
//可以通过transferTo方法复制文件
// file.transferTo();
return "success";
}
}
package org.springframework.web.servlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.lang.Nullable;
public interface HandlerInterceptor {
/**
* 这个方法在业务处理器处理请求之前被调用,在该方法中可以对用户请求进行处理。
* 如果程序员决定改拦截器对请求进行拦截处理之后还要调用其他的拦截器,或者业务处理器去进行处理,就返回true,否则返回false。
*
* @param request
* @param response
* @param handler
* @return
* @throws Exception
*/
default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
return true;
}
/**
* 这个方法在业务处理器处理完请求后,但是DispatcherServlet向客户端返回响应前被调用
*
* @param request
* @param response
* @param handler
* @param modelAndView
* @throws Exception
*/
default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
}
/**
* 该方法在DispatcherServlet完全处理请求后被调用,通常用于一些资源清理的操作。
*
* @param request
* @param response
* @param handler
* @param ex
* @throws Exception
*/
default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
}
}
package com.sunxiaping.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
* 2020-07-26 18:04
*/
public class SelfInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("==========preHandle==============");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("==========postHandle==============");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("==========afterCompletion==============");
}
}
package com.sunxiaping.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
* 2020-07-26 18:04
*/
public class SelfInterceptor2 implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("==========preHandle2==============");
return true;
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("==========postHandle2==============");
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("==========afterCompletion2==============");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
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">
<!-- 开启组件扫描 -->
<context:component-scan base-package="com.sunxiaping" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置拦截器 -->
<mvc:interceptors>
<!-- 拦截所有的请求 -->
<bean class="com.sunxiaping.interceptor.SelfInterceptor2"></bean>
<mvc:interceptor>
<!-- 拦截指定的请求-->
<mvc:mapping path="/emps"/>
<bean class="com.sunxiaping.interceptor.SelfInterceptor"/>
</mvc:interceptor>
</mvc:interceptors>
<!-- 配置SpringMVC的注解驱动 -->
<mvc:annotation-driven/>
</beans>
<mvc:annotation-drivern>
,那么DispatcherServlet默认装配的异常处理器是ExceptionHandlerExceptionResolver。<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="${pageContext.request.contextPath}/user/findAll">查询所有用户信息</a>
</body>
</html>
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns="http://www.springframework.org/schema/beans"
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">
<!-- 开启组件扫描 -->
<context:component-scan base-package="com.sunxiaping"></context:component-scan>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置SpringMVC的注解驱动 -->
<mvc:annotation-driven/>
</beans>
package com.sunxiaping.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.Serializable;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
* 2020-07-26 6:32
*/
@Controller
@RequestMapping(value = "/user")
public class UserController implements Serializable {
@GetMapping(value = "/findAll")
public String findAll() {
System.out.println("查询所有用户信息");
if (true) {
throw new RuntimeException("aa");
}
return "success";
}
}
package com.sunxiaping.web;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;
/**
* @author <a href="mailto:1900919313@qq.com">weiwei.xu</a>
* @version 1.0
* 2020-07-26 18:23
*/
@ControllerAdvice
public class UserControllerAdvice {
@ExceptionHandler(RuntimeException.class)
public ModelAndView resolverMathException(Exception ex) {
ModelAndView mv = new ModelAndView();
mv.setViewName("error");
mv.addObject("msg", "出错啦");
return mv;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
原文:https://www.cnblogs.com/xuweiweiwoaini/p/13660297.html