JSR303和拦截器

一、JSR303

/* @NotNull :作用于基本数据类型
 *   @NotEmpty    作用于集合
 *   @NotBlank    作用于字符串
 */
package com.zking.oa.model;
 
import sun.plugin2.message.Message;
 
import javax.validation.constraints.NotBlank;
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;
    }
}

  pom.xml

<!--做职务参数校验jsr303的jar包依赖 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.7.Final</version>
        </dependency>
 

 

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>org.example</groupId>
    <artifactId>ssm3</artifactId>
    <version>1.0-SNAPSHOT</version>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <maven.compiler.plugin.version>3.7.0</maven.compiler.plugin.version>
 
        <!--添加jar包依赖-->
        <!--1.spring 5.0.2.RELEASE相关-->
        <spring.version>5.0.2.RELEASE</spring.version>
        <!--2.mybatis相关-->
        <mybatis.version>3.4.5</mybatis.version>
        <!--mysql-->
        <mysql.version>5.1.44</mysql.version>
        <!--pagehelper分页jar依赖-->
        <pagehelper.version>5.1.2</pagehelper.version>
        <!--mybatis与spring集成jar依赖-->
        <mybatis.spring.version>1.3.1</mybatis.spring.version>
        <!--3.dbcp2连接池相关 druid-->
        <commons.dbcp2.version>2.1.1</commons.dbcp2.version>
        <commons.pool2.version>2.4.3</commons.pool2.version>
        <!--4.log日志相关-->
        <log4j2.version>2.9.1</log4j2.version>
        <!--5.其他-->
        <junit.version>4.12</junit.version>
        <servlet.version>4.0.0</servlet.version>
        <lombok.version>1.18.2</lombok.version>
    </properties>
 
    <dependencies>
        <!--1.spring相关-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>
 
        <!--2.mybatis相关-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis.version}</version>
        </dependency>
        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <!--pagehelper分页插件jar包依赖-->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>${pagehelper.version}</version>
        </dependency>
        <!--mybatis与spring集成jar包依赖-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis.spring.version}</version>
        </dependency>
 
        <!--3.dbcp2连接池相关-->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>${commons.dbcp2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>${commons.pool2.version}</version>
        </dependency>
 
        <!--4.log日志相关依赖-->
        <!--核心log4j2jar包-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${log4j2.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j2.version}</version>
        </dependency>
        <!--web工程需要包含log4j-web,非web工程不需要-->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-web</artifactId>
            <version>${log4j2.version}</version>
        </dependency>
 
        <!--5.其他-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>
 
        <!-- jsp依赖-->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.3</version>
        </dependency>
        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>
 
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
 
<!--做职务参数校验jsr303的jar包依赖 -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.0.7.Final</version>
        </dependency>
 
 
 
    </dependencies>
 
    <build>
    <finalName>ssm2</finalName>
    <resources>
        <!--解决mybatis-generator-maven-plugin运行时没有将XxxMapper.xml文件放入target文件夹的问题-->
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <!--解决mybatis-generator-maven-plugin运行时没有将jdbc.properites文件放入target文件夹的问题-->
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>jdbc.properties</include>
                <include>*.xml</include>
            </includes>
        </resource>
    </resources>
 
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven.compiler.plugin.version}</version>
                <configuration>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.2</version>
                <dependencies>
                    <!--使用Mybatis-generator插件不能使用太高版本的mysql驱动 -->
                    <dependency>
                        <groupId>mysql</groupId>
                        <artifactId>mysql-connector-java</artifactId>
                        <version>${mysql.version}</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <overwrite>true</overwrite>
                </configuration>
            </plugin>
            <plugin>
                <artifactId>maven-clean-plugin</artifactId>
                <version>3.1.0</version>
            </plugin>
            <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
            <plugin>
                <artifactId>maven-resources-plugin</artifactId>
                <version>3.0.2</version>
            </plugin>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
            </plugin>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.1</version>
            </plugin>
            <plugin>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.2.2</version>
            </plugin>
            <plugin>
                <artifactId>maven-install-plugin</artifactId>
                <version>2.5.2</version>
            </plugin>
            <plugin>
                <artifactId>maven-deploy-plugin</artifactId>
                <version>2.8.2</version>
            </plugin>
        </plugins>
    </pluginManagement>
    </build>
 
</project>

controller类

 /**
     * @Valid是在与实体类中的职务校验注释配合使用
     * BindingResult 存放了所有违背校验的错误信息
     * @param clazz
     * @param Bindingresult
     * @return
     */
 
    @RequestMapping("/valiAdd")
    public String valiAdd(@Valid Clazz clazz, BindingResult Bindingresult ,HttpServletRequest request ){
        if(Bindingresult.hasErrors()){
            Map msg=new HashMap();
            //违背规则
          List<FieldError> FieldErrors = Bindingresult.getFieldErrors();
            for (FieldError fieldError : FieldErrors) {
                System.out.println(fieldError.getField()+""+fieldError.getDefaultMessage());
          //msg.put (cid不为空)
           msg.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
            request.setAttribute("msg",msg);//赋值
            return  "clzEdit";
        }
        else{
        this.clazzBiz.insertSelective(clazz);
        }
        return  "redirect:/clz/list";
    }

修改界面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>班级的编辑界面</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/clz/${empty b ? 'valiAdd' : 'edit'} " method="post">
    id:<input type="text" name="cid" value="${b.cid }"><span style="color: red;">${msg.cid}</span><br>
    cname:<input type="text" name="cname" value="${b.cname }"><span style="color: red;">${msg.cname}</span><br>
    cteacher:<input type="text" name="cteacher" value="${b.cteacher }"><span style="color: red;">${msg.cteacher}</span><br>
    <input type="submit">
</form>
</body>
</html>

二,拦截器


        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.zking.ssm.web;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
@Controller
public class HellController {
 
        @RequestMapping("/hello")
        public String hello(){
            System.out.println("进入业务方法。。。。");
            return "List";
        }
 
}

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

 
package com.zking.ssm.intercept;
 
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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...");
    }
}
 

 拦截器链
配置文件代码  拦截器2

业务方法:

two--posthandle

one---posthandle

one---aftercomplation

two--aftercomplation

  springmvc-servlet.xml

<!-- 配置连接器链 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
           <bean class="com.zking.oa.intercept.OnehandlerInterceptor"></bean>
        </mvc:interceptor>
        <mvc:interceptor>
            <mvc:mapping path="/clz/**"/>
            <bean class="com.zking.oa.intercept.TwohandlerInterceptor"></bean>
        </mvc:interceptor>
    </mvc:interceptors>
package com.zking.oa.intercept;

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

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

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

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

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



三.登录权限控制 

前端代码:

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/19
  Time: 20:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
登录界面
</body>
</html>
 

后台:

package com.zking.ssm.web;
 
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
 
import javax.servlet.http.HttpServletRequest;
 
@Controller
public class LoginController {
 
    @RequestMapping("/login")
    public String login(HttpServletRequest request){
//        登录成功需要保存用户信息
        String uname = request.getParameter("uname");
        if("zhangsan".equals(uname)){
            request.getSession().setAttribute("uname",uname);
        }
        return "index";
    }
 
    @RequestMapping("/loginout")
    public String loginout(HttpServletRequest request){
        request.getSession().invalidate();
        return "index";
    }
 
}
 

今天的分享就到这啦!我们下期再见!!!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值