什么是springMVC
springmvc是实现mvc设计模型的请求驱动类型的web框架。通过注解的方式,让一个JAVA类成为控制器(controller)
三层架构:
表现层(展示层和控制层),业务层,持久层
springmvc用于表现层框架,与浏览器进行数据的交互,接受浏览器发送的请求和返回给浏览器响应结果
M --model —javavbean(可重用主键)
V --view —jsp
C --controller—servlet
spring mvc的入口是servlet,struct2是filter
spring mvc是基于方法设计的,struct2是基于类
spring创建单例类对象,速度比sturct2快,处理ajax请求更方便
spring框架是基于组件方式的执行流程
组件:
1.前端控制器DispatcherServlet(核心):在web.xml中,获取请求,发送请求到处理器映射器中。
2.处理器映射器Handlermapping:处理器映射器接收前端控制器的请求,根据请求可以告知controller类的哪一个方法应该执行,并把这个方法返回到前端控制器
3.处理器适配器HandlerAdapter:接收前端控制器从处理器映射器拿过来的方法,然后去执行方法,再把结果返回给前端控制器
4.视图解析器VIewResolver:在springmvc.xml中,接收前端控制器从处理器适配器拿过来的结果,根据结果去寻找相应的视图(如jsp),然后把视图返回给前端控制器
5.前端控制器把视图响应给浏览器。
@RequestMapping 注解属性的使用方式。
package com.zxh.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
//控制器类,相当于servlet
/*
* @Controller //声明这个类是控制器类,可以让处理器映射器处理。
* */
@Controller //相当于@Conmpenent
@RequestMapping(path = "/user")//卸载类上
public class UserContaoller {
@RequestMapping(path = "/hello") //请求映射,当发起请求后就会执行这个方法
public String Helloone() {
System.out.println("Hello springmvc");
return "success";
}
/*
*
* @RequestMapping(path = "/user") //建立请求url和处理请求方法之间的联系
* 可以放在类和接口上,也可以放在方法上。
* 属性:path 请求的路径,就是绑定哪一个请求执行这个方法。path = "/user"
* value 跟path作用一样
* method 用来指定请求方式 get或者post method = {RequestMethod.GET}
* params 用来指定请求传递给方法的参数(如果写了需要传递的参数,请求没有传递,则方法不执行)
* params={"username"},必须要传递一个key为username的参数
* params={"username=zxh"},必须要传递一个key为username且value=zxh的参数
* params={"price!100"},必须要传递一个key为price切value不等于100的参数
* headers 用于指定请求中的请求头(如果写了需要传递的请求头,请求没有传递,则方法不执行)
* headers={"Accept"},必须要传递一个Accept的请求头
* */
//写在方法上。
@RequestMapping(path = "/test",method = {RequestMethod.GET},params = {"username"}, headers={"Accept"})
public String TestRequestmapping(){
System.out.println("测试Requestmapping注解");
return "success";
}
}
请求参数的绑定
一:
1.表单传递过来的参数:如username=zxh&password=123
2.会根据url找到相应的方法 如TestUser(String username,String password)
3.方法里面的参数名称必须和表单的参数名称一致,这样就可以绑定了
二:
支持的数据类型有 基本数据类型和字符串,javabean对象,集合数据类型
User对象
private String name ;
private String password;
// private Account account;
private List<Account> accountlist;
private Map<String,Account> accountmap;
Account对象
private int price;
private String phone;
1.封装基本类型和string类型
jsp页面
<a href="param/test?username=zxh">请求参数绑定</a>
--%>
controller类
@RequestMapping(path = "test")
public String TestPara(String username)
{
System.out.println("执行了param方法"+username);
return "success";
}
2.javabean对象
jsp页面
<%--把数据封装到User对象中,user中存在account对象。
注意:表单name里的值必须和pojo类中的属性名一样,才可以封装。--%>
<%--
<form action="param/userbean" method="post">
姓名 <input type="text" name="name"><br>
密码 <input type="text" name="password"><br>
账户 <input type="text" name="account.price"><br>
手机号 <input type="text" name="account.phone"><br>
<input type="submit" value="提交" ><br>
</form>--%>
controller类
@RequestMapping(value = "/userbean")
public String TestUser(User user)
{
System.out.println(user);
return "success";
}
3.集合类型的封装
jsp页面
<%--把数据封装到User类中,类中存在List和map集合--%>
<form action="param/userbean" method="post">
姓名 <input type="text" name="name"><br>
密码 <input type="text" name="password"><br>
<%-- 封装到list集合中--%>
账户1 <input type="text" name="accountlist[0].price"><br>
手机号1 <input type="text" name="accountlist[0].phone"><br>
<%--封装到map集合中--%>
账户2 <input type="text" name="accountmap['one'].price"><br>
手机号2 <input type="text" name="accountmap['one'].phone"><br>
<input type="submit" value="提交" ><br>
</form>
controller类
@RequestMapping(value = "/userbean")
public String TestUser(User user)
{
List<Account> account1 = user.getAccountlist();
Map<String,Account> account2= user.getAccountmap();
System.out.println(user);
System.out.println(account1);
System.out.println(account2);
return "success";
}
自定义类型转换器(适配器模式)
首先,页面传递的数据全部都是字符串形式 。springmvc会自动把类型转化成相应的类型到controller方法中。
1.定义一个类实现Converter接口(必须实现这个接口),该接口有两个泛型,第一个表示当前类型,第二个表示你需要的类型。相当于创造一根数据线(左边接口时usb,右边接口是type-c)
2.在springmvc.xml中配置自定义类型转换器。(声明这个线所在的位置)
3.在mvc:annotation-driven 标签中写上conversion-service,让转换器生效。(把线插入设备)
//coverter类
package com.zxh.utils;
import org.springframework.core.convert.converter.Converter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
* 自定义类型转换器
* 把字符串转换成日期
* */
public class StirngtoDate implements Converter<String,Date>{
/*
* 把传入进来的字符串 传换成 Date类型
* */
@Override
public Date convert(String s) {
if(s==null)
{
throw new RuntimeException("请输入日期参数");
}
else {
//指定需要的格式
DateFormat df = new SimpleDateFormat("yyyy-mm-dd");
//转换成日期
try {
return df.parse(s);
} catch (ParseException e) {
throw new RuntimeException("转换失败,格式不正确");
}
}
}
}
/**--------*-----*/
//把自定义转换器注入到容器中
<!--配置自定义类型转化器-->
<bean id="conversionServiceFactoryBean" class="org.springframework.context.support.ConversionServiceFactoryBean">
<!--声明自定义转换器类-->
<property name="converters">
<set>
<!--导入自定义转换器全路径类名-->
<bean class="com.zxh.utils.StirngtoDate"></bean>
</set>
</property>
</bean>
/*---------------*/
//让转换器生效
<mvc:annotation-driven conversion-service="conversionServiceFactoryBean"></mvc:annotation-driven>
@RequestParam注解属性的使用方式。
把请求中指定名称的参数,传递给控制器方法中的参数。(用于解决请求中参数名和方法中参数名不一致问题)
JSP页面
<%--requestparam注解--%>
<a href="Rparam/onerparam?name=haha" >Requestparam</a>
//Controller页面
/*
* 注解 @Requestpatam
* 把请求中name的值放到方法参数username中
* 属性:value=name:用于指定请求中的参数名
* */
@RequestMapping(path = "onerparam")
public String TestoneRequestparam(@RequestParam(name = "name") String username){
System.out.println(username);
return "success";
}
@RequestBody注解属性的使用方式。
用于获取请求体内容,得到的数据内容格式是(key=value&key=vlaue…)
get请求无法使用此注解标签
JSP页面
<%--reuqestbody注解--%>
<form action="Rparam/onerbody" method="post">
价格 <input type="text" name="price"><br>
手机号 <input type="text" name="phone"><br>
日期 <input type="text" name="date"><br>
<input type="submit" value="提交" ><br>
</form>
//Controller页面
/*
* 注解 @RequestBody
* 会把请求中所有的参数以key=value的形式存放在body中
*
* */
@RequestMapping(path = "onerbody")
public String TestRequestbody(@RequestBody String body){
System.out.println(body);
return "success";
}
//返回的数据格式
//price=00&phone=123&date=2020-1-2
@PathVaribale注解属性的使用方式。
用于绑定url中的占位符,如url中/add/{user},这个{user}就是url占位符,一般用于restful风格编程
restful风格:
使得controller中的每一个方法的url路径都相同,根据请求的方式和url占位符来调用controller中的方法
JSP页面
<%--Pathvaribale注解,注意url的写法是 直接 /id ,不是 ?id==value --%>
<a href="Rparam/onePvaribale/10" >PathVaribale</a>
//Controller类
/*
* 注解 @PathVaribale
* 把请求中url id的值放到方法中id的值
* 属性:name=value:用于指定请求url中的占位符名称。
* */
@RequestMapping(path = "/onePvaribale/{sid}")
public String TestPathVaribale(@PathVariable(name = "sid") String id){
System.out.println(id);
return "success";
}
@ModelAttribute注解属性的使用方式。
自我提供方法,完善前端提供的javabean对象属性,并重新封装,然后把javabean返回给控制器方法的参数中
出现在方法上:表示当前方法会在控制器的方法执行之前执行
出现在参数上: 获取指定的数据给参数赋值
JSP页面
<%--ModelAttribute注解--%>
<form action="Rparam/oneMAttribute" method="post">
价格 <input type="text" name="price"><br>
手机号 <input type="text" name="phone"><br>
<input type="submit" value="提交" ><br>
</form>
//controller类
@RequestMapping(path = "/oneMAttribute")
public String TestModelAttribute(@ModelAttribute(value = "account") Account account){
System.out.println("请求调用的控制器方法执行了");
System.out.println(account);
return "success";
}
/*
* 该方法会在TestModelAttribute执行前执行。
有返回值 public Account FirstTestModelAttribute(int price)
* 会把处理过的Account对象直接传递给TestModelAttribute的Account参数
无返回值 public void FirstTestModelAttribute(int price , Map<String ,Account>)
1.需要一个map集合的参数,把对象放在map中
2.然后在TestModelAttribute中参数中使用@ModelAttribute(value="")。
* */
/* @ModelAttribute
public Account FirstTestModelAttribute(int price)
{
//通过价格查询数据库,返回实体中没有的日期属性(模拟)
Account account = new Account();
account.setPrice(price);
account.setPhone("1234567");
account.setDate(new Date());
System.out.println("有ModelAttribute注解的方法执行了");
return account;
}*/
@ModelAttribute
public void FirstTestModelAttribute(int price , Map<String ,Account> map) {
//通过价格查询数据库,返回实体中没有的日期属性(模拟)
Account account = new Account();
account.setPrice(price);
account.setPhone("1234567");
account.setDate(new Date());
map.put("account", account);
System.out.println("有ModelAttribute注解的方法执行了");
}
@SeesionAttributes
将指定的Model中的键值对添加至session中,model和modelmap相当于request
注解只能写在类上,不能写在方法上
@SessionAttributes(value ={"name"})
public class RparamController {
/*
* @SeesionAttributes
* 属性:
* value:用于指定存入的属性名称,(把request域中的值存入到session域中)
* type:用纸指定存入的数据类型。
* Model ModelMap 相当于httprequest对象。
*
* */
@RequestMapping(path = "/oneSAttribute")
public String TestSessionAttribute(Model model, ModelMap modelMap, SessionStatus sessionStatus){
System.out.println("请求调用的控制器方法执行了");
//相当于request.setAttribute()。
model.addAttribute("name","zxh");
//相当于request.getAttribute()。
String name = (String) modelMap.get("name");
//相当于session.removeAttribute,但这个是清空session
sessionStatus.setComplete();
return "success";
}
}
//JSP页面
<%--
Created by IntelliJ IDEA.
User: ZhangXianhao
Date: 2020/3/2
Time: 15:53
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>success</title>
</head>
<body>
<h1>success</h1>
${ requestScope.name}
${sessionScope.name}
</body>
</html>
Modelandview对象
/*
* ModelAndView 对象作用:
* 1.可以把对象存储到request域中
* 2.可以跳转到其他页面
* 3.返回modelandview对象
* */
@RequestMapping(value = "/modeladnview")
public ModelAndView TstModeladnView()
{
//1.创建modelandview对象
ModelAndView ma = new ModelAndView();
User user = new User();
user.setName("zxh");
user.setPassword("123");
//2.把user对象存储到modelandview对象中,同时也会存入到requset域中。
ma.addObject("user",user);
//3.跳转到哪一个页面。
ma.setViewName("success");
System.out.println("111111");
return ma;
}
传递Json数据到controller中封装成javabean对象,然后把JavaBean对象转换成jason字符串传递给前端。
<%--
Created by IntelliJ IDEA.
User: ZhangXianhao
Date: 2020/3/4
Time: 17:37
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
<script src="https://libs.baidu.com/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
//发送ajax请求
$.ajax({
//编写json格式,设置属性和值
url:"user/ajax",
contentType:"application/json;charset=UTF-8",
//传递json数据到前端。
data: '{"name":"test","password":"123"}',
dataType:"json",
type:"post",
success:function (data){
//data是服务器端响应返回的json数据
alert(data);
alert(data.name);
}
});
})
})
</script>
</head>
<body>
<a href="user/modeladnview"> ModelandView</a>
<br>
<button id="btn">ajax异步请求</button>
</body>
</html>
//controller类
@RequestMapping(value = "/ajax")
public @ResponseBody User TestAjax(@RequestBody User user) {
//前端发送ajax请求,传入了json字符串,后端把json字符串封装到User对象中(导入架包后自动实现)
System.out.println("ajax来了");
System.out.println(user.getName());
System.out.println(user);
//返回user对象,并用 @ResponseBody注解把对象封装成json字符串传递给前面调用的jsp页面。
return user;
}
采用Ajax上传文件方式
1.form表单的enctype取值改变为:multipart/form-data(getparamter失效)
2.method属性必须是post
3.提供一个文件选择域
4.导入commons-fileupload组件
5.进行controll编写
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<%--
Created by IntelliJ IDEA.
User: ZhangXianhao
Date: 2020/3/5
Time: 10:08
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script>
function uploadFiles(){
var uploadFile = new FormData($("#file")[0]);
console.log(uploadFile);
if("undefined" != typeof(uploadFile) && uploadFile != null && uploadFile != ""){
$.ajax({
url:'springmvcfile/one',
type:'POST',
data:uploadFile,
async: false,
cache: false,
contentType: false, //不设置内容类型
processData: false, //不处理数据
success:function(data){
data = JSON.parse(data);
//获取表格对象
var ta = document.getElementById("ta");
//插入新的行
var tr = ta.insertRow(1);
var cell0 = tr.insertCell(0);
cell0.innerHTML=data.uuid;
var cell1 = tr.insertCell(1);
cell1.innerHTML=data.size;
var cell2 = tr.insertCell(2);
cell2.innerHTML=data.type;
var cell3 = tr.insertCell(3);
cell3.innerHTML=data.filename;
var cell4 = tr.insertCell(4);
cell4.innerHTML=data.time;
var cell5 = tr.insertCell(5);
cell5.innerHTML=data.address;
},
error:function(){
alert("上传失败!");
}
})
}else {
alert("选择的文件无效!请重新选择");
}
}
</script>
</head>
<body>
<%-- <form enctype="multipart/form-data">
选择文件:<input type="file"name="fileload"><br>
<input type="submit" value="传统方式上传" >
</form>
--%>
<br>
<%-- <form action="springmvcfile/one" method="post" enctype="multipart/form-data">
选择文件:<input type="file"name="fileload"><br>
<input type="button" value="上传文件" onclick="uploadFiles();"/>
</form>
--%>
<form method="post" id="file" action="" enctype="multipart/form-data">
<h3>选择一个文件:</h3>
<input id="excelFile" type="file" name="fileload" />
<br/>
<span id="id"></span>
<table></table>
<br/>
<input type="button" value="上传" onclick="uploadFiles();"/>
</form>
<table border="1" id="ta">
<tr>
<td>uuid</td>
<td>文件大小</td>
<td>文件类型</td>
<td>文件原始名</td>
<td>上传时间</td>
<td>文件地址</td>
</tr>
</table>
body>
</html>
package com.zxh.controller;
import com.zxh.pojo.IFile;
import com.zxh.service.FileService;
import org.apache.commons.io.IOUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
@Controller
@RequestMapping(path = "/springmvcfile")
public class SpirngmvcfileController {
/*
*
* spingmvc方式上传
* */
@RequestMapping(value = "/one")
public @ResponseBody IFile TestSpringmvcfile(HttpServletRequest req, MultipartFile fileload) throws Exception {
ApplicationContext ac = new ClassPathXmlApplicationContext("springmvc.xml");
FileService fileService = (FileService) ac.getBean("fileservice");
//获取当前日期,平且转换为yyymmdd格式
String timeStr1 = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//指定文件上传位置
String path = req.getSession().getServletContext().getRealPath("/" + timeStr1 + "/");
//调用业务层
IFile iFile= fileService.SelectFile(path, fileload);
return iFile;
}
}
package com.zxh.service.serviceimpl;
import com.zxh.dao.daoimpl.FileDaoimpl;
import com.zxh.pojo.IFile;
import com.zxh.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;
@Service(value = "fileservice")
public class FileServiceimpl implements FileService {
@Resource(name = "ifile")
private IFile ifile;
@Resource(name = "filedao")
private FileDaoimpl fileDaoimpl;
@Override
public IFile SelectFile(String path, MultipartFile fileload) throws IOException {
//判断该路径是否存在
File file = new File(path);
if(!file.exists())
{
//如果不存在则创建该文件夹
file.mkdir();
}
//获取上传文件的名称
String filename = fileload.getOriginalFilename();
System.out.println(filename);
//获取上传的文件大小
double dsize = Double.valueOf(fileload.getSize())/1024/1024;
String ssize = String.valueOf(dsize);
System.out.println(dsize);
//获取文件类型
String typename = filename.substring(filename.lastIndexOf("."));
System.out.println(typename);
//把文件名称设置成唯一值防止覆盖,uuid
String uuid = UUID.randomUUID().toString().replace("-","");
//把uuid和后缀名拼接起来。
String lastname=uuid+typename;
System.out.println(path);
//获取文件上传的日期
String time = path.substring(path.lastIndexOf("\\")+1);
System.out.println(time);
//完成文件上传
fileload.transferTo(new File(path,lastname));
//封装文件信息传递到IFile对象中
ifile.setUuid(uuid);
ifile.setSize(ssize);
ifile.setType(typename);
ifile.setFilename(filename);
ifile.setTime(time);
ifile.setAddress(time+"\\"+lastname);
System.out.println(ifile);
fileDaoimpl.SelectfileDao(ifile);
return ifile;
}
}
springmvc下载文件
<form action="springmvcfile/two" method="post">
请输入文件地址:<input type="text" name="name"><br>
<input type="submit"value="下载">
</form>
@RequestMapping(value = "/two")
public void TestFiledown(HttpServletRequest req, HttpServletResponse resp,String name) throws Exception {
//获取文件的类型
String filetype = name.substring(name.lastIndexOf(".")+1);
System.out.println(filetype);
//读取服务器中的文件地址
String path = req.getSession().getServletContext().getRealPath("");
System.out.println(path+"\\"+name);
//把下载文件的地址给与file
File file = new File(path+"\\"+name);
//打开输入流
InputStream is = new FileInputStream(file);
//设置需要下载的文件大小,文件类型,请求头和文件名
resp.setContentLength((int)file.length());
resp.setContentType(filetype);
resp.setHeader("Content-Disposition","attachment;filename="+name);
//打开输出流,下载到本地硬盘中
OutputStream os = resp.getOutputStream();
IOUtils.copy(is,os);
os.close();
is.close();
}
Springmvc异常处理
springmvc处理异常过程
1.配置异常处理器组件
2.controller,service,dao得异常都会向上抛出给前端控制器
3.前端控制器把异常抛出到异常处理器组件
4.异常处理器组件处理异常,把处理后得异常返回到浏览器
springmvc处理配置和编写
1.编写自定义异常类
package com.zxh.Excetion;
/*
*
* 自定义异常类POJO
* */
public class TryCatch extends Exception{
//存储提示信息
private String message;
public TryCatch(String message) {
this.message=message;
}
@Override
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
2.编写异常处理器,实现接口HandlerExceptionResolver
package com.zxh.Excetion;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ExceptionResoler implements HandlerExceptionResolver {
/**
*处理异常
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param e
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
TryCatch tryCatch=null;
//判断Exception是不是TryCatch类型的异常
if(e instanceof TryCatch){
//把Exception强转换为TryCath类型异常
tryCatch=(TryCatch) e;
}
else {
tryCatch = new TryCatch("系统正在维护");
}
//船舰modelandview对象
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("error",tryCatch.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
3.配置异常处理器(跳转到提示页面 )
<!-- //配置异常处理器-->
<bean id="exceptionResoler" class="com.zxh.Excetion.ExceptionResoler"/>
4.controller使用自定义异常
package com.zxh.controller;
import com.zxh.Excetion.TryCatch;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping(value = "/catch")
public class CatchController {
@RequestMapping(value = "/one")
public String TestCatch() throws TryCatch {
System.out.println("Catch。。。。。");
try {
int i=10/0;
} catch (Exception e) {
e.printStackTrace();
//抛出自定义异常信息
throw new TryCatch("计算内容出现错误");
}
return "success";
}
}
springmvc拦截器(AOP思想)
拦截器和过滤器的区别:
1.过滤器配置/*后,对所有要访问的支援进行拦截,拦截器指挥拦截控制器方法,不会拦截jsp,html等。
2.过滤器有servlet提供,而拦截器由springmvc提供。
3.过滤器范围大,拦截器范围小
springmvc处理和配置拦截器
1.编写拦截器类,实现接口 HandlerInterceptor
package com.zxh.Excetion;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ExceptionResoler implements HandlerExceptionResolver {
/**
*处理异常
* @param httpServletRequest
* @param httpServletResponse
* @param o
* @param e
* @return
*/
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
TryCatch tryCatch=null;
//判断Exception是不是TryCatch类型的异常
if(e instanceof TryCatch){
//把Exception强转换为TryCath类型异常
tryCatch=(TryCatch) e;
}
else {
tryCatch = new TryCatch("系统正在维护");
}
//船舰modelandview对象
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("error",tryCatch.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
2.配置拦截器类
<!--配置拦截器-->
<mvc:interceptors>
<!--配置具体的拦截器-->
<mvc:interceptor>
<!--要拦截的具体方法,如我要拦截interceptorcontroller中 Test()方法,就在里面写地址-->
<mvc:mapping path="/test/two"/>
<!--不要拦截的具体方法-->
<!-- <mvc:exclude-mapping path=""/>-->
<!--配置拦截器对象-->
<bean class="com.zxh.Interceptor.MyInterceptor"></bean>
</mvc:interceptor>
3.执行结果
预处理拦截器执行了
controll中的方法执行了。。。。
拦截器后处理执行了
这里是success页面执行的结果
拦截器最后的处理执行了
总结
以上就是springmvc的基本使用
1.首先要学会搭建环境
2.熟悉各个标签的使用
3.熟悉前后端数据传输的方式
4.熟悉文件下载和文件上传的使用
5.熟悉自定义异常类和拦截器的使用