springmvc 03(JSR303和拦截器)

目录

一,JSR303

        1.服务端验证

        2.步骤

二,拦截器

        1.简介

        2.拦截器与过滤器

                2.1 什么是过滤器

                2.2 拦截器和过滤器的区别

        3.拦截器案例

                3.1 使用原理


一,JSR303

        1.服务端验证

        2.步骤

1.导入pom.xml配置



    org.hibernate
    hibernate-validator
    6.0.7.Final




    4.0.0

    org.example
    springmvc
    1.0-SNAPSHOT
    war

    springmvc Maven Webapp
    
    http://www.example.com

    
        UTF-8
        1.8
        1.8
        3.7.0

        
        
        5.0.2.RELEASE
        
        3.4.5
        
        5.1.44
        
        5.1.2
        
        1.3.1
        
        2.1.1
        2.4.3
        
        2.9.1
        
        4.12
        4.0.0
        1.18.2
    

    
        
        
            org.springframework
            spring-context
            ${spring.version}
        
        
            org.springframework
            spring-orm
            ${spring.version}
        
        
            org.springframework
            spring-tx
            ${spring.version}
        
        
            org.springframework
            spring-aspects
            ${spring.version}
        
        
            org.springframework
            spring-web
            ${spring.version}
        
        
            org.springframework
            spring-test
            ${spring.version}
        

        
        
            org.mybatis
            mybatis
            ${mybatis.version}
        
        
        
            mysql
            mysql-connector-java
            ${mysql.version}
        
        
        
            com.github.pagehelper
            pagehelper
            ${pagehelper.version}
        
        
        
            org.mybatis
            mybatis-spring
            ${mybatis.spring.version}
        

        
        
            org.apache.commons
            commons-dbcp2
            ${commons.dbcp2.version}
        
        
            org.apache.commons
            commons-pool2
            ${commons.pool2.version}
        

        
        
        
            org.apache.logging.log4j
            log4j-core
            ${log4j2.version}
        
        
            org.apache.logging.log4j
            log4j-api
            ${log4j2.version}
        
        
        
            org.apache.logging.log4j
            log4j-web
            ${log4j2.version}
        

        
        
            junit
            junit
            ${junit.version}
            test
        
        
            javax.servlet
            javax.servlet-api
            ${servlet.version}
            provided
        
        
            org.projectlombok
            lombok
            ${lombok.version}
            provided
        

        
        
        
        
        
            org.apache.logging.log4j
            log4j-core
            2.9.1
        
        
            org.apache.logging.log4j
            log4j-api
            2.9.1
        
        
        
            org.apache.logging.log4j
            log4j-web
            2.9.1
        
        
            org.springframework
            spring-webmvc
            ${spring.version}
        

        
        
            javax.servlet.jsp
            javax.servlet.jsp-api
            2.3.3
        
        
            jstl
            jstl
            1.2
        
        
            taglibs
            standard
            1.1.2
        
        
            commons-fileupload
            commons-fileupload
            1.3.3
        

        
        
            org.hibernate
            hibernate-validator
            6.0.7.Final
        

    

    
        springmvc
        
            
            
                src/main/java
                
                    **/*.xml
                
            
            
            
                src/main/resources
                
                    jdbc.properties
                    *.xml
                
            
        

        
            

                
                    org.apache.maven.plugins
                    maven-compiler-plugin
                    ${maven.compiler.plugin.version}
                    
                        ${maven.compiler.source}
                        ${maven.compiler.target}
                        ${project.build.sourceEncoding}
                    
                
                
                    org.mybatis.generator
                    mybatis-generator-maven-plugin
                    1.3.2
                    
                        
                        
                            mysql
                            mysql-connector-java
                            ${mysql.version}
                        
                    
                    
                        true
                    
                

                
                    maven-clean-plugin
                    3.1.0
                
                
                
                    maven-resources-plugin
                    3.0.2
                
                
                    maven-compiler-plugin
                    3.8.0
                
                
                    maven-surefire-plugin
                    2.22.1
                
                
                    maven-war-plugin
                    3.2.2
                
                
                    maven-install-plugin
                    2.5.2
                
                
                    maven-deploy-plugin
                    2.8.2
                
            
        
    

再进行其他的配置

springmvc 03(JSR303和拦截器)_第1张图片

 applicationContext-mybatis.xml



    
    
    
    
    

    

    
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
    

    
    
    
        
        
        
        
        
        
        
        
            
                
                    
                        
                            helperDialect=mysql
                        
                    
                
            
        
    

    
    
    
        
        
        
        
        
    

    
        
    
    
    

generatorConfig.xml




    
    

    
    

    
    
        
        
            
             
        

        
        

        
        
            
            
        

        
        
        
        
            
            
            
            
            
            
            
            
        

        
        
            
            
        

        
        
        
        
        
            
            
        

        
        
        
        
        
        
        
        
        
        
        
        
        

        

        
jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/t280?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456

 log4j2.xml





    
        
        /root/workspace/lucenedemo/logs
        /root/workspace/lucenedemo/logs/error
        /root/workspace/lucenedemo/logs/warn
        %d{yyyy-MM-dd HH:mm:ss.SSS} [%t-%L] %-5level %logger{36} - %msg%n
    

    
        
        
            
            
            
            
            
        

        
        
        
            
        
        
        
            
            
            
            
                
                
                
                
                
                
            
        

        
            
            
            
                
                
            
            
            
        

        
            
            
            
                
                
                
            
        

    

    
    
        
        
        

        
        
        
        
        
        


        
        
            
            
            
            
        

    

 mybits.cfg.xml




    
    

    
        
    

    
    
        
    

    
        
        
        
    

    
    
        
            
            

            
            
            
            
            
                
                
                
                
            
        
    



    
       
    

mvc.tld





    mvc 1.1 core library
    mvc core
    1.1
    mvc
    http://jsp.veryedu.cn


    
        page
        com.ruojuan.ssm.tag.PageTag
        JSP
        
            pageBean
            true
            true
        
    


 springmvc-servlet.xml



    
    
    
    

    
    
    
    

    
    
        
        
        
        
    



    
    
    
    

    
        
        
        
        
        
        
    

    
    

    
    
        
            
            
            
        
        
            
            
            
        
    


 web.xml




  Archetype Created Web Application
  
    contextConfigLocation
    classpath:applicationContext.xml
  
  
  
    org.springframework.web.context.ContextLoaderListener
  

  
  
    SpringMVC
    org.springframework.web.servlet.DispatcherServlet
    
    
      contextConfigLocation
      /WEB-INF/springmvc-servlet.xml
    
    1
    
    true
  
  
    SpringMVC
    /
  

  
  
    encodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
    true
    
      encoding
      UTF-8
    
  
  
    encodingFilter
    /*
  

实体类:

用注解的方式来提示是否输入

springmvc 03(JSR303和拦截器)_第2张图片 

Clzz.java实体类

package com.ruojuan.ssm.model;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;

/**
 * @NotNull :作用于基本数据类型
 * @NotEmpty    作用于集合
 * @NotBlank    作用于字符串
 */
public class Clazz {

    @NotNull(message = "cid不能为空")
    private Integer cid;

    @NotBlank(message = "班级名不能为空")
    private String cname;

    @NotBlank(message = "教员老师不能为空")
    private String cteacher;

    private String pic;

    public Clazz(Integer cid, String cname, String cteacher, String pic) {
        this.cid = cid;
        this.cname = cname;
        this.cteacher = cteacher;
        this.pic = pic;
    }

    public Clazz() {
        super();
    }

    public Integer getCid() {
        return cid;
    }

    public void setCid(Integer cid) {
        this.cid = cid;
    }

    public String getCname() {
        return cname;
    }

    public void setCname(String cname) {
        this.cname = cname;
    }

    public String getCteacher() {
        return cteacher;
    }

    public void setCteacher(String cteacher) {
        this.cteacher = cteacher;
    }

    public String getPic() {
        return pic;
    }

    public void setPic(String pic) {
        this.pic = pic;
    }
}

 控制层ClazzController.java

//    给数据添加服务端校验
    @RequestMapping("/valiAdd")
    public String valiAdd(@Validated Clazz clazz, BindingResult result,HttpServletRequest req){
//        如果服务端验证不通过,有错误
        if(result.hasErrors()){
//            服务端验证了实体类的多个属性,多个属性都没有验证通过
            List fieldErrors = result.getFieldErrors();
            Map map = new HashMap<>();
            for (FieldError fieldError : fieldErrors) {
//                将多个属性的验证失败信息输送到控制台
                System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage());
                map.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            req.setAttribute("errorMap",map);
        }else {
            this.clazzBiz.insertSelective(clazz);
            return "redirect:/clz/list";
        }
        return "clzEdit";
    }

 前端代码:


<%--
--%> id:${errorMap.cid}
cname:${errorMap.cname}
cteacher:${errorMap.cteacher}

 效果:

当你不输入时就提示不能输入空值

springmvc 03(JSR303和拦截器)_第3张图片

 

二,拦截器

        1.简介

SpringMVC的处理器拦截器,类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理。

  依赖于web框架,在实现上基于Java的反射机制属于面向切面编程(AOP)的一种运用。由于拦截器是基于web框架的调用,因此可以使用Spring的依赖注入(DI)进行一些业务操作,同时一个拦截器实例在一个 
  controller生命周期之内可以多次调用。

        2.拦截器与过滤器

                2.1 什么是过滤器

    依赖于servlet容器。在实现上基于函数回调,可以对几乎所有请求进行过滤,但是缺点是一个过滤器实例
    只能在容器初始化时调用一次。使用过滤器的目的是用来做一些过滤操作,比如:在过滤器中修改字符编码;
    在过滤器中修改HttpServletRequest的一些参数,包括:过滤低俗文字、危险字符等。

                2.2 拦截器和过滤器的区别

    过滤器(filter):

    1) filter属于Servlet技术,只要是web工程都可以使用
    2) filter主要对所有请求过滤
    3) filter的执行时机早于Interceptor

    拦截器(interceptor)

    1) interceptor属于SpringMVC技术,必须要有SpringMVC环境才可以使用
    2) interceptor通常对处理器Controller进行拦截
    3) interceptor只能拦截dispatcherServlet处理的请求

应用场景

    1)日志记录:记录请求信息的日志,以便进行信息监控、信息统计、计算PV(Page View)等。

    2)权限检查:如登录检测,进入处理器检测是否登录,如果没有直接返回到登录页面;

    3)性能监控:有时候系统在某段时间莫名其妙的慢,可以通过拦截器在进入处理器之前记录开始时间,在处理完后记录结束时间,从而得到该请求的处理时间(如果有反向代理,如apache可以自动记录);

    4)通用行为:读取cookie得到用户信息并将用户对象放入请求,从而方便后续流程使用,还有如提取Locale、Theme信息等,只要是多个Controller中的处理方法都需要的,我们就可以使用拦截器实现。

        3.拦截器案例

                3.1 使用原理

1.   拦截器入门:

①创建一个类名为HellController

 
  
package com.ruojuan.ssm.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author ruojuan
 * @site 123456999
 * @company 玉渊工作室
 * @create 2022-08-19 16:44
 */
@Controller
public class HellController {

        @RequestMapping("/hello")
        public String hello(){
            System.out.println("进入业务方法。。。。");
            return "List";
        }

}

 

②再创建一个类为拦截器OneHandlerInterceptor

springmvc 03(JSR303和拦截器)_第4张图片


package com.ruojuan.ssm.intercept;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ruojuan
 * @site 123456999
 * @company 玉渊工作室
 * @create 2022-08-19 16:37
 */

public class OneInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("【OneInterceptor】:preHandle...");

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("【OneInterceptor】:postHandle...");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("【OneInterceptor】:afterCompletion...");
    }
}

③在springmvc-servlet.xml配置拦截器文件

springmvc 03(JSR303和拦截器)_第5张图片


 
        
    

④结果

springmvc 03(JSR303和拦截器)_第6张图片

 

2.拦截器链

①创建另一个拦截器

springmvc 03(JSR303和拦截器)_第7张图片


package com.ruojuan.ssm.intercept;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ruojuan
 * @site 123456999
 * @company 玉渊工作室
 * @create 2022-08-19 16:37
 */

public class OneInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("【OneInterceptor】:preHandle...");

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("【OneInterceptor】:postHandle...");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("【OneInterceptor】:afterCompletion...");
    }
}

package com.ruojuan.ssm.intercept;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ruojuan
 * @site 123456999
 * @company 玉渊工作室
 * @create 2022-08-19 16:47
 */
public class TwoHandlerInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //预处理
        System.out.println("[OneHandlerInterceptor].preHandle");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //后处理
        System.out.println("[OneHandlerInterceptor].postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //完成后处理
        System.out.println("[OneHandlerInterceptor].afterCompletion");
    }
}

②springmvc-servlet.xml配置文件

springmvc 03(JSR303和拦截器)_第8张图片

 


        
            
            
        
        
            
            
        
    

springmvc 03(JSR303和拦截器)_第9张图片

 springmvc 03(JSR303和拦截器)_第10张图片

 

public class OneInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("【OneInterceptor】:preHandle...");
        StringBuffer url = request.getRequestURL();
        if (url.indexOf("/login") > 0 || url.indexOf("/logout") > 0){
            //        如果是 登录、退出 中的一种
            return true;
        }
//            代表不是登录,也不是退出
//            除了登录、退出,其他操作都需要判断是否 session 登录成功过
        String uname = (String) request.getSession().getAttribute("uname");
        if (uname == null || "".equals(uname)){
            return false;
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("【OneInterceptor】:postHandle...");

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("【OneInterceptor】:afterCompletion...");
    }
}

@Controller
public class LoginController {
    @RequestMapping("/login")
    public String login(HttpServletRequest req){
        String uname = req.getParameter("uname");
        HttpSession session = req.getSession();
        if ("zs".equals(uname)){
            session.setAttribute("uname",uname);
        }
        return "redirect:/clz/list";
    }

    @RequestMapping("/logout")
    public String logout(HttpServletRequest req){
        req.getSession().invalidate();
        return "redirect:/clz/list";
    }
}

        

你可能感兴趣的:(springMVC,spring,spring,前端)