zoukankan      html  css  js  c++  java
  • springmvc学习日志四

    一、回顾

      1.文件上传

        1.1引入fileupload的jar包

        1.2在springmvc的配置文件中引入CommonsMutilpartResolver文件上传解析器

        1.3在控制层在写入代码

      2.拦截器

        2.1创建一个类实现HandlerInterceptor接口

        2.2在springmvc配置文件中配置该拦截器

      3.数据校验

        3.1引入Hibernate-validate的jar包

        3.2在相应的实体类属性上加上校验注解

        3.3在控制层接受参数的地方加上 @Valid 如果参数不符合校验 把错误封装到BindingResult对象中

    二、restful风格

    特点:

    1、每一个URI代表1种资源;
    2、客户端使用GET、POST、PUT、DELETE4个表示操作方式的动词对服务端资源进行操作:GET用来获取资源,POST用来新建资源(也可以用于更新资源),PUT用来更新资源,DELETE用来删除资源;
    3、通过操作资源的表现形式来操作资源;

    请求地址http://localhost:8080/Springmvc-04/user/6

    设置restful风格无需在添加jar包,只需在之前示例的基础上设置请求处理方式

    建立实体类

    public class User {
          private String name;
          private String password;
          private String phone;
    }

    建立jsp页面,向控制层传输数据和提交方式

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    <script type="text/javascript" src="/springmvc4/js/jquery-3.2.1.min.js"></script>
    <script type="text/javascript">
         $.ajax({
            url:"user/1",
            type:"post",
            data:{
                _method:"delete",
                "name":"张三",
                "password":"123456",
                "phone":"15295730918"
            },
            success:function(result){
                //alert(result);
                location.href="/springmvc4/index.jsp";
            }
         });
    </script>
    </head>
    <body>
    
    </body>
    </html>

    1.当请求提交方式为get时,建立Controller类,并根据请求的方式调用相应的方法

    @Controller
    @RequestMapping("user")
    public class UserController {
            
        //restFul---->user/1
        //method:表示方法处理get请求
        //把1赋值给{uid}了,uid可自定义 
        @RequestMapping(value="{uid}", method=RequestMethod.GET) //查询操作
        public String findById(@PathVariable("uid") int id) {//@PathVariable把uid的值赋值给形参数
            System.out.println("====findId===="+id);
            return "index";
        }
    }

    2.当请求提交的方式为post、put和delete时

    首先在web.xml中配置过滤器

    <!-- 
              把post请求转化为PUT和DELETE请求
              使用_method表示真正的提交方式
       -->
      <filter>
             <filter-name>hiddenHttpMethodFilte</filter-name>
             <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
        </filter>
        <filter-mapping>
            <filter-name>hiddenHttpMethodFilte</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>

    再建立Controller类,在类中根据不同的方式调用不同的方法

    @Controller
    @RequestMapping("user")
    public class UserController {
        
        @RequestMapping( method=RequestMethod.POST) //添加操作
        public String insertUser(User user) {
            System.out.println("1==="+user);
            return "index";
        }
        //springmvc提供了一个过滤,该过滤器可以把post请求转化为put和delete请求
        @RequestMapping( method=RequestMethod.PUT) //修改操作
        //用于返回Ajax对象,一定要加,当使用springmvc提供的可以把post请求转化为put和delete请求的过滤器时
        @ResponseBody  
        public String updateUser(User user) {
            System.out.println(user+"update");
            return "index";//也可返回json对象
        }
    
        //如果web.xml中配置为*.do,那么只在url地址栏中加.do,这里的value中不需要加.do
        @RequestMapping(value="{id}" ,method=RequestMethod.DELETE) //删除操作
        @ResponseBody 
        public String deleteUser(@PathVariable int id) {
            System.out.println(id+"=====delete");
            return "index";
        }
        
    }

     三、springmvc异常处理

    1.局部处理。当在一个类中有异常时,可在类中直接进行异常处理

    @Controller
    @RequestMapping("user")
    public class UserController {
            
        //restFul---->user/1
        //method:表示方法处理get请求
        //把1赋值给{uid}了,uid可自定义 
        @RequestMapping(value="{uid}", method=RequestMethod.GET) //查询操作
        public String findById(@PathVariable("uid") int id) {//@PathVariable把uid的值赋值给形参数
            System.out.println("====findId===="+id);
            // int a=10/0; //除数不能为零
            if(id==0) {
                throw new RuntimeException("请求的参数有错误");
            }
            return "index";
        }
        @ExceptionHandler //当该类发生异常时由该方法来处理,该方法的Exception会接受异常对象
        public ModelAndView error(Exception exception) {
            ModelAndView mv=new ModelAndView();
            mv.addObject("error", exception.getMessage());
            mv.setViewName("error");
            return mv;
        }
        

    2.定义一个全局异常类。当多个类中出现异常时

    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.servlet.ModelAndView;
    
    @ControllerAdvice 
    public class ExceptionController {
            
        @ExceptionHandler //当该类发生异常时由该方法来处理,该方法的Exception会接受异常对象
        public ModelAndView error(Exception exception) {
            ModelAndView mv=new ModelAndView();
            mv.addObject("error", exception.getMessage());
            mv.setViewName("error");
            return mv;
        }
    }

    3.用于专门显示错误信息的jsp页面

    <%@ page language="java" contentType="text/html; charset=UTF-8"
        pageEncoding="UTF-8" isErrorPage="true"%>
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Insert title here</title>
    </head>
    <body>
         ${error }
    </body>
    </html>

    四、spingmvc有哪些注解

    @Controller : 标注该类为控制层类。
     @RequestMappint: 标注请求的地址
     @ResponseBody: 把java对象转化为json对象。
     @Valid: 标注校验该数据
     @PathVariable: 接受uri地址的值赋给方法的参数
     @SessionAttributes
    @RequestParam
    @ExceptionAdvice: 标注一个类为异常处理类
    @ExceptionHandler: 标注一个方法为异常处理的方法。
    @InitBinder: 处理日期时间参数
  • 相关阅读:
    如何理解javaScript对象?
    web移动端开发技巧与注意事项汇总
    javaScript基础语法(上)
    css选择器的使用详解
    css属性兼容主流浏览器
    前端开发必备站点汇总
    Highchart基础教程-图表配置
    Highchart基础教程-图表的主要组成
    Highcharts入门小示例
    Highcharts配置
  • 原文地址:https://www.cnblogs.com/sitian2050/p/11469181.html
Copyright © 2011-2022 走看看