上一篇文章分享了,上传和下载。本片文章将分享的内容是 JSR303 以及 拦截器
JSR-303 是 JAVA EE 6 中的一项子规范,叫做 Bean Validation,官方参考实现是Hibernate Validator。
简单的说,JSR-303就是用来做表单验证的。
我们之前用js、jQuery做表单验证,JS属于前端的脚本验证(只作用于客户端的浏览器中,可以被屏蔽)
JSR303属于服务端验证
org.hibernate
hibernate-validator
6.0.7.Final
package com.zhw.model;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**
* @NotNull :作用于基本数据类型
* @NotEmpty 作用于集合
* @NotBlank 作用于字符串
*/
public class Clazz {
@NotNull(message = "班级编号不能为空")
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;
}
}
package com.zhw.web;
import com.zhw.biz.ClazzBiz;
import com.zhw.model.Clazz;
import com.zhw.model.dto.ClazzDto;
import com.zhw.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.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author louis
* @create 2022-08-17 18:39
*/
@Controller
@RequestMapping("/clz")
public class ClazzController {
@Autowired
private ClazzBiz clazzBiz;
@RequestMapping("/list")
public String list(HttpServletRequest req, Clazz clazz){
PageBean pageBean = new PageBean();
pageBean.setRequest(req);
List lst = this.clazzBiz.listPager(clazz, pageBean);
req.setAttribute("lst",lst);
req.setAttribute("pageBean",pageBean);
return "clzList";
}
@RequestMapping("/add")
public String add(HttpServletRequest req, Clazz clazz){
this.clazzBiz.insertSelective(clazz);
return "redirect:/clz/list";
}
@RequestMapping("/edit")
public String edit(HttpServletRequest req, Clazz clazz){
this.clazzBiz.updateByPrimaryKeySelective(clazz);
return "redirect:/clz/list";
}
@RequestMapping("/del")
public String del(HttpServletRequest req, Clazz clazz){
this.clazzBiz.deleteByPrimaryKey(clazz.getCid());
return "redirect:/clz/list";
}
@RequestMapping("/toEdit")
public String toEdit(HttpServletRequest req, Clazz clazz){
if(clazz.getCid() != null){
List lst = this.clazzBiz.listPager(clazz, null);
req.setAttribute("b",lst.get(0));
}
return "clzEdit";
}
@RequestMapping("/upload")
public String upload(HttpServletRequest request, ClazzDto clazzDto){
try {
String diskPath = "D:/Temp/images/";
String reqPath = "/upload/mvc/";
MultipartFile picFile = clazzDto.getPicFile();
// 完成文件上传
FileUtils.copyInputStreamToFile(picFile.getInputStream(),new File(diskPath+picFile.getOriginalFilename()));
// 保存到数据库中
Clazz clz = new Clazz();
clz.setCid(clazzDto.getCid());
clz.setPic(reqPath + picFile.getOriginalFilename());
this.clazzBiz.updateByPrimaryKeySelective(clz);
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/clz/list";
}
// 给数据添加服务端校验
@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";
}
@RequestMapping("/download")
public ResponseEntity download(Clazz clazz, HttpServletRequest req){
try {
//先根据文件id查询对应图片信息
Clazz clz = this.clazzBiz.selectByPrimaryKey(clazz.getCid());
String diskPath = "D:/Temp/images/";
String reqPath = "/upload/mvc/";
String realPath = clz.getPic().replace(reqPath,diskPath);
String fileName = realPath.substring(realPath.lastIndexOf("/")+1);
//下载关键代码
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(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
博客的编辑界面
Spring MVC
中的拦截器(Interceptor
)类似于ServLet中的过滤器(Filter
),它主要用于拦截用户请求并作出相应的处理。例如通过拦截器可以进行权限验证、记录请求信息的日志、判断用户是否登录等。
package com.zhw.intercept;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author louis
* @create 2022-08-19 20:51
*/
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...");
}
}
package com.zhw.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author louis
* @create 2022-08-19 20:47
*/
@Controller
public class HelloController {
@RequestMapping("/hello")
public String hello(){
System.out.println("come in ...");
return "index";
}
}
package com.zhw.intercept;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author louis
* @create 2022-08-19 21:11
*/
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、login.jsp
<%--
Created by IntelliJ IDEA.
User: zhw
Date: 2022/8/20
Time: 21:28
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
Title
登录界面
2、LoginController
package com.zhw.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
/**
* @author louis
* @create 2022-08-20 21:29
*/
@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";
}
}
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