zoukankan      html  css  js  c++  java
  • springmvc的restful风格和异常处理

    1.Springmvc的restful风格:

    一般用ajax传过来时会对应相应的方式,该方式的作用是约定俗成的

    当传过来的方式为get时

    @RequestMapping(value="{id}",method=RequestMethod.GET)
        public String select(@PathVariable String id) {
            System.out.println("select"+id);
            return "index";
        }

    当传过来的方式为post时

    @RequestMapping(method=RequestMethod.POST)
        public String add(Users user) {
            System.out.println("add"+user);
            return "index";
        }

    当传过来的方式为put,delete时,需要在web.xml配置过滤器

     <filter>
          <filter-name>a</filter-name>
          <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
      </filter>
      <filter-mapping>
          <filter-name>a</filter-name>
          <url-pattern>/*</url-pattern>
      </filter-mapping>

    当传过来的方式为put时,ajax传过来方式还是需要田POST,但是传的参数里需要添加一个_method为PUT的参数

        @RequestMapping(method=RequestMethod.PUT)
        @ResponseBody
        public String update(Users user) {
            System.out.println("update"+user);
            return "index";
        }

    当传过来的方式为put时,ajax传过来方式还是需要是POST,但是传的参数里需要添加一个_method为delete的参数

    @RequestMapping(value="{mid}",method=RequestMethod.DELETE)
        @ResponseBody
        public String delete(@PathVariable("mid") int id) {
            System.out.println("delete"+id);
            return "index";
        }

    2.异常处理

    1.直接在本类进行处理

    @ExceptionHandler
        public ModelAndView excep(Exception exception,Model model) {
            ModelAndView mv=new ModelAndView();
            model.addAttribute("err", exception.getMessage());
            mv.setViewName("error");
            return mv;
        }

    2.全局异常处理,需要重新创建一个包下的一个类,所以springmvc配置文件包扫描需要扩大范围:

    package com.zhiyou.zt.exception;
    
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.servlet.ModelAndView;
    @ControllerAdvice
    public class Except {
        @ExceptionHandler
        public ModelAndView error(Exception exception) {
            ModelAndView mv=new ModelAndView();
            mv.addObject("error",exception.getMessage());
            mv.setViewName("error");
            return mv;
        }
    }
  • 相关阅读:
    Content-Type: multipart/form-data; boundary=
    -ErrorAction SilentlyContinue
    計量文件夾大小
    使用tesseract識別簡單的圖形碼
    适用于演示场景的修改网页内容
    分页展示与标题行
    查询当前脚本运行环境
    选项菜单
    tomcat创建虚拟目录存储图片
    springmvc记录(页面回显、url模板映射、自定义参数绑定、全局异常处理、文件上传、拦截器、hibernate validation数据校验、静态资源映射)
  • 原文地址:https://www.cnblogs.com/1556553526qq-com/p/11471031.html
Copyright © 2011-2022 走看看