目录
一、JSR303
1、pom依赖
2、后端
①实体类
②ClazzController.java
3、前端
二、拦截器
1、拦截器的初步认识
①OneHandlerInterceptor
②HelloController
③springmvc-servlet的配置
2、拦截器链
①TwoHandlerInterceptor
②springmvc-servlet的配置
3、登录权限控制
3.1 前端
3.2 后端
org.hibernate
hibernate-validator
6.0.7.Final
package com.chenchen.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;
}
}
package com.chenchen.ssm.web;
import com.chenchen.ssm.biz.ClazzBiz;
import com.chenchen.ssm.model.Clazz;
import com.chenchen.ssm.model.dto.ClazzDto;
import com.chenchen.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 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 : 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(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
}
clzEdit.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
编辑界面
<%--
运行效果:
输入为空则提示
package com.chenchen.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 chenchen
* @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...");
}
}
package com.chenchen.ssm.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* @author chenchen
* @create 2022-08-19 19:21
*/
@Controller
public class HelloController {
@RequestMapping("hello")
public String hello(){
System.out.println("进入业务方法...");
return "index";
}
}
package com.chenchen.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 chenchen
* @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...");
}
}
运行效果:
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" %>
Title
登录界面
LoginController
package com.chenchen.ssm.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
/**
* @author chenchen
* @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";
}
}
运行效果: