• SpringMVC (JSR303 & 拦截器)


    目录

    一、JSR303 

    1、什么是JSR303

     2、导入pom依赖

    3、后端代码

    4、前端

    二、拦截器


    一、JSR303 

    1、什么是JSR303

    JSR303就是服务端验证

     2、导入pom依赖

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

    3、后端代码

    Clazz

     都是判空

     @NotNull 作用基本数据类型
     @NotEmpty 作用集合数组
     @NotBlank 作用字符串

    1. package com.zsx.ssm.model;
    2. import javax.validation.constraints.NotBlank;
    3. import javax.validation.constraints.NotEmpty;
    4. import javax.validation.constraints.NotNull;
    5. /**
    6. * @NotNull 作用基本数据类型
    7. * @NotEmpty 作用集合数组
    8. * @NotBlank 作用字符串
    9. */
    10. public class Clazz {
    11. @NotNull(message = "cid不能为空")
    12. protected Integer cid;
    13. @NotBlank(message = "班级名称不能为空")
    14. protected String cname;
    15. @NotBlank(message = "教员不能为空")
    16. protected String cteacher;
    17. protected String pic;
    18. public Clazz(Integer cid, String cname, String cteacher, String pic) {
    19. this.cid = cid;
    20. this.cname = cname;
    21. this.cteacher = cteacher;
    22. this.pic = pic;
    23. }
    24. public Clazz() {
    25. super();
    26. }
    27. public Integer getCid() {
    28. return cid;
    29. }
    30. public void setCid(Integer cid) {
    31. this.cid = cid;
    32. }
    33. public String getCname() {
    34. return cname;
    35. }
    36. public void setCname(String cname) {
    37. this.cname = cname;
    38. }
    39. public String getCteacher() {
    40. return cteacher;
    41. }
    42. public void setCteacher(String cteacher) {
    43. this.cteacher = cteacher;
    44. }
    45. public String getPic() {
    46. return pic;
    47. }
    48. public void setPic(String pic) {
    49. this.pic = pic;
    50. }
    51. }
    ClazzController
    1. package com.zsx.ssm.controller;
    2. import com.zsx.ssm.biz.ClazzBiz;
    3. import com.zsx.ssm.model.Clazz;
    4. import com.zsx.ssm.model.dto.ClazzDto;
    5. import com.zsx.ssm.util.PageBean;
    6. import org.apache.commons.io.FileUtils;
    7. import org.springframework.beans.factory.annotation.Autowired;
    8. import org.springframework.http.*;
    9. import org.springframework.stereotype.Controller;
    10. import org.springframework.validation.BindingResult;
    11. import org.springframework.validation.FieldError;
    12. import org.springframework.web.bind.annotation.RequestMapping;
    13. import org.springframework.web.multipart.MultipartFile;
    14. import javax.servlet.http.HttpServletRequest;
    15. import javax.validation.Valid;
    16. import java.io.File;
    17. import java.util.HashMap;
    18. import java.util.List;
    19. import java.util.Map;
    20. /**
    21. * @author zsx
    22. * @site 155954····
    23. * @company 交换余生
    24. * @create 2022--08--17 19:07
    25. */
    26. @Controller
    27. @RequestMapping("/clz")
    28. public class ClazzController {
    29. @Autowired
    30. private ClazzBiz clazzBiz;
    31. // list-->clzList
    32. // toList-->重定向list-->redirect:/clz/list
    33. // toEdit-->跳转到编辑界面-->clzEdit
    34. // Clazz:以前是通过模型驱动接口封装,现在是直接在方法中接收参数
    35. @RequestMapping("/list")
    36. public String list(Clazz clazz, HttpServletRequest request){
    37. PageBean pageBean=new PageBean();
    38. pageBean.setRequest(request);
    39. List lst = this.clazzBiz.listPager(clazz, pageBean);
    40. request.setAttribute("lst",lst);
    41. request.setAttribute("pageBean",pageBean);
    42. return "clzList";
    43. }
    44. @RequestMapping("/toEdit")
    45. public String toEdit(Clazz clazz, HttpServletRequest request){
    46. Integer cid = clazz.getCid();
    47. //传了id代表修改,没传代表增加
    48. if(cid != null){
    49. List lst = this.clazzBiz.listPager(clazz, null);
    50. request.setAttribute("b",lst.get(0));
    51. }
    52. return "clzEdit";
    53. }
    54. @RequestMapping("/add")
    55. public String add(Clazz clazz){
    56. this.clazzBiz.insertSelective(clazz);
    57. return "redirect:/clz/list";
    58. }
    59. /**
    60. * @Valid 是与实体类中的服务端校验 注解配合使用的
    61. * BindingResult 存放了所有违背 校验的信息
    62. * @param clazz
    63. * @param bindingResult
    64. * @return
    65. */
    66. @RequestMapping("/valiAdd")
    67. public String valiAdd(@Valid Clazz clazz, BindingResult bindingResult,HttpServletRequest request){
    68. if(bindingResult.hasErrors()){
    69. Map msg = new HashMap();
    70. //违背了规则
    71. List fieldErrors = bindingResult.getFieldErrors();
    72. for (FieldError fieldError : fieldErrors) {
    73. //cid/cname/cteacher:不为空
    74. // System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage());
    75. msg.put(fieldError.getField(),fieldError.getDefaultMessage());
    76. }
    77. request.setAttribute("msg",msg);
    78. return "clzEdit";
    79. }else{
    80. this.clazzBiz.insertSelective(clazz);
    81. }
    82. return "redirect:/clz/list";
    83. }
    84. @RequestMapping("/edit")
    85. public String edit(Clazz clazz){
    86. this.clazzBiz.updateByPrimaryKeySelective(clazz);
    87. return "redirect:/clz/list";
    88. }
    89. @RequestMapping("/del")
    90. public String del(Clazz clazz){
    91. this.clazzBiz.deleteByPrimaryKey(clazz.getCid());
    92. return "redirect:/clz/list";
    93. }
    94. /**
    95. * 文件上传
    96. * @param clazzDto
    97. * @return
    98. */
    99. @RequestMapping("/upload")
    100. public String upload(ClazzDto clazzDto){
    101. try {
    102. //前台上传的文件
    103. MultipartFile picFile = clazzDto.getPicFile();
    104. // InputStream inputStream = picFile.getInputStream();
    105. //实际应该配置到 resource.properties 中
    106. String disPath="E:/temp";//图片存放地址
    107. //数据库保存的地址 也是访问地址
    108. String requestPath="/upload/mvc/";
    109. // 拿到上传文件的名字
    110. String filename = picFile.getOriginalFilename();
    111. FileUtils.copyInputStreamToFile(picFile.getInputStream(),new File(disPath+filename));
    112. Clazz clazz = new Clazz();
    113. clazz.setCid(clazzDto.getCid());
    114. clazz.setPic(requestPath+filename);
    115. this.clazzBiz.updateByPrimaryKeySelective(clazz);
    116. // FileOutputStream fileOutputStream = new FileOutputStream(new File("e/temp/1.png"));
    117. // byte[] bbuf = new byte[1024];
    118. // int i=0;
    119. // while (true){
    120. // i=inputStream.read(bbuf,0,i);
    121. // fileOutputStream.write(bbuf,0,i);
    122. // if(i<0){
    123. // break;
    124. // }
    125. // }
    126. } catch (Exception e) {
    127. e.printStackTrace();
    128. }
    129. return "redirect:/clz/list";
    130. }
    131. /**
    132. * 文件下载
    133. * @param clazzDto
    134. * @return
    135. */
    136. @RequestMapping("/dowload")
    137. public ResponseEntity dowload(ClazzDto clazzDto){
    138. try {
    139. Clazz clazz = this.clazzBiz.selectByPrimaryKey(clazzDto.getCid());
    140. String pic = clazz.getPic();
    141. String disPath="E:/temp";//图片存放地址
    142. //数据库保存的地址 也是访问地址
    143. String requestPath="/upload/mvc/";
    144. String realPath = pic.replace(requestPath,disPath);
    145. String fileName = realPath.substring(realPath.lastIndexOf("/")+1);
    146. File file=new File(realPath);
    147. HttpHeaders headers = new HttpHeaders();//http头信息
    148. String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
    149. headers.setContentDispositionFormData("attachment", downloadFileName);
    150. headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
    151. //MediaType:互联网媒介类型 contentType:具体请求中的媒体类型信息
    152. return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
    153. } catch (Exception e) {
    154. e.printStackTrace();
    155. }
    156. return null;
    157. }
    158. }
    OneHandlerInterceptor
    1. package com.zsx.ssm.intercept;
    2. import org.springframework.web.servlet.HandlerInterceptor;
    3. import org.springframework.web.servlet.ModelAndView;
    4. import javax.servlet.http.HttpServletRequest;
    5. import javax.servlet.http.HttpServletResponse;
    6. /**
    7. * @author zsx
    8. * @site 155954····
    9. * @company 交换余生
    10. * @create 2022--08--19 19:29
    11. */
    12. public class OneHandlerInterceptor implements HandlerInterceptor {
    13. @Override
    14. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    15. //预处理
    16. System.out.println("[OneHandlerInterceptor] . preHandle");
    17. return true;
    18. }
    19. @Override
    20. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    21. //后处理
    22. System.out.println("[OneHandlerInterceptor] . postHandle...");
    23. }
    24. @Override
    25. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    26. //完成后处理
    27. System.out.println("[OneHandlerInterceptor] . afterCompletion...");
    28. }
    29. }

    4、前端

    clzEdit.jsp

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    4. <html>
    5. <head>
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    7. <title>博客的编辑界面title>
    8. head>
    9. <body>
    10. <%--form action="${pageContext.request.contextPath }/clz/${empty b ? 'add' : 'edit'}" method="post">--%>
    11. <form action="${pageContext.request.contextPath }/clz/${empty b ? 'valiAdd' : 'edit'}" method="post">
    12. cid:<input type="text" name="cid" value="${b.cid }"><span style="color: red;">${msg.cid}span><br>
    13. cname:<input type="text" name="cname" value="${b.cname }"><span style="color: red;">${msg.cname}span><br>
    14. cteacher:<input type="text" name="cteacher" value="${b.cteacher }"><span style="color: red;">${msg.cteacher}span><br>
    15. <input type="submit">
    16. form>
    17. body>
    18. html>

    效果图:

    二、拦截器

    1、后台

    LoginController
    1. package com.zsx.ssm.controller;
    2. import org.springframework.stereotype.Controller;
    3. import org.springframework.web.bind.annotation.RequestMapping;
    4. import javax.servlet.http.HttpServletRequest;
    5. /**
    6. * @author zsx
    7. * @site 155954····
    8. * @company 交换余生
    9. * @create 2022--08--19 19:57
    10. */
    11. @Controller
    12. public class LoginController {
    13. /**
    14. * 登录
    15. * @param request
    16. * @return
    17. */
    18. @RequestMapping("/login")
    19. public String login(HttpServletRequest request){
    20. //登录成功保留用户信息
    21. String uname = request.getParameter("uname");
    22. if("zsx".equals(uname)){
    23. request.getSession().setAttribute("uname",uname);
    24. }
    25. return "index";
    26. }
    27. /**
    28. * 退出
    29. * @param request
    30. * @return
    31. */
    32. @RequestMapping("/logout")
    33. public String logout(HttpServletRequest request){
    34. //消除Session
    35. request.getSession().invalidate();
    36. return "index";
    37. }
    38. }
    OneHandlerInterceptor
    1. package com.zsx.ssm.intercept;
    2. import org.springframework.web.servlet.HandlerInterceptor;
    3. import org.springframework.web.servlet.ModelAndView;
    4. import javax.servlet.http.HttpServletRequest;
    5. import javax.servlet.http.HttpServletResponse;
    6. /**
    7. * @author zsx
    8. * @site 155954····
    9. * @company 交换余生
    10. * @create 2022--08--19 19:29
    11. */
    12. public class OneHandlerInterceptor implements HandlerInterceptor {
    13. @Override
    14. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    15. //预处理
    16. System.out.println("[OneHandlerInterceptor] . preHandle");
    17. //如果是login/logout 放行 不拦截 反之都拦截
    18. String url = request.getRequestURL().toString();
    19. if(url.indexOf("/login") > 0 || url.indexOf("/logout") > 0){
    20. return true;
    21. }
    22. //对于请求业务方法 只有登陆过,存在session数据 才能访问
    23. String uname = (String)request.getSession().getAttribute("uname");
    24. if(uname == null || "".equals(uname)){
    25. response.sendRedirect("/login.jsp");
    26. return false;
    27. }
    28. return true;
    29. }
    30. @Override
    31. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    32. //后处理
    33. System.out.println("[OneHandlerInterceptor] . postHandle...");
    34. }
    35. @Override
    36. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    37. //完成后处理
    38. System.out.println("[OneHandlerInterceptor] . afterCompletion...");
    39. }
    40. }

    springmvc-servlet.xml

    1. <mvc:interceptors>
    2. <mvc:interceptor>
    3. <mvc:mapping path="/**"/>
    4. <bean class="com.zsx.ssm.intercept.OneHandlerInterceptor">bean>
    5. mvc:interceptor>
    6. mvc:interceptors>

    效果图:

    未登录被拦截时:

    登录后:

    登录后访问数据展示页面:

    退出登录后:

  • 相关阅读:
    ERP系统中有采购管理模块,为什么企业要选择供应商管理SRM系统?
    python Matplotlib绘制三维图
    HAL库实现基于STM32+RN8302B的电压采集
    解决在pycharm中使用matplotlib画图问题
    基于 Web 的 RADIUS 认证服务
    51单片机应用开发---定时器(定时1S,LED以1S间隔闪烁)
    双十一数据背后: 电商助力实体经济数字化转型才是未来方向
    南大通用GBase 8a MPP Cluster开发接口简介
    dayjs初体验
    python将本地png切片栅格数据写入postgis(Postgre入门三)
  • 原文地址:https://blog.csdn.net/weixin_61523879/article/details/126431523