springMVC:发送异步请求,接收异步请求,响应异步请求,跨域访问,自定义拦截器,拦截器执行流程,拦截器配置项,多拦截器配置,异常处理器,注解开发异常处理器,自定义异常,项目异常处理方案,文件上传,文件上传注意事项

 

  1.  
  • 能够阐述@RequestBody和@ResponseBody的作用

  • 能够运用@RequestBody和@ResponseBody实现异步交互开发

  • 能够阐述@RestController和@RestControllerAdvice注解的作用

  • 能够叙述跨域访问的概念

  • 能够总结跨域访问产生的问题

  • 能够运用@CrossOrigin注解解决跨域访问的问题

  • 能够描述REST风格URL的特性和运用的四种请求方式

  • 能够描述@PathVariable注解的作用

  • 能够使用Postman工具对SpringMVC基于REST风格URL的工程的测试

使用jQuery的ajax方法发送异步请求:

  1. <a href="javascript:void(0);" id="testAjax">访问controller</a>
  2. <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.3.1.min.js"></script>
  3. <script type="text/javascript">
  4. $(function(){
  5. $("#testAjax").click(function(){ //为id="testAjax"的组件绑定点击事件
  6. $.ajax({ //发送异步调用
  7. type:"POST", //请求方式: POST请求
  8. url:"ajaxController", //请求url
  9. data:'ajax message', //请求参数(也就是请求内容)
  10. dataType:"text", //响应正文类型
  11. contentType:"application/text", //请求正文的MIME类型
  12. });
  13. });
  14. });
  15. </script>

 

 名称: @RequestBody  类型: 形参注解  位置:处理器类中的方法形参前方  作用:将异步提交数据组织成标准请求参数格式,并赋值给形参  范例:

  1. @RequestMapping("/ajaxController")
  2. public String ajaxController(@RequestBody String message){
  3. System.out.println(message);
  4. return "page.jsp";
  5. }

 

检查pom.xml是否导入jackson的坐标

  1. <!--json相关坐标3个-->
  2. <dependency>
  3. <groupId>com.fasterxml.jackson.core</groupId>
  4. <artifactId>jackson-core</artifactId>
  5. <version>2.9.0</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>com.fasterxml.jackson.core</groupId>
  9. <artifactId>jackson-databind</artifactId>
  10. <version>2.9.0</version>
  11. </dependency>
  12. <dependency>
  13. <groupId>com.fasterxml.jackson.core</groupId>
  14. <artifactId>jackson-annotations</artifactId>
  15. <version>2.9.0</version>
  16. </dependency>

 

  • 通过JavaScript传递JSON格式数据到服务器

注意:请求数据格式与POJO中的属性对应

  1. public class User {
  2. private String name;
  3. private Integer age;
  4. //添加get,set方法
  5. }
  6. {"name":"Jock","age":39}
  7. //为id="testAjaxPojo"的组件绑定点击事件
  8. $("#testAjaxPojo").click(function(){
  9. $.ajax({
  10. type:"POST",
  11. url:"ajaxPojoToController",
  12. data:'{"name":"Jock","age":39}',
  13. dataType:"text",
  14. contentType:"application/json",
  15. });
  16. });

 

将@RequestBody注解添加到Pojo参数前方

  1. {"name":"Jock","age":39}
  1. @RequestMapping("/ajaxPojoToController")
  2. //如果处理参数是POJO,且页面发送的请求数据格式与POJO中的属性对应,@RequestBody注解可以自动映射对应请求数据到POJO中
  3. public String ajaxPojoToController(@RequestBody User user){
  4. System.out.println("controller pojo :"+user);
  5. return "page.jsp";
  6. }

 

  • 注解添加到集合参数前方时,封装的异步提交数据按照集合的存储结构进行关系映射 注意:页面发送的数据是JSON格式的对象数组

    1. [{"name":"Jock","age":39},{"name":"Jockme","age":40}]
    1. //为id="testAjaxList"的组件绑定点击事件
    1. $("#testAjaxList").click(function(){
    2. $.ajax({
    3. type:"POST",
    4. url:"ajaxListToController",
    5. data:'[{"name":"Jock","age":39},{"name":"Jockme","age":40}]',
    6. dataType:"text",
    7. contentType:"application/json",
    8. });
    9. });

     

    1.  
    1. @RequestMapping("/ajaxListToController")
    2. //如果处理参数是List集合且封装了POJO,且页面发送的数据是JSON格式的,数据将自动映射到集合参数中
    3. public String ajaxListToController(@RequestBody List<User> userList){
    4. System.out.println("controller list :"+userList);
    5. return "page.jsp";
    6. }

     

方法返回值为Pojo时,自动封装数据成json对象数据

  1. @RequestMapping("/ajaxReturnJson")
  2. @ResponseBody
  3. public User ajaxReturnJson(){
  4. System.out.println("controller return json pojo...");
  5. User user = new User();
  6. user.setName("Jockme");
  7. user.setAge(40);
  8. return user;
  9. }

 

方法返回值为List时,自动封装数据成json对象数组数据

  1. @RequestMapping("/ajaxReturnJsonList")
  2. @ResponseBody
  3. //基于jackon技术,使用@ResponseBody注解可以将返回的保存POJO对象的集合转成json数组格式数据
  4. public List ajaxReturnJsonList(){
  5. System.out.println("controller return json list...");
  6. User user1 = new User();
  7. user1.setName("Tom");
  8. user1.setAge(3);
  9. User user2 = new User();
  10. user2.setName("Jerry");
  11. user2.setAge(5);
  12. ArrayList al = new ArrayList();
  13. al.add(user1);
  14. al.add(user2);
  15. return al;
  16. }

 

  1. //为id="testAjaxReturnJson"的组件绑定点击事件
  1. $("#testAjaxReturnJson").click(function(){
  2. //发送异步调用
  3. $.ajax({
  4. type:"POST",
  5. url:"ajaxReturnJson",
  6. //回调函数
  7. success:function(data){
  8. console.log(data);
  9. alert(JSON.stringify(data));
  10. // alert(data['name']+" , "+data['age']);
  11. }
  12. });
  13. });

 

  1.  

 

  • 域名:https://www.taobao.com -> https://140.205.94.189

  • DNS:域名系统,记录了域名和IP的映射关系

  • 在淘宝网站上使用JS访问京东网站

  • 跨域访问:通过域名A下的操作访问域名B下的资源时 

     

     

  • 跨域访问时,会出现无法访问的现象 

  •  

     

  • 为当前主机添加备用域名:C:\Windows\System32\drivers\etc

    • 修改windows安装目录中的hosts文件:欺骗浏览器将www.jock.com映射到127.0.0.1

      1. 127.0.0.1 www.jock.com
    • 格式: ip 域名

  • 动态刷新DNS

    • 命令: ipconfig /displaydns

    • 命令: ipconfig /flushdns

发送跨域请求:

  1. //为id="testCross"的组件绑定点击事件
  2. $("#testCross").click(function(){
  3. //发送异步调用
  4. $.ajax({
  5. type:"POST",
  6. // url:"cross",
  7. url:"http://www.jock.com/cross",
  8. // url:"http://localhost/cross",
  9. //回调函数
  10. success:function(data){
  11. alert("跨域调用信息反馈:"+data['name']+" , "+data['age']);
  12. }
  13. });
  14. });

 

 名称: @CrossOrigin  类型: 方法注解 、 类注解  位置:处理器类中的方法上方 或 类上方  作用:设置当前处理器方法/处理器类中所有方法支持跨域访问  范例:

  1. @RequestMapping("/cross")
  2. @ResponseBody
  3. //使用@CrossOrigin开启跨域访问
  4. //标注在处理器方法上方表示该方法支持跨域访问
  5. //标注在处理器类上方表示该处理器类中的所有处理器方法均支持跨域访问
  6. @CrossOrigin
  7. public User cross(HttpServletRequest request){
  8. System.out.println("controller cross..."+request.getRequestURL());
  9. User user = new User();
  10. user.setName("Jockme");
  11. user.setAge(39);
  12. return user;
  13. }

 

 

 

拦截器( Interceptor)是一种动态拦截方法调用的机制。 

 

 

 作用:

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

  2. 阻止原始方法的调用

 核心原理:AOP思想

 请求处理过程解析

 

 

 

 

 

 

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

 拦截器VS过滤器区别

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

  2. 拦截内容不同: Filter对所有访问进行增强, 拦截器仅针对SpringMVC的访问进行增强 

 

 

 

 

 

  • 制作拦截功能类(通知):实现HandlerInterceptor接口

    1. //自定义拦截器需要实现HandleInterceptor接口
    2. public class MyInterceptor implements HandlerInterceptor {
    3. //处理器运行之前执行
    4. @Override
    5. public boolean preHandle(HttpServletRequest request,
    6. HttpServletResponse response,
    7. Object handler) throws Exception {
    8. System.out.println("前置运行----a1");
    9. //返回值为false将拦截原始处理器的运行
    10. //如果配置多拦截器,返回值为false将终止当前拦截器后面配置的拦截器的运行
    11. return true;
    12. }
    13. //处理器运行之后执行
    14. @Override
    15. public void postHandle(HttpServletRequest request,
    16. HttpServletResponse response,
    17. Object handler,
    18. ModelAndView modelAndView) throws Exception {
    19. System.out.println("后置运行----b1");
    20. }
    21. //所有拦截器的后置执行全部结束后,执行该操作
    22. @Override
    23. public void afterCompletion(HttpServletRequest request,
    24. HttpServletResponse response,
    25. Object handler,
    26. Exception ex) throws Exception {
    27. System.out.println("完成运行----c1");
    28. }
    29. //三个方法的运行顺序为 preHandle -> postHandle -> afterCompletion
    30. //如果preHandle返回值为false,三个方法仅运行preHandle
    31. }

     

  • 编写Controller

    1. @Controller
    2. public class InterceptorController {
    3. @RequestMapping("/handleRun")
    4. public String handleRun() {
    5. System.out.println("业务处理器运行------------main");
    6. return "page.jsp";
    7. }
    8. }

     

  • 配置拦截器的执行位置(类似切入点)

    1. <!--开启拦截器使用-->
    2. <mvc:interceptors>
    3. <!--开启具体的拦截器的使用,可以配置多个-->
    4. <mvc:interceptor>
    5. <!--设置拦截器的拦截路径-->
    6. <mvc:mapping path="/handleRun"/>
    7. <!--指定具体的拦截器类-->
    8. <bean class="com.itheima.interceptor.MyInterceptor"/>
    9. </mvc:interceptor>
    10. </mvc:interceptors>

     

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

 

 

  • 三个方法的运行顺序为 preHandle -> postHandle -> afterCompletion

  • 如果preHandle返回值为false,三个方法仅运行preHandle

 

原始方法之前运行

  1. public boolean preHandle(HttpServletRequest request,
  2. HttpServletResponse response,
  3. Object handler) throws Exception {
  4. System.out.println("preHandle");
  5. return true;
  6. }

 

  • 参数  request:请求对象  response:响应对象  handler:被调用的处理器对象,本质上是一个方法对象,对反射中的Method对象进行了再包装

  • 返回值

     返回值为false,被拦截的处理器将不执行

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

  1. public void postHandle(HttpServletRequest request,
  2. HttpServletResponse response,
  3. Object handler,
  4. ModelAndView modelAndView) throws Exception {
  5. System.out.println("postHandle");
  6. System.out.println(modelAndView.getViewName());
  7. modelAndView.setViewName("page2.jsp");
  8. }

 

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

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

  1. public void afterCompletion(HttpServletRequest request,
  2. HttpServletResponse response,
  3. Object handler,
  4. Exception ex) throws Exception {
  5. System.out.println("afterCompletion");
  6. }

 

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

  1. <mvc:interceptor>
  2. <!--设置拦截器的拦截路径,支持*通配-->
  3. <!--/* 表示拦截所有/开头的映射-->
  4. <!--匹配/user,但不能匹配/user/add、/user/del-->
  5. <!--/** 表示拦截所有映射-->
  6. <!--匹配/user、/user/add、/user/del-->
  7. <!--/user/* 表示拦截所有/user/开头的映射-->
  8. <!--/user/add* 表示拦截所有/user/开头,且具体映射名称以add开头的映射-->
  9. <!--/user/*All 表示拦截所有/user/开头,且具体映射名称以All结尾的映射-->
  10. <mvc:mapping path="/**"/>
  11. <!--设置拦截排除的路径-->
  12. <mvc:exclude-mapping path="/b*"/>
  13. <!--指定具体的拦截器类-->
  14. <bean class="com.itheima.interceptor.MyInterceptor"/>
  15. </mvc:interceptor>

 

拦截器完整执行过程如下所示:

 

 

多拦截配置使用多个mvc:interceptor

  1. <mvc:interceptors>
  2. <mvc:interceptor>
  3. <mvc:exclude-mapping path="/*"/>
  4. <!--指定具体的拦截器类-->
  5. <bean class="com.itheima.interceptor.MyInterceptor1"/>
  6. </mvc:interceptor>
  7. <!--配置多个拦截器,配置顺序即为最终运行顺序-->
  8. <mvc:interceptor>
  9. <mvc:mapping path="/*"/>
  10. <bean class="com.itheima.interceptor.MyInterceptor2"/>
  11. </mvc:interceptor>
  12. <mvc:interceptor>
  13. <mvc:mapping path="/*"/>
  14. <bean class="com.itheima.interceptor.MyInterceptor3"/>
  15. </mvc:interceptor>
  16. </mvc:interceptors>

 

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

 

 

责任链模式  责任链模式是一种行为模式  特征:沿着一条预先设定的任务链顺序执行,每个节点具有独立的工作任务  优势: 独立性:只关注当前节点的任务,对其他任务直接放行到下一节点 隔离性:具备链式传递特征,无需知晓整体链路结构,只需等待请求到达后进行处理即可 灵活性:可以任意修改链路结构动态新增或删减整体链路责任 解耦:将动态任务与原始任务解耦

 弊端: 链路过长时,处理效率低下 如果节点对象存在循环引用时,会造成死循环,导致系统崩溃

 

1.实现HandlerExceptionResolver接口(异常处理器)

  1. @Component
  2. public class ExceptionResolver implements HandlerExceptionResolver {
  3. public ModelAndView resolveException(HttpServletRequest request,
  4. HttpServletResponse response,
  5. Object handler,
  6. Exception ex) {
  7. System.out.println("异常处理器正在执行中");
  8. ModelAndView modelAndView = new ModelAndView();
  9. //定义异常现象出现后,反馈给用户查看的信息
  10. modelAndView.addObject("msg","出错啦! ");
  11. //定义异常现象出现后,反馈给用户查看的页面
  12. modelAndView.setViewName("error.jsp");
  13. return modelAndView;
  14. }
  15. }

 

2.根据异常的种类不同,进行分门别类的管理,返回不同的信息

  1. @Component
  2. public class ExceptionResolver implements HandlerExceptionResolver {
  3. @Override
  4. public ModelAndView resolveException(HttpServletRequest request,
  5. HttpServletResponse response,
  6. Object handler,
  7. Exception ex) {
  8. System.out.println("my exception is running ...."+ex);
  9. ModelAndView modelAndView = new ModelAndView();
  10. if( ex instanceof NullPointerException){
  11. modelAndView.addObject("msg","空指针异常");
  12. }else if ( ex instanceof ArithmeticException){
  13. modelAndView.addObject("msg","算数运算异常");
  14. }else{
  15. modelAndView.addObject("msg","未知的异常");
  16. }
  17. modelAndView.setViewName("error.jsp");
  18. return modelAndView;
  19. }
  20. }

 

3.在Controller中模拟不同的异常进行测试

  1. //http://localhost/save
  2. @RequestMapping("/save")
  3. @ResponseBody
  4. public String save() throws Exception {
  5. System.out.println("user controller save is running ...");
  6. //模拟业务层发起调用产生了异常
  7. //除0算术异常
  8. //int i = 1/0;
  9. //空指针异常
  10. //String str = null;
  11. //str.length();
  12. return "";
  13. }

 

 

上述异常处理器中包含太多if else逻辑判断,需要进行优化:

 

 

  • 使用注解实现异常分类管理  名称: @ControllerAdvice  类型: 类注解  位置:异常处理器类上方  作用:设置当前类为异常处理器类  范例:

  1. @ControllerAdvice
  2. public class ExceptionAdvice {
  3. }
  4. 使用注解实现异常分类管理 名称: @ExceptionHandler 类型: 方法注解 位置:异常处理器类中针对指定异常进行处理的方法上方 作用:设置指定异常的处理方式 说明:处理器方法可以设定多个 范例:
  5. @ExceptionHandler(NullPointerException.class)
  6. @ResponseBody
  7. public String doNullException(HttpServletResponse response, Exception ex) throws JsonProcessingException {
  8. return "Null point";
  9. }
  10. @ExceptionHandler(ArithmeticException.class)
  11. @ResponseBody
  12. public String doArithmeticException(Exception e){
  13. return "ArithmeticException";
  14. }
  15. @ExceptionHandler(Exception.class)
  16. @ResponseBody
  17. public String doException(Exception ex){
  18. return "all";
  19. }

 

 

扩展知识

1.如果标记了@ControllerAdvice类中的每个方法都使用了@ResponseBody,可以采用如下的简写方式:

 

 

  1. //@ResponseBody
  2. //@ControllerAdvice
  3. @RestControllerAdvice //= @ControllerAdvice + @ResponseBody
  4. public class ExceptionAdvice {
  5. }

 

@RestControllerAdvice = @ControllerAdvice + @ResponseBody

2.@ResponseBody返回中文字符串乱码,在spring-mvc.xml配置转换器编码:

  1. <mvc:annotation-driven>
  2. <mvc:message-converters>
  3. <bean class="org.springframework.http.converter.StringHttpMessageConverter">
  4. <constructor-arg value="UTF-8" />
  5. </bean>
  6. </mvc:message-converters>
  7. </mvc:annotation-driven>

 

 

  • 异常处理方案

    • 业务异常:  发送对应消息传递给用户,提醒规范操作

    • 系统异常:  发送固定消息传递给用户,安抚用户  发送特定消息给运维人员,提醒维护  记录日志

    • 其他异常:  发送固定消息传递给用户,安抚用户  发送特定消息给编程人员,提醒维护

      • 纳入预期范围内

       记录日志

  • 自定义BusinessException

    1. //自定义异常继承RuntimeException,覆盖父类所有的构造方法
    2. public class BusinessException extends RuntimeException {
    3. public BusinessException() {
    4. }
    5. public BusinessException(String message) {
    6. super(message);
    7. }
    8. public BusinessException(String message, Throwable cause) {
    9. super(message, cause);
    10. }
    11. public BusinessException(Throwable cause) {
    12. super(cause);
    13. }
    14. public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
    15. super(message, cause, enableSuppression, writableStackTrace);
    16. }
    17. }

     

  • 自定义SystemException

    1. //自定义异常继承RuntimeException,覆盖父类所有的构造方法
    2. public class SystemException extends RuntimeException {
    3. public SystemException() {
    4. }
    5. public SystemException(String message) {
    6. super(message);
    7. }
    8. public SystemException(String message, Throwable cause) {
    9. super(message, cause);
    10. }
    11. public SystemException(Throwable cause) {
    12. super(cause);
    13. }
    14. public SystemException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
    15. super(message, cause, enableSuppression, writableStackTrace);
    16. }
    17. }

     

     

  • 在UserControll中模拟触发异常

    1. //http://localhost/ajax.jsp
    2. @RequestMapping("/save")
    3. @ResponseBody
    4. public String save(@RequestBody User user) throws Exception {
    5. System.out.println("user controller save is running ...");
    6. //对用户的非法操作进行判定,并包装成异常对象进行处理,便于统一管理
    7. if(user.getName().trim().length() < 8){
    8. throw new BusinessException("对不起,用户名长度不满足要求,请重新输入!");
    9. }
    10. if(user.getAge() < 0){
    11. throw new BusinessException("对不起,年龄必须是0到100之间的数字!");
    12. }
    13. if (user.getAge() > 100) {
    14. throw new SystemException("我是系统异常,不能给用户看!");
    15. }
    16. if (true) {
    17. throw new RuntimeException("test");
    18. }
    19. }

     

  • 通过自定义异常将所有的异常现象进行分类管理,以统一的格式对外呈现异常消息

    1. @RestControllerAdvice //= @ControllerAdvice + @ResponseBody
    2. public class ProjectExceptionAdvice {
    3. @ExceptionHandler(BusinessException.class)
    4. public String doBusinessException(Exception ex){
    5. //业务异常出现的消息要发送给用户查看
    6. return ex.getMessage();
    7. }
    8. @ExceptionHandler(SystemException.class)
    9. public String doSystemException(Exception ex){
    10. System.out.println(ex.getMessage());
    11. //系统异常出现的消息不要发送给用户查看,发送统一的信息给用户看
    12. return "服务器出现问题,请联系管理员!";
    13. //实际的问题现象应该传递给redis服务器,运维人员通过后台系统查看
    14. //redisTemplate.opsForvalue.set("msg", ex.getMessage());
    15. }
    16. @ExceptionHandler(Exception.class)
    17. public String doException(Exception ex){
    18. //将ex堆栈信息保存起来
    19. ex.printStackTrace();
    20. return "太热情,请稍候……";
    21. }

     

 

  • 上传文件过程分析

     

     

  • MultipartResolver接口

    • MultipartResolver接口定义了文件上传过程中的相关操作,并对通用性操作进行了封装

    • MultipartResolver接口底层实现类CommonsMultipartResovler

    • CommonsMultipartResovler并未自主实现文件上传下载对应的功能,而是调用了apache的文件上传下载组件

    • 第一步:引入commons-fileupload坐标

      1. <dependency>
      2. <groupId>commons-fileupload</groupId>
      3. <artifactId>commons-fileupload</artifactId>
      4. <version>1.4</version>
      5. </dependency>

       

    • 第二步:编写页面表单

      1. <form action="/fileupload" method="post" enctype="multipart/form-data">
      2. 上传LOGO: <input type="file" name="file"/><br/>
      3. <input type="submit" value="上传"/>
      4. </form>

       

    • 第三步:SpringMVC配置 CommonsMultipartResolver

      1. <!--配置文件上传处理器-->
      2. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
      3. <property name="maxUploadSize" value="1024000000"/>
      4. </bean>

       

    • 第四步:在Controller中保存上传的文件

      1. @RequestMapping(value = "/fileupload")
      2. public String fileupload(MultipartFile file) throws IOException {
      3. file.transferTo(new File("file.png"));
      4. return "page.jsp";
      5. }

       

  1. 文件命名问题, 获取上传文件名,并解析文件名与扩展名

    1. file.getOriginalFilename();
  2. 文件名过长问题

  3. 重名问题

    1. //使用uuid做为文件名
    2. String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
    3. //获取文件后缀名
    4. String suffix = fileName.substring(fileName.lastIndexOf("."));
    5. //以uuid+文件后缀名保存文件
    6. file.transferTo(new File(realPath, uuid + suffix));

     

  4. 文件保存路径

    1. ServletContext context = request.getServletContext();
    2. String basePath = context.getRealPath("/images");
    3. File file = new File(basePath+"/");
    4. if(!file.exists()) file.mkdirs();

     

 

同时上传多个文件:

  1. <form action="/fileupload" method="post" enctype="multipart/form-data">
  2. <%--文件上传表单的name属性值一定要与controller处理器中方法的参数对应,否则无法实现文件上传--%>
  3. 上传LOGO:<input type="file" name="file"/><br/>
  4. 上传照片:<input type="file" name="file1"/><br/>
  5. 上传任意文件:<input type="file" name="file2"/><br/>
  6. <input type="submit" value="上传"/>
  7. </form>

 

完整代码:

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

 

 GET(查询) http://localhost/user/1 GET  POST(保存) http://localhost/user POST  PUT(更新) http://localhost/user/1 PUT  DELETE(删除) http://localhost/user/1 DELETE

注意:上述行为是约定方式,约定不是规范,可以打破,所以称Rest风格,而不是Rest规范

 

查询id=100的用户信息两种实现方式:

  1. //@Controller
  2. //@ResponseBody
  3. //设置rest风格的控制器
  4. @RestController //= @Controller + @ResponseBody
  5. //设置公共访问路径,配合方法上的访问路径使用
  6. @RequestMapping("/user")
  7. public class UserController {
  8. //第一种获取请求参数:?id=xx&age=
  9. //http://localhost/user/getUser?id=100
  10. @RequestMapping("/getUser")
  11. public String get(int id) {
  12. System.out.println("running ....get:"+id);
  13. return "success";
  14. }
  15. //第二种获取请求参数:/user/100
  16. //查询 http://localhost/user/100
  17. @GetMapping("/{id}")
  18. public String restGet(@PathVariable int id) {
  19. System.out.println("restful is running ....get:"+id);
  20. return "success.jsp";
  21. }
  22. }

 

四种请求方式:GET, POST, PUT, DELETE

 

 

发送PUT, DELETE请求的两种方式:

第一种方式:使用页面form表单提交PUT与DELETE请求

  • 开启SpringMVC对RESTful风格的访问支持过滤器

    1. <!--配置拦截器,解析请求中的参数_method,否则无法发起PUT请求与DELETE请求,配合页面表单使用-->
    2. <filter>
    3. <filter-name>HiddenHttpMethodFilter</filter-name>
    4. <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    5. </filter>
    6. <filter-mapping>
    7. <filter-name>HiddenHttpMethodFilter</filter-name>
    8. <servlet-name>DispatcherServlet</servlet-name>
    9. </filter-mapping>

     

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

    1. <form action="/user/1" method="post">
    2. <input type="hidden" name="_method" value="PUT"/>
    3. <input type="submit"/>
    4. </form>

     

扩展知识

第二种方式:使用ajax发送PUT, DELETE请求(常用)

  1. <%@page pageEncoding="UTF-8" language="java" contentType="text/html;UTF-8" %>
  2. <a href="javascript:void(0);" id="testPut">测试PUT提交</a><br/>
  3. <a href="javascript:void(0);" id="testDelete">测试DELETE提交</a><br/>
  4. <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-3.3.1.min.js"></script>
  5. <script type="text/javascript">
  6. $(function () {
  7. $("#testPut").click(function(){
  8. $.ajax({
  9. type:"PUT",
  10. url:"/user/1",
  11. success:function(data){
  12. window.location = data;
  13. }
  14. });
  15. });
  16. $("#testDelete").click(function(){
  17. $.ajax({
  18. type:"DELETE",
  19. url:"/user/2",
  20. success:function(data){
  21. window.location = data;
  22. }
  23. });
  24. });
  25. });
  26. </script>

 

第三种方式:使用Postman发送PUT, DELETE请求

  1. Restful请求路径简化配置方式 : @RestController = @Controller + @ResponseBody 

 

 

  1. 完整的简化后代码,@RestController = @Controller + @Response

    1. //设置rest风格的控制器
    2. @RestController
    3. //设置公共访问路径,配合下方访问路径使用
    4. @RequestMapping("/user")
    5. public class UserController {
    6. //接收GET请求简化配置方式
    7. @GetMapping("/{id}")
    8. public String get(@PathVariable Integer id){
    9. System.out.println("restful is running ....get:"+id);
    10. return "success.jsp";
    11. }
    12. //接收POST请求简化配置方式
    13. @PostMapping("/{id}")
    14. public String post(@PathVariable Integer id){
    15. System.out.println("restful is running ....post:"+id);
    16. return "success.jsp";
    17. }
    18. //接收PUT请求简化配置方式
    19. @PutMapping("/{id}")
    20. public String put(@PathVariable Integer id){
    21. System.out.println("restful is running ....put:"+id);
    22. return "success.jsp";
    23. }
    24. //接收DELETE请求简化配置方式
    25. @DeleteMapping("/{id}")
    26. public String delete(@PathVariable Integer id){
    27. System.out.println("restful is running ....delete:"+id);
    28. return "success.jsp";
    29. }
    30. }

     

     

postman 是一款可以发送Restful风格请求 的工具,方便开发调试

 

 

版权声明:本文为859630097com原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://www.cnblogs.com/859630097com/p/14538534.html