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;
        }
    }
  • 相关阅读:
    【POJ1961 Period】【KMP】
    浅谈KMP算法
    【关于动态开点线段树】
    【POJ3349 Snowflake Snow Snowflakes】【Hash表】
    【NOI 2002 银河英雄传说】【带权并查集】
    路径问题
    group_concat函数详解
    MySQL中GROUP_CONCAT中排序
    怎么实现CSS限制字数,超出部份显示点点点.
    jsp去掉小数点
  • 原文地址:https://www.cnblogs.com/1556553526qq-com/p/11471031.html
Copyright © 2011-2022 走看看