• 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;
        }
    }
  • 相关阅读:
    gulp + es6 + babel+ angular 搭建环境并实现简单的路由
    【SAS BASE】FORMAT Statement及PROC FORMAT
    【SAS BASE】PROC PRINT
    【SAS BASE】PROC SORT
    【SAS BASE】ARRAY语句及多变量简写
    【SAS BASE】SAS函数
    【SAS BASE】PROC CONTENTS与LABEL
    【SAS BASE】SAS格式、缺失值表示、命名规则及路径
    【SAS BASE】IMPORT过程(适用于CSV文件及其他分隔符文件)
    【SAS BASE】通过DATA步导入数据注意事项(适用于text、ASCII、sequential、flat文件)
  • 原文地址:https://www.cnblogs.com/1556553526qq-com/p/11471031.html
Copyright © 2020-2023  润新知