• JSR303和拦截器


    一、JSR303

    1、pom依赖

    <dependency>
          <groupId>org.hibernategroupId>
          <artifactId>hibernate-validatorartifactId>
          <version>6.0.7.Finalversion>
        dependency>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2、后端

    ①实体类

    package com.xnx.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不能为空")
        protected Integer cid;
    
        @NotBlank(message = "班级名称不能为空")
        protected String cname;
    
        @NotBlank(message = "教员老师不能为空")
        protected String cteacher;
    
        protected 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;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66

    ②ClazzController.java

    package com.xnx.ssm.web;
    
    import com.xnx.ssm.biz.ClazzBiz;
    import com.xnx.ssm.model.Clazz;
    import com.xnx.ssm.model.dto.ClazzDto;
    import com.xnx.ssm.util.PageBean;
    import org.apache.commons.io.FileUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Controller;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.FieldError;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.multipart.MultipartFile;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.validation.Valid;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    @Controller
    @RequestMapping("/clz")
    public class ClazzController {
        @Autowired
        private ClazzBiz clazzBiz;
    //    list->clzlist
    //    toList->重定向list->"redirect:/clz/list"
    //    toEdit->跳转到编辑界面->clzEdit
    //    Clazz:以前是通过模型驱动接口封装,现在是直接在方法中接收参数即可
    
        @RequestMapping("/list")
        public String list(Clazz clazz, HttpServletRequest request){
            PageBean pageBean=new PageBean();
            pageBean.setRequest(request);
            List<Clazz> lst = this.clazzBiz.listPager(clazz, pageBean);
            request.setAttribute("lst",lst);
            request.setAttribute("pageBean",pageBean);
            return "clzList";
        }
    
        @RequestMapping("/toEdit")
        public String toEdit(Clazz clazz, HttpServletRequest request){
            Integer cid = clazz.getCid();
    //        传递的id代表了修改,没传代表新增
            if(cid != null){
                List<Clazz> lst = this.clazzBiz.listPager(clazz, null);
                request.setAttribute("b",lst.get(0));
            }
            return "clzEdit";
        }
    
        @RequestMapping("/add")
        public String add(Clazz clazz){
            this.clazzBiz.insertSelective(clazz);
            return "redirect:/clz/list";
        }
    
        /**
         * @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) {
    //                cid : cid不能为空
                    System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage());
    //                msg.put(cid,cid不能为空)
                    msg.put(fieldError.getField(),fieldError.getDefaultMessage());
    
                }
                request.setAttribute("msg",msg);
    //            如果出现了错误,一个将提示语显示在表单提交元素后方
                return "clzEdit";
            }else{
                this.clazzBiz.insertSelective(clazz);
            }
            return "redirect:/clz/list";
        }
    
        @RequestMapping("/edit")
        public String edit(Clazz clazz){
            this.clazzBiz.updateByPrimaryKeySelective(clazz);
            return "redirect:/clz/list";
        }
    
        @RequestMapping("/del")
        public String del(Clazz clazz){
            this.clazzBiz.deleteByPrimaryKey(clazz.getCid());
            return "redirect:/clz/list";
        }
    
    //    文件上传
        @RequestMapping("/upload")
        public String upload(ClazzDto clazzDto){
            try{
    //          前台上传的文件
                MultipartFile picFile = clazzDto.getPicFile();
    //            InputStream inputStream = picFile.getInputStream();
                /*FileOutputStream fout = new FileOutputStream(new File("D/temp/1.png"));
                byte[] bbuf=new byte[1024];
                int len = 0;
                while(true){
                    len=inputStream.read(bbuf,0,len);
                    fout.write(bbuf,0,len);
                    if(len<0){
                        break;
                    }
                }*/
    //            实际应该配置到resource.properties中
                String dispath="E:/temp/images";//图片的存放地址
    //            http://localhost:8080/upload/mvc/**.png
                String requestPath="/upload/mvc";//数据库保存的地址,也是访问地址
    //            拿到上传文件的名字
                String fileName = picFile.getOriginalFilename();//**.png
    
                FileUtils.copyInputStreamToFile(picFile.getInputStream(),new File(dispath+fileName));
    //           将图片上传之后,并且将图片地址更新到数据库中
                Clazz clazz=new Clazz();
                clazz.setCid(clazzDto.getCid());
                clazz.setPic(requestPath+fileName);
                this.clazzBiz.updateByPrimaryKeySelective(clazz);
            }catch (Exception e){
                e.printStackTrace();
            }
            return "redirect:/clz/list";
        }
    
        //    文件下载
        @RequestMapping("/download")
        public ResponseEntity download(ClazzDto clazzDto){
            try{
    //            1.点击下载传递文件的ID,通过文件的ID查询出文件的路径
                Clazz clazz = this.clazzBiz.selectByPrimaryKey(clazzDto.getCid());
                String pic=clazz.getPic();// /upload/mvc/**.png
    //              实际应该配置到resource.properties中
                String diskPath="E:/temp/images/";//图片的存放地址
    //            http://localhost:8080/upload/mvc/图片.png
                String requestPath="/upload/mvc/";//数据库保存的地址,也是访问地址
                
    //            2.通过文件的请求地址,转换成文件存放的硬盘地
                String realPath=pic.replace(requestPath,diskPath);// E:/temp/images
                String fileName=realPath.substring(realPath.lastIndexOf("/")+1);
    //            3.将硬盘中文件下载下来->固定代码
                File file=new File(realPath);
                HttpHeaders headers = new HttpHeaders();//http头信息
                String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
                headers.setContentDispositionFormData("attachment", downloadFileName);
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息
                return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
            }catch (Exception e){
                e.printStackTrace();
            }
            return null;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168
    • 169
    • 170
    • 171

    3、前端

    clzEdit.jsp

    <%@ 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 ? 'add' : 'edit'}" method="post">
    --%>
    <form action="${pageContext.request.contextPath }/clz/${empty b ? 'valiAdd' : 'edit'}" method="post">
        cid:<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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    运行效果:
    在这里插入图片描述
    输入为空则提示

    二、拦截器

    1、拦截器的初步认识

    ①OneHandlerInterceptor

    package com.xnx.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 xnx
     * @create 2022-08-19 18:32
     */
    public class OneHandlerInterceptor 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...");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    ②HelloController

    package com.xnx.ssm.web;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    /**
     * @author xnx
     * @create 2022-08-19 19:21
     */
    @Controller
    public class HelloController {
    
        @RequestMapping("hello")
        public String hello(){
            System.out.println("进入业务方法...");
            return "index";
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19

    ③springmvc-servlet的配置

    
        <mvc:interceptors>
            
            <bean class="com.xnx.ssm.intercept.OneHandlerInterceptor">bean>
        mvc:interceptors>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    运行效果:
    在这里插入图片描述

    2、拦截器链

    在这里插入图片描述

    ①TwoHandlerInterceptor

    package com.xnx.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 xnx
     * @create 2022-08-19 18:32
     */
    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] . afterCompletion...");
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34

    ②springmvc-servlet的配置

    
        <mvc:interceptors>
            <mvc:interceptor>
                <mvc:mapping path="/**"/>
                <bean class="com.xnx.ssm.intercept.OneHandlerInterceptor">bean>
            mvc:interceptor>
            <mvc:interceptor>
                <mvc:mapping path="/clz/**"/>
                <bean class="com.xnx.ssm.intercept.TwoHandlerInterceptor">bean>
            mvc:interceptor>
        mvc:interceptors>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    运行效果:
    在这里插入图片描述
    在这里插入图片描述

    3、登录权限控制

    3.1 前端

    login.jsp

    <%--
      Created by IntelliJ IDEA.
      User: Administrator
      Date: 2022/8/19
      Time: 19:55
      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>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    3.2 后端

    LoginController

    package com.xnx.ssm.web;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import javax.servlet.http.HttpServletRequest;
    
    /**
     * @author xnx
     * @create 2022-08-19 19:52
     */
    @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";
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32

    3.3运行效果

    http://localhost:8080/clz/list 不能访问,因为session被过滤掉
    http://localhost:8080/login 不能访问,因为用户未成功登录被过滤掉
    http://localhost:8080/login?uname=zs 可以访问
    http://localhost:8080/loginout 清除掉session

    http://localhost:8080/clz/list:
    在这里插入图片描述
    http://localhost:8080/login:
    在这里插入图片描述
    http://localhost:8080/login?uname=zs
    在这里插入图片描述
    http://localhost:8080/loginout
    在这里插入图片描述
    四种测试的控制台打印:
    在这里插入图片描述

  • 相关阅读:
    简谈计算机网络与网络编程
    事业编招聘:雄安新区公开选聘专业骨干人才
    下一站——Java,准备好踏上新征程了?少年!!!!
    什么是网站权重?网站权重查询方法有哪些?
    Arial.tff字体,YOLO中下载。已解决
    Spring Security JWT Authentication and Authorisation(一)
    计算几何+2sat:1020T3
    4.5.CVAT——视频标注的详细步骤
    网页设计——个人简历
    金九失足,10月喜提“Java高分指南”,11月冲击大厂
  • 原文地址:https://blog.csdn.net/weixin_67677668/article/details/126430797