目录
一、JSR303
1、什么是JSR303
2、导入pom依赖
3、后端代码
4、前端
二、拦截器
JSR303就是服务端验证
org.hibernate
hibernate-validator
6.0.7.Final
Clazz
都是判空
@NotNull 作用基本数据类型
@NotEmpty 作用集合数组
@NotBlank 作用字符串
package com.zsx.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;
}
}
ClazzController
package com.zsx.ssm.controller;
import com.zsx.ssm.biz.ClazzBiz;
import com.zsx.ssm.model.Clazz;
import com.zsx.ssm.model.dto.ClazzDto;
import com.zsx.ssm.util.PageBean;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
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.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author zsx
* @site 155954····
* @company 交换余生
* @create 2022--08--17 19:07
*/
@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 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 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 fieldErrors = bindingResult.getFieldErrors();
for (FieldError fieldError : fieldErrors) {
//cid/cname/cteacher:不为空
// System.out.println(fieldError.getField() + ":" + fieldError.getDefaultMessage());
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";
}
/**
* 文件上传
* @param clazzDto
* @return
*/
@RequestMapping("/upload")
public String upload(ClazzDto clazzDto){
try {
//前台上传的文件
MultipartFile picFile = clazzDto.getPicFile();
// InputStream inputStream = picFile.getInputStream();
//实际应该配置到 resource.properties 中
String disPath="E:/temp";//图片存放地址
//数据库保存的地址 也是访问地址
String requestPath="/upload/mvc/";
// 拿到上传文件的名字
String filename = picFile.getOriginalFilename();
FileUtils.copyInputStreamToFile(picFile.getInputStream(),new File(disPath+filename));
Clazz clazz = new Clazz();
clazz.setCid(clazzDto.getCid());
clazz.setPic(requestPath+filename);
this.clazzBiz.updateByPrimaryKeySelective(clazz);
// FileOutputStream fileOutputStream = new FileOutputStream(new File("e/temp/1.png"));
// byte[] bbuf = new byte[1024];
// int i=0;
// while (true){
// i=inputStream.read(bbuf,0,i);
// fileOutputStream.write(bbuf,0,i);
// if(i<0){
// break;
// }
// }
} catch (Exception e) {
e.printStackTrace();
}
return "redirect:/clz/list";
}
/**
* 文件下载
* @param clazzDto
* @return
*/
@RequestMapping("/dowload")
public ResponseEntity dowload(ClazzDto clazzDto){
try {
Clazz clazz = this.clazzBiz.selectByPrimaryKey(clazzDto.getCid());
String pic = clazz.getPic();
String disPath="E:/temp";//图片存放地址
//数据库保存的地址 也是访问地址
String requestPath="/upload/mvc/";
String realPath = pic.replace(requestPath,disPath);
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;
}
}
OneHandlerInterceptor
package com.zsx.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 zsx
* @site 155954····
* @company 交换余生
* @create 2022--08--19 19:29
*/
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...");
}
}
clzEdit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
博客的编辑界面
<%--form action="${pageContext.request.contextPath }/clz/${empty b ? 'add' : 'edit'}" method="post">--%>
效果图:
LoginController
package com.zsx.ssm.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
/**
* @author zsx
* @site 155954····
* @company 交换余生
* @create 2022--08--19 19:57
*/
@Controller
public class LoginController {
/**
* 登录
* @param request
* @return
*/
@RequestMapping("/login")
public String login(HttpServletRequest request){
//登录成功保留用户信息
String uname = request.getParameter("uname");
if("zsx".equals(uname)){
request.getSession().setAttribute("uname",uname);
}
return "index";
}
/**
* 退出
* @param request
* @return
*/
@RequestMapping("/logout")
public String logout(HttpServletRequest request){
//消除Session
request.getSession().invalidate();
return "index";
}
}
OneHandlerInterceptor
package com.zsx.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 zsx
* @site 155954····
* @company 交换余生
* @create 2022--08--19 19:29
*/
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");
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...");
}
}
springmvc-servlet.xml
效果图:
未登录被拦截时:
登录后:
登录后访问数据展示页面:
退出登录后: