SpringMVC进阶-异常拦截器文件上传和Restful风格
发布日期:2021-05-07 14:44:55 浏览次数:17 分类:技术文章

本文共 15109 字,大约阅读时间需要 50 分钟。

目录

案例需要的依赖

4.0.0
org.example
springmvc021
1.0-SNAPSHOT
war
com.fasterxml.jackson.core
jackson-core
2.9.0
com.fasterxml.jackson.core
jackson-databind
2.9.0
com.fasterxml.jackson.core
jackson-annotations
2.9.0
javax.servlet
javax.servlet-api
3.1.0
provided
javax.servlet.jsp
jsp-api
2.0
provided
org.springframework
spring-context
5.1.6.RELEASE
org.springframework
spring-web
5.1.6.RELEASE
org.springframework
spring-webmvc
5.1.6.RELEASE
org.projectlombok
lombok
1.16.6
org.apache.maven.plugins
maven-compiler-plugin
3.1
1.8
1.8
utf-8
org.apache.tomcat.maven
tomcat7-maven-plugin
2.1
80
/

1 异步调用

在这里插入图片描述

1.1 发送异步请求

前端index.jsp代码

两个注意事项

1.前端需要通过contentType告诉后端是JSON数据,并且数据在请求体中

2.前端需要把数据转换成字符串再发送

<%@ page contentType="text/html;charset=UTF-8" language="java" %>            

在这里插入图片描述

java代码

在这里插入图片描述

package cn.itcast.controller;import cn.itcast.domain.User;import org.springframework.format.annotation.DateTimeFormat;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.ResponseBody;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;@Controller@RequestMapping("/user")public class UserController {
@RequestMapping("/ajax") @ResponseBody public Map
ajax(@RequestBody List
users){
System.out.println(users); //不要直接返回字符串,返回对象,测试前端success接收到的是字符串还是对象 HashMap
map = new HashMap<>(); map.put("status","success"); return map; }}

在这里插入图片描述

在这里插入图片描述

2 异步请求-跨域访问

2.1 跨域访问介绍

  • 当通过域名A下的操作访问域名B下的资源时,称为跨域访问
  • 跨域访问时,会出现无法访问的现象

2.2 跨域环境搭建

当前电脑启动两台服务器会比较麻烦。

可以为当前电脑设置两个host域名,访问页面用A域名,页面访问后台用B域名

修改C:\Windows\System32\drivers\etc 目录下的 host文件,将该文件拷贝到其他盘,修改后替换原文件即可

添加如下内容

127.0.0.1       a.com127.0.0.1       b.com

前端index.jsp代码 修改访问的服务的地址

<%@ page contentType="text/html;charset=UTF-8" language="java" %>            

在浏览器中访问a.com ,因为要发请求给

1593099295180

2.3 跨域访问支持

在接口所在的方法或者类上加@CrossOrigin注解

//使用@CrossOrigin开启跨域访问//标注在处理器方法上方表示该方法支持跨域访问//标注在处理器类上方表示该处理器类中的所有处理器方法均支持跨域访问package cn.itcast.controller;import cn.itcast.domain.User;import org.springframework.format.annotation.DateTimeFormat;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.CrossOrigin;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Map;@Controller@RequestMapping("/user")@CrossOriginpublic class UserController {
@RequestMapping("/ajax") @ResponseBody public Map
ajax(@RequestBody List
users){
System.out.println(users); HashMap
map = new HashMap<>(); map.put("status","success"); return map; }}

在这里插入图片描述

3 拦截器

3.1 拦截器Interceptor

请求处理过程解析

image-20200427164038103

概念和作用

是一种动态拦截方法调用的机制

作用

1.在指定的方法调用前后执行预先设定后的的代码

2.阻止原始方法的执行

核心原理:AOP思想

拦截器链:多个拦截器按照一定的顺序,对原始被调用功能进行增强

拦截器VS过滤器

归属不同: Filter属于Servlet技术, Interceptor属于SpringMVC技术

拦截内容不同: Filter对所有访问进行增强, Interceptor仅针对SpringMVC的访问进行增强
image-20200427164512745

3.2 自定义拦截器开发过程

第一步:实现HandlerInterceptor接口

//自定义拦截器需要实现HandleInterceptor接口public class MyInterceptor implements HandlerInterceptor {
//处理器运行之前执行 @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("前置运行----a1"); //返回值为false将拦截原始处理器的运行 //如果配置多拦截器,返回值为false将终止当前拦截器后面配置的拦截器的运行 return true; } //处理器运行之后执行 @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("后置运行----b1"); } //所有拦截器的后置执行全部结束后,执行该操作 @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("完成运行----c1"); } //三个方法的运行顺序为 preHandle -> postHandle -> afterCompletion //如果preHandle返回值为false,三个方法仅运行preHandle}

第二步:配置拦截器

注意:配置顺序为先配置执行位置,后配置执行类

3.3 拦截器执行流程

image-20200427164840131

3.4 拦截器配置与方法参数

3.4.1 前置处理方法

原始方法之前运行

public boolean preHandle(HttpServletRequest request,                         HttpServletResponse response,                         Object handler) throws Exception {
System.out.println("preHandle"); return true;}
  • 参数
    request:请求对象
    response:响应对象
    handler:被调用的处理器对象,本质上是一个方法对象,对反射中的Method对象进行了再包装
  • 返回值
    返回值为false,被拦截的处理器将不执行

3.4.2 后置处理方法

原始方法运行后运行,如果原始方法被拦截,则不执行

public void postHandle(HttpServletRequest request,                       HttpServletResponse response,                       Object handler,                       ModelAndView modelAndView) throws Exception {
System.out.println("postHandle");}

参数

modelAndView:如果处理器执行完成具有返回结果,可以读取到对应数据与页面信息,并进行调整

3.4.3 完成处理方法

拦截器最后执行的方法,无论原始方法是否执行

public void afterCompletion(HttpServletRequest request,                            HttpServletResponse response,                            Object handler,                            Exception ex) throws Exception {
System.out.println("afterCompletion");}

参数

ex:如果处理器执行过程中出现异常对象,可以针对异常情况进行单独处理

3.5 拦截器配置项

3.6 多拦截器配置

image-20200427171422781

责任链模式

责任链模式是一种行为模式
特征:着一条预先设定的任务链顺序执行,每个节点具有独立的工作任务

优势:

独立性:只关注当前节点的任务,对其他任务直接放行到下一节点
隔离性:具备链式传递特征,无需知晓整体链路结构,只需等待请求到达后进行处理即可
灵活性:可以任意修改链路结构动态新增或删减整体链路责任
解耦:将动态任务与原始任务解耦

弊端:

链路过长时,处理效率低下
可能存在节点上的循环引用现象,造成死循环,导致系统崩溃

4 异常处理

在这里插入图片描述

系统的Dao、Service、Controller出现都通过throws Exception向上抛出,最后由SpringMVC前端控制器交由异常处理器进行异常处理,如下图:

1593101330925

4.0 异常处理的方式

方式1(了解)

使用Spring MVC提供的简单异常处理器SimpleMappingExceptionResolver

1593101397999

方式2(XML了解)

第一步 创建异常处理器类实现HandlerExceptionResolver

1593101437662

第二步 编写异常页面error.jsp

1593101464016

第三步:把自定义异常处理类注册到springmvc框架中

1593101488122

第四步:控制器中编写会发生异常的代码

测试异常跳转

方式3(注解)掌握

package cn.itcast.exception;import org.springframework.stereotype.Component;import org.springframework.web.bind.annotation.ControllerAdvice;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;@ControllerAdvicepublic class ExceptionAdvice {
//该注解中设置要捕获的异常的类型,当前方法中编写异常的处理方式 @ExceptionHandler(RuntimeException.class) public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("/error.jsp"); modelAndView.addObject("msg","系统出错"); return modelAndView; }}

1593153998744

在这里插入图片描述

4.1 异常处理解决方案

如果是前后端分离需要传json数据,后端异常手动处理发送给前端,如果是纯后端就交给框架处理,返回页面消息即可!

  • 异常处理方案
    • 业务异常:
      发送对应消息传递给用户,提醒规范操作
    • 系统异常:
      发送固定消息传递给用户,安抚用户
      发送特定消息给运维人员,提醒维护
      记录日志
    • 其他异常:
      发送固定消息传递给用户,安抚用户
      发送特定消息给编程人员,提醒维护
      纳入预期范围内
      记录日志

4.2 自定义异常

1593102161185

//自定义异常继承RuntimeException,覆盖父类所有的构造方法public class BusinessException extends RuntimeException {
public BusinessException() {
} public BusinessException(String message) {
super(message); } public BusinessException(String message, Throwable cause) {
super(message, cause); } public BusinessException(Throwable cause) {
super(cause); } public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace); }}
  • 异常触发方式

    if(user.getName().trim().length()<4) {
    throw new BusinessException("用户名长度必须在2-4位之间,请重新输入! ");}
  • 通过自定义异常将所有的异常现象进行分类管理,以统一的格式对外呈现异常消息

5 实用技术

5.1 文件上传下载

前端页面

必表单中的三个注意事项

  • input的type必须是file类型
  • 表单的提交方式必须是post
  • 表单的enctype属性的值必须是”multipart/form-data”

页面表单代码

1.类型必须是multipart/form-data,上传的标签name名字必须与后台接收的变量名一致否则传不上去
1593102313554

1593102324376

单文件上传

1.导入fileupload和common-io依赖

commons-fileupload
commons-fileupload
1.3.1
commons-io
commons-io
2.3

2.配置文件上传解析器

1593102410802

B表示Byte

1M=1024*1024
注意事项:bean的id值必须和我的保持一致,不然后台获取不到表单数据

3.编写控制器

1593102437307

1593102446579

多文件上传

页面代码

1593102484899

页面效果

1593102497607

控制器

1593102515834
在这里插入图片描述

1593102523368

总结

1.页面中的多个上传选项name要一致

2.后端接受文件上传数据时多文件使用数组接收
3.bean中标签id必须为multipartResolver

5.2 文件上传注意事项

  1. 文件命名问题, 获取上传文件名,并解析文件名与扩展名
  2. 文件名过长问题
  3. 文件保存路径
  4. 重名问题
@RequestMapping(value = "/fileupload")//参数中定义MultipartFile参数,用于接收页面提交的type=file类型的表单,要求表单名称与参数名相同public String fileupload(MultipartFile file,MultipartFile file1,MultipartFile file2, HttpServletRequest request) throws IOException {
System.out.println("file upload is running ..."+file); // MultipartFile参数中封装了上传的文件的相关信息 // System.out.println(file.getSize()); // System.out.println(file.getBytes().length); // System.out.println(file.getContentType()); // System.out.println(file.getName()); // System.out.println(file.getOriginalFilename()); // System.out.println(file.isEmpty()); //首先判断是否是空文件,也就是存储空间占用为0的文件 if(!file.isEmpty()){
//如果大小在范围要求内正常处理,否则抛出自定义异常告知用户(未实现) //获取原始上传的文件名,可以作为当前文件的真实名称保存到数据库中备用 String fileName = file.getOriginalFilename(); //设置保存的路径 String realPath = request.getServletContext().getRealPath("/images"); //保存文件的方法,指定保存的位置和文件名即可,通常文件名使用随机生成策略产生,避免文件名冲突问题 file.transferTo(new File(realPath,file.getOriginalFilename())); } //测试一次性上传多个文件 if(!file1.isEmpty()){
String fileName = file1.getOriginalFilename(); //可以根据需要,对不同种类的文件做不同的存储路径的区分,修改对应的保存位置即可 String realPath = request.getServletContext().getRealPath("/images"); file1.transferTo(new File(realPath,file1.getOriginalFilename())); } if(!file2.isEmpty()){
String fileName = file2.getOriginalFilename(); String realPath = request.getServletContext().getRealPath("/images"); file2.transferTo(new File(realPath,file2.getOriginalFilename())); } return "page.jsp";}

5.4 Restful风格配置

5.4.1 Rest

  • Rest( REpresentational State Transfer) 一种网络资源的访问风格,定义了网络资源的访问方式
    • 传统风格访问路径
      http://localhost/user/get?id=1
      http://localhost/deleteUser?id=1
    • Rest风格访问路径
      http://localhost/user/1
  • Restful是按照Rest风格访问网络资源
  • 优点
    隐藏资源的访问行为,通过地址无法得知做的是何种操作
    书写简化

5.4.2 Rest行为约定方式

GET(查询) http://localhost/user/1 GET

POST(保存) http://localhost/user POST
PUT(更新) http://localhost/user PUT
DELETE(删除) http://localhost/user DELETE
注意:上述行为是约定方式,约定不是规范,可以打破,所以称Rest风格,而不是Rest规范
在这里插入图片描述

5.4.3 Restful开发入门

在这里插入图片描述

在这里插入图片描述

//设置rest风格的控制器@RestController//设置公共访问路径,配合下方访问路径使用@RequestMapping("/user/")public class UserController {
//rest风格访问路径完整书写方式 @RequestMapping("/user/{id}") //使用@PathVariable注解获取路径上配置的具名变量,该配置可以使用多次 public String restLocation(@PathVariable Integer id){
System.out.println("restful is running ...."); return "success.jsp"; } //rest风格访问路径简化书写方式,配合类注解@RequestMapping使用 @RequestMapping("{id}") public String restLocation2(@PathVariable Integer id){
System.out.println("restful is running ....get:"+id); return "success.jsp"; } //接收GET请求配置方式 @RequestMapping(value = "{id}",method = RequestMethod.GET) //接收GET请求简化配置方式 @GetMapping("{id}") public String get(@PathVariable Integer id){
System.out.println("restful is running ....get:"+id); return "success.jsp"; } //接收POST请求配置方式 @RequestMapping(value = "{id}",method = RequestMethod.POST) //接收POST请求简化配置方式 @PostMapping("{id}") public String post(@PathVariable Integer id){
System.out.println("restful is running ....post:"+id); return "success.jsp"; } //接收PUT请求简化配置方式 @RequestMapping(value = "{id}",method = RequestMethod.PUT) //接收PUT请求简化配置方式 @PutMapping("{id}") public String put(@PathVariable Integer id){
System.out.println("restful is running ....put:"+id); return "success.jsp"; } //接收DELETE请求简化配置方式 @RequestMapping(value = "{id}",method = RequestMethod.DELETE) //接收DELETE请求简化配置方式 @DeleteMapping("{id}") public String delete(@PathVariable Integer id){
System.out.println("restful is running ....delete:"+id); return "success.jsp"; }}
HiddenHttpMethodFilter
org.springframework.web.filter.HiddenHttpMethodFilter
HiddenHttpMethodFilter
DispatcherServlet

开启SpringMVC对Restful风格的访问支持过滤器,即可通过页面表单提交PUT与DELETE请求

页面表单使用隐藏域提交请求类型,参数名称固定为_method,必须配合提交类型method=post使用

  • Restful请求路径简化配置方式

    @RestControllerpublic class UserController {
    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE) public String restDelete(@PathVariable String id){
    System.out.println("restful is running ....delete:"+id); return "success.jsp"; }}

5.5 postman工具安装与使用

postman 是 一款可以发送Restful风格请求的工具,方便开发调试。首次运行需要联网注册

在这里插入图片描述

在这里插入图片描述

面试题

spring里面用到了哪些设计模式?

  1. 代理模式

  2. 工厂模式

  3. 单例模式

  4. 责任链模式

  5. 模板模式: 模版方法模式定义了一个操作中的算法骨架,而将一些步骤延迟到子类中,使得子类可以不改变一个算法的结构,就可以重定义该算法的某些特定步骤

    https://www.cnblogs.com/Adam-Ye/p/13638784.html

拦截器和过滤器的区别

过滤器是web核心三大组件之一,可以增强所有的请求和响应。

拦截器是springmvc的一个特有功能,理论上只能增强处理器(处理器:controller中的方法),底层是AOP技术。

上一篇:SpringMVC进阶-校验框架
下一篇:SpringMVC入门-注解配置和请求传参和响应数据

发表评论

最新留言

初次前来,多多关照!
[***.217.46.12]2025年04月14日 08时25分20秒