JSR303和拦截器

目录

  • 一、 JSR303
    • 1.1.简介
    • 1.2.pom依赖
    • 1.3.后端
  • 二、拦截器
    • 2.1 入门
    • 2.2 拦截器链
    • 2.3 登录权限控制

一、 JSR303

1.1.简介

服务端验证

1.2.pom依赖


      org.hibernate
      hibernate-validator
      6.0.7.Final
    

1.3.后端

JSR303和拦截器_第1张图片
代码展示

package com.yzp.model;

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

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

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

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

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

    protected String pic;

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

    public Clayy() {
        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;
    }

    @Override
    public String toString() {
        return "Clayy{" +
                "cid=" + cid +
                ", cname='" + cname + '\'' +
                ", cteacher='" + cteacher + '\'' +
                ", pic='" + pic + '\'' +
                '}';
    }
}

控制层代码controller

/**
     * @valid 是与实体类中的服务端校验 注解配合使用的
     * @param clayy
     * @param bindingResult  存放了所有违背 校验的错误信息
     * @return
     */
    @RequestMapping("/valiAdd")
    public  String valiAdd(@Valid Clayy clayy, BindingResult bindingResult,HttpServletRequest request){
        if(bindingResult.hasErrors()){
            Map msg = new HashMap();
//            违背规则
            List fieldErrors = bindingResult.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                //cid :cid不能为空
                System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage());
                msg.put(fieldError.getField(),fieldError.getDefaultMessage());
            }
                request.setAttribute("msg",msg);
            //如果出现了错误,应该将提示语显示在表单提示元素后方
            return  "clyedit";
        }else {
            this.clayyBiz.insertSelective(clayy);
        }
        return  "redirect:/cly/list";
    }

jsp代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>



    
    班级的编辑界面


cid:${msg.cid}
cname:${msg.cname}
cteacher:${msg.cteacher}
pic:

运行结果:
JSR303和拦截器_第2张图片

二、拦截器

2.1 入门

package com.yzp.controller;

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

/**
 * @author易泽鹏
 * @site 16670388677
 * @company
 * @create  2022-08-22 18:08
 */
@Controller
public class HelloController {

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


后台代码

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.xml里面


        
    

index代码

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/22
  Time: 20:16
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    测试json数据返回


   返回list<T>对象
返回list<map>对象
返回T对象
返回map对象
返回hunhe对象

http://localhost:8080/hello

运行结果:
JSR303和拦截器_第3张图片
JSR303和拦截器_第4张图片

2.2 拦截器链

拦截器OneInterceptor

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

拦截器TwoInterceptor

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

        return true;
    }

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

    }

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

配置文件SpringMVC.xml

 
        
            
            
        
        
            
            
        
    

注:如果preHandle的返回值为false,则后续代码不执行
运行结果
在这里插入图片描述

在这里插入图片描述

2.3 登录权限控制

拦截器

package com.yzp.intercept;

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

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

/**
 * @author易泽鹏
 * @site 16670388677
 * @company
 * @create  2022-08-22 17:57
 */
public class OneHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //预处理
        System.out.println("OneHandlerInterceptor.preHandle");
        //如果 login、logout 这个两个请求就直接放行,反之就拦截
        String url = request.getRequestURL().toString();
        if(url.indexOf("/login")>0||url.indexOf("/logout")>0){
            return  true;
        }
        //对于请求业务方法 只有登录果,也就是存在session,才能访问
        String uname = (String)request.getSession().getAttribute("uname");
        System.out.println(uname);
        if(uname==null||"".equals(uname)){
          response.sendRedirect("/login.jsp");
            return false;
        }
        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");
    }
}

controller代码

package com.yzp.controller;

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

import javax.servlet.http.HttpServletRequest;

/**
 * @author易泽鹏
 * @site 16670388677
 * @company
 * @create  2022-08-22 18:37
 */
@Controller
public class LoginController {

    @RequestMapping("/login")
    public  String login(HttpServletRequest request){
        //登录成功 需要 保存用户信息
        String uname = request.getParameter("uname");
        if("yzp".equals(uname)){
            request.getSession().setAttribute("uname",uname);
            System.out.println(uname);
        }
        return "index";
    }
    @RequestMapping("/logout")
    public  String logout(HttpServletRequest request){
       request.getSession().invalidate();
        return "index";
    }
}

测试步骤如下:
http://localhost:8082/cly/list 不能访问,因为session被过滤掉
http://localhost:8082/login 不能访问,因为用户未成功登录被过滤掉
http://localhost:8082/login?uname=yzp 可以访问

http://localhost:8082/logout 清除掉session

JSR303和拦截器_第5张图片
JSR303和拦截器_第6张图片
登录成功跳到主界面
JSR303和拦截器_第7张图片
登录成功之后才可访问cly/list界面
JSR303和拦截器_第8张图片
JSR303和拦截器_第9张图片

你可能感兴趣的:(java,spring,hibernate)