拦截器类:实现HandlerInterception
package com.yx.interceptor;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("执行后,返回前执行....");
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
//在处理过程中进行拦截
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//已经登录了就放行 否则进行拦截
HttpSession session=request.getSession();
if(session.getAttribute("user")!=null){
return true;//放行
}else{
//没有登录 跳转到登录页面进行登录操作
response.sendRedirect(request.getContextPath()+"/login");
return false;
}
}
}
在SpringMVC.xml文件中注册拦截器:
常量类:
package com.yx.utils;
public class Constants {
public final static int OK_CODE = 0; //0表示Ok
public final static int FAIL_CODE = 400;
public final static String OK_MSG = "请求成功";
public final static String FAIL_MSG = "请求失败";
public final static int STATUS_0 = 0;//可用状态
public final static int STATUS_1 = 1;//禁用状态
public final static String CACHE_NAME = "KACache";
}
返回类型实体类:
package com.yx.utils;
import java.io.Serializable;
/**
* 数据封闭类,返回给前端
*/
public class DataInfo implements Serializable {
private static final long serialVersionUID = 1L;
private Integer code;
private String msg;
private Object data; //json数据
private Long count; // 分页信息:总条数
public DataInfo() {
}
public DataInfo(Integer code, String msg, Object data) {
this.code = code;
this.msg = msg;
this.data = data;
}
public DataInfo(Integer code, String msg, Object data, Long count) {
this.code = code;
this.msg = msg;
this.data = data;
this.count = count;
}
public Integer getCode() {
return code;
}
public static DataInfo ok() {
return new DataInfo(Constants.OK_CODE, Constants.OK_MSG, null);
}
public static DataInfo ok(Object data) {
return new DataInfo(Constants.OK_CODE, Constants.OK_MSG, data);
}
public static DataInfo ok(String msg, long count, Object data) {
return new DataInfo(Constants.OK_CODE, Constants.OK_MSG, data,count);
}
public static DataInfo ok(String msg, Object data) {
return new DataInfo(Constants.OK_CODE, msg, data);
}
public static DataInfo fail(String msg) {
return new DataInfo(Constants.FAIL_CODE, msg, null);
}
public static DataInfo fail(int errorCode, String msg) {
return new DataInfo(errorCode, msg, null);
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Long getCount() {
return count;
}
public void setCount(Long count) {
this.count = count;
}
}
return:返回统一的返回结果
验证码返回对象:
package com.yx.codeutil;
public class VerifyCode {
private String code;
private byte[] imgBytes;
private long expireTime;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public byte[] getImgBytes() {
return imgBytes;
}
public void setImgBytes(byte[] imgBytes) {
this.imgBytes = imgBytes;
}
public long getExpireTime() {
return expireTime;
}
public void setExpireTime(long expireTime) {
this.expireTime = expireTime;
}
}
接口:
package com.yx.codeutil;
import java.io.IOException;
import java.io.OutputStream;
public interface IVerifyCodeGen {
/**
* 生成验证码并返回code,将图片写的os中
*
* @param width
* @param height
* @param os
* @return
* @throws IOException
*/
String generate(int width, int height, OutputStream os) throws IOException;
/**
* 生成验证码对象
*
* @param width
* @param height
* @return
* @throws IOException
*/
VerifyCode generate(int width, int height) throws IOException;
}
实现类:
package com.yx.codeutil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
/**
* 验证码实现类
*/
public class SimpleCharVerifyCodeGenImpl implements IVerifyCodeGen {
private static final Logger logger = LoggerFactory.getLogger(SimpleCharVerifyCodeGenImpl.class);
private static final String[] FONT_TYPES = { "\u5b8b\u4f53", "\u65b0\u5b8b\u4f53", "\u9ed1\u4f53", "\u6977\u4f53", "\u96b6\u4e66" };
private static final int VALICATE_CODE_LENGTH = 4;
/**
* 设置背景颜色及大小,干扰线
*
* @param graphics
* @param width
* @param height
*/
private static void fillBackground(Graphics graphics, int width, int height) {
// 填充背景
graphics.setColor(Color.WHITE);
//设置矩形坐标x y 为0
graphics.fillRect(0, 0, width, height);
// 加入干扰线条
for (int i = 0; i < 8; i++) {
//设置随机颜色算法参数
graphics.setColor(RandomUtils.randomColor(40, 150));
Random random = new Random();
int x = random.nextInt(width);
int y = random.nextInt(height);
int x1 = random.nextInt(width);
int y1 = random.nextInt(height);
graphics.drawLine(x, y, x1, y1);
}
}
/**
* 生成随机字符
*
* @param width
* @param height
* @param os
* @return
* @throws IOException
*/
@Override
public String generate(int width, int height, OutputStream os) throws IOException {
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics graphics = image.getGraphics();
fillBackground(graphics, width, height);
String randomStr = RandomUtils.randomString(VALICATE_CODE_LENGTH);
createCharacter(graphics, randomStr);
graphics.dispose();
//设置JPEG格式
ImageIO.write(image, "JPEG", os);
return randomStr;
}
/**
* 验证码生成
*
* @param width
* @param height
* @return
*/
@Override
public VerifyCode generate(int width, int height) {
VerifyCode verifyCode = null;
try (
//将流的初始化放到这里就不需要手动关闭流
ByteArrayOutputStream baos = new ByteArrayOutputStream();
) {
String code = generate(width, height, baos);
verifyCode = new VerifyCode();
verifyCode.setCode(code);
verifyCode.setImgBytes(baos.toByteArray());
} catch (IOException e) {
logger.error(e.getMessage(), e);
verifyCode = null;
}
return verifyCode;
}
/**
* 设置字符颜色大小
*
* @param g
* @param randomStr
*/
private void createCharacter(Graphics g, String randomStr) {
char[] charArray = randomStr.toCharArray();
for (int i = 0; i < charArray.length; i++) {
//设置RGB颜色算法参数
g.setColor(new Color(50 + RandomUtils.nextInt(100),
50 + RandomUtils.nextInt(100), 50 + RandomUtils.nextInt(100)));
//设置字体大小,类型
g.setFont(new Font(FONT_TYPES[RandomUtils.nextInt(FONT_TYPES.length)], Font.BOLD, 26));
//设置x y 坐标
g.drawString(String.valueOf(charArray[i]), 15 * i + 5, 19 + RandomUtils.nextInt(8));
}
}
}
生成随机数工具类:
package com.yx.codeutil;
import java.awt.*;
import java.util.Random;
public class RandomUtils extends org.apache.commons.lang3.RandomUtils {
private static final char[] CODE_SEQ = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J',
'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '2', '3', '4', '5', '6', '7', '8', '9' };
private static final char[] NUMBER_ARRAY = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
private static Random random = new Random();
public static String randomString(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(String.valueOf(CODE_SEQ[random.nextInt(CODE_SEQ.length)]));
}
return sb.toString();
}
public static String randomNumberString(int length) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < length; i++) {
sb.append(String.valueOf(NUMBER_ARRAY[random.nextInt(NUMBER_ARRAY.length)]));
}
return sb.toString();
}
public static Color randomColor(int fc, int bc) {
int f = fc;
int b = bc;
Random random = new Random();
if (f > 255) {
f = 255;
}
if (b > 255) {
b = 255;
}
return new Color(f + random.nextInt(b - f), f + random.nextInt(b - f), f + random.nextInt(b - f));
}
public static int nextInt(int bound) {
return random.nextInt(bound);
}
}
生成验证码接口:
/**
* 获取验证码方法
* @param request
* @param response
*/
@RequestMapping("/verifyCode")
public void verifyCode(HttpServletRequest request, HttpServletResponse response) {
IVerifyCodeGen iVerifyCodeGen = new SimpleCharVerifyCodeGenImpl();
try {
//设置长宽
VerifyCode verifyCode = iVerifyCodeGen.generate(80, 28);
String code = verifyCode.getCode();
//将VerifyCode绑定session
request.getSession().setAttribute("VerifyCode", code);
//设置响应头
response.setHeader("Pragma", "no-cache");
//设置响应头
response.setHeader("Cache-Control", "no-cache");
//在代理服务器端防止缓冲
response.setDateHeader("Expires", 0);
//设置响应内容类型
response.setContentType("image/jpeg");
response.getOutputStream().write(verifyCode.getImgBytes());
response.getOutputStream().flush();
} catch (IOException e) {
System.out.println("异常处理");
}
}
用户登录验证接口:
/**
* 登录验证
*/
@RequestMapping("/loginIn")
public String loginIn(HttpServletRequest request, Model model){
//获取用户名与密码
String username = request.getParameter("username");
String password = request.getParameter("password");
String code=request.getParameter("captcha");
String type=request.getParameter("type");
//判断验证码是否正确(验证码已经放入session)
HttpSession session = request.getSession();
String realCode = (String)session.getAttribute("VerifyCode");
if (!realCode.toLowerCase().equals(code.toLowerCase())){
model.addAttribute("msg","验证码不正确");
return "login";
}else{
//验证码正确则判断用户名和密码
if(type.equals("1")){//管理员信息
//用户名和密码是否正确
Admin admin=adminService.queryUserByNameAndPassword(username,password);
if(admin==null){//该用户不存在
model.addAttribute("msg","用户名或密码错误");
return "login";
}
session.setAttribute("user",admin);
session.setAttribute("type","admin");
}else{//来自读者信息表
ReaderInfo readerInfo=readerService.queryUserInfoByNameAndPassword(username,password);
if(readerInfo==null){
model.addAttribute("msg","用户名或密码错误");
return "login";
}
session.setAttribute("user",readerInfo);
session.setAttribute("type","reader");
}
return "index";
}
}