项目结构
管理员登录验证以及设计一个拦截器
数据库
user表
entity类
@Component
public class User {
private Long id;//用户id,主键、自增
private String username;//用户名
private String password;//密码
省略get和set方法
这里dao层 mapper文件 service只需设计一个查找username这里先省略不写 等到设计user(admin)增删改查时在贴上
下面直接写
Controler类
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.ischoolbar.programmer.entity.Student;
import com.ischoolbar.programmer.entity.User;
import com.ischoolbar.programmer.service.StudentService;
import com.ischoolbar.programmer.service.UserService;
import com.ischoolbar.programmer.util.CpachaUtil;
/**
* 系统主页控制器
* @author llq
*
*/
@RequestMapping("/system")
@Controller
public class SystemController {
@Autowired
private UserService userService;
@RequestMapping(value = "/index",method=RequestMethod.GET)
public ModelAndView index(ModelAndView model){
model.setViewName("system/index");
return model;
}
/**
* 登陆页面
* @param model
* @return
*/
@RequestMapping(value = "/login",method=RequestMethod.GET)
public ModelAndView login(ModelAndView model){
model.setViewName("system/login");
return model;
}
/**
* 注销登录
* @param request
* @return
*/
@RequestMapping(value = "/login_out",method=RequestMethod.GET)
public String loginOut(HttpServletRequest request){
request.getSession().setAttribute("user", null);
return "redirect:login";
}
/**
* 登录表单提交
* @return
*/
@RequestMapping(value = "/login",method=RequestMethod.POST)
@ResponseBody
public Map<String, String> login(
@RequestParam(value="username",required=true) String username,
@RequestParam(value="password",required=true) String password,
@RequestParam(value="vcode",required=true) String vcode,
HttpServletRequest request
){
Map<String, String> ret = new HashMap<String, String>();
if(StringUtils.isEmpty(username)){
ret.put("type", "error");
ret.put("msg", "用户名不能为空!");
return ret;
}
if(StringUtils.isEmpty(password)){
ret.put("type", "error");
ret.put("msg", "密码不能为空!");
return ret;
}
if(StringUtils.isEmpty(vcode)){
ret.put("type", "error");
ret.put("msg", "验证码不能为空!");
return ret;
}
String loginCpacha = (String)request.getSession().getAttribute("loginCpacha");
if(StringUtils.isEmpty(loginCpacha)){
ret.put("type", "error");
ret.put("msg", "长时间未操作,会话已失效,请刷新后重试!");
return ret;
}
if(!vcode.toUpperCase().equals(loginCpacha.toUpperCase())){
ret.put("type", "error");
ret.put("msg", "验证码错误!");
return ret;
}
request.getSession().setAttribute("loginCpacha", null);
//从数据库中去查找用户
//管理员
User user = userService.findByUserName(username);
if(user == null){
ret.put("type", "error");
ret.put("msg", "不存在该用户!");
return ret;
}
if(!password.equals(user.getPassword())){
ret.put("type", "error");
ret.put("msg", "密码错误!");
return ret;
}
request.getSession().setAttribute("user", user);
ret.put("type", "success");
ret.put("msg", "登录成功!");
return ret;
}
/**
* 显示 验证码
* @param request
* @param vl
* @param w
* @param h
* @param response
*/
@RequestMapping(value="/get_cpacha",method=RequestMethod.GET)
public void getCpacha(HttpServletRequest request,
@RequestParam(value="vl",defaultValue="4",required=false) Integer vl,
@RequestParam(value="w",defaultValue="98",required=false) Integer w,
@RequestParam(value="h",defaultValue="33",required=false) Integer h,
HttpServletResponse response){
CpachaUtil cpachaUtil = new CpachaUtil(vl, w, h);
String generatorVCode = cpachaUtil.generatorVCode();
request.getSession().setAttribute("loginCpacha", generatorVCode);
BufferedImage generatorRotateVCodeImage = cpachaUtil.generatorRotateVCodeImage(generatorVCode, true);
try {
ImageIO.write(generatorRotateVCodeImage, "gif", response.getOutputStream());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
拦截器类
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.ischoolbar.programmer.entity.User;
/**
- 登录过滤拦截器
- @author llq
*/
public class LoginInterceptor implements HandlerInterceptor{
@Override
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
// TODO Auto-generated method stub
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
Object arg2) throws Exception {
// TODO Auto-generated method stub
String url = request.getRequestURI();
//System.out.println("进入拦截器,url = " + url);
Object user = request.getSession().getAttribute("user");
if(user == null){
//表示未登录或者登录状态失效
System.out.println("未登录或登录失效,url = " + url);
if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
//ajax请求
Map<String, String> ret = new HashMap<String, String>();
ret.put("type", "error");
ret.put("msg", "登录状态已失效,请重新去登录!");
response.getWriter().write(JSONObject.fromObject(ret).toString());
return false;
}
response.sendRedirect(request.getContextPath() + "/system/login");
return false;
}
return true;
}
}
工具类
功能生成验证码
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.util.Random;
/**
-
验证码生成器
-
@author llq
*/
public class CpachaUtil {/**
- 验证码来源
/
final private char[] code = {
‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’,
‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’, ‘g’, ‘h’, ‘i’, ‘j’,
‘k’, ‘m’, ‘n’, ‘p’, ‘q’, ‘r’, ‘s’, ‘t’, ‘u’, ‘v’,
‘w’, ‘x’, ‘y’, ‘z’, ‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’,
‘G’, ‘H’, ‘J’, ‘K’, ‘L’, ‘M’, ‘N’, ‘P’, ‘Q’, ‘R’,
‘S’, ‘T’, ‘U’, ‘V’, ‘W’, ‘X’, ‘Y’, ‘Z’
};
/* - 字体
/
final private String[] fontNames = new String[]{
“黑体”, “宋体”, “Courier”, “Arial”,
“Verdana”, “Times”, “Tahoma”, “Georgia”};
/* - 字体样式
*/
final private int[] fontStyles = new int[]{
Font.BOLD, Font.ITALIC|Font.BOLD
};
/**
- 验证码长度
- 默认4个字符
/
private int vcodeLen = 4;
/* - 验证码图片字体大小
- 默认17
/
private int fontsize = 21;
/* - 验证码图片宽度
/
private int width = (fontsize+1)vcodeLen+10;
/ - 验证码图片高度
/
private int height = fontsize+12;
/* - 干扰线条数
- 默认3条
*/
private int disturbline = 3;
public CpachaUtil(){}
/**
- 指定验证码长度
- @param vcodeLen 验证码长度
*/
public CpachaUtil(int vcodeLen) {
this.vcodeLen = vcodeLen;
this.width = (fontsize+1)*vcodeLen+10;
}
/**
- 指定验证码长度、图片宽度、高度
- @param vcodeLen
- @param width
- @param height
*/
public CpachaUtil(int vcodeLen,int width,int height) {
this.vcodeLen = vcodeLen;
this.width = width;
this.height = height;
}
/**
-
生成验证码图片
-
@param vcode 要画的验证码
-
@param drawline 是否画干扰线
-
@return
/
public BufferedImage generatorVCodeImage(String vcode, boolean drawline){
//创建验证码图片
BufferedImage vcodeImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = vcodeImage.getGraphics();
//填充背景色
g.setColor(new Color(246, 240, 250));
g.fillRect(0, 0, width, height);
if(drawline){
drawDisturbLine(g);
}
//用于生成伪随机数
Random ran = new Random();
//在图片上画验证码
for(int i = 0;i < vcode.length();i++){
//设置字体
g.setFont(new Font(fontNames[ran.nextInt(fontNames.length)], fontStyles[ran.nextInt(fontStyles.length)], fontsize));
//随机生成颜色
g.setColor(getRandomColor());
//画验证码
g.drawString(vcode.charAt(i)+"", ifontsize+10, fontsize+5);
}
//释放此图形的上下文以及它使用的所有系统资源
g.dispose();return vcodeImage;
}
/** -
获得旋转字体的验证码图片
-
@param vcode
-
@param drawline 是否画干扰线
-
@return
/
public BufferedImage generatorRotateVCodeImage(String vcode, boolean drawline){
//创建验证码图片
BufferedImage rotateVcodeImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = rotateVcodeImage.createGraphics();
//填充背景色
g2d.setColor(new Color(246, 240, 250));
g2d.fillRect(0, 0, width, height);
if(drawline){
drawDisturbLine(g2d);
}
//在图片上画验证码
for(int i = 0;i < vcode.length();i++){
BufferedImage rotateImage = getRotateImage(vcode.charAt(i));
g2d.drawImage(rotateImage, null, (int) (this.height * 0.7) * i, 0);
}
g2d.dispose();
return rotateVcodeImage;
}
/* -
生成验证码
-
@return 验证码
/
public String generatorVCode(){
int len = code.length;
Random ran = new Random();
StringBuffer sb = new StringBuffer();
for(int i = 0;i < vcodeLen;i++){
int index = ran.nextInt(len);
sb.append(code[index]);
}
return sb.toString();
}
/* -
为验证码图片画一些干扰线
-
@param g
/
private void drawDisturbLine(Graphics g){
Random ran = new Random();
for(int i = 0;i < disturbline;i++){
int x1 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int x2 = ran.nextInt(width);
int y2 = ran.nextInt(height);
g.setColor(getRandomColor());
//画干扰线
g.drawLine(x1, y1, x2, y2);
}
}
/* -
获取一张旋转的图片
-
@param c 要画的字符
-
@return
*/
private BufferedImage getRotateImage(char c){
BufferedImage rotateImage = new BufferedImage(height, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = rotateImage.createGraphics();
//设置透明度为0
g2d.setColor(new Color(255, 255, 255, 0));
g2d.fillRect(0, 0, height, height);
Random ran = new Random();
g2d.setFont(new Font(fontNames[ran.nextInt(fontNames.length)], fontStyles[ran.nextInt(fontStyles.length)], fontsize));
g2d.setColor(getRandomColor());
double theta = getTheta();
//旋转图片
g2d.rotate(theta, height/2, height/2);
g2d.drawString(Character.toString©, (height-fontsize)/2, fontsize+5);
g2d.dispose();return rotateImage;
}
/** -
@return 返回一个随机颜色
/
private Color getRandomColor(){
Random ran = new Random();
return new Color(ran.nextInt(220), ran.nextInt(220), ran.nextInt(220));
}
/* -
@return 角度
*/
private double getTheta(){
return ((int) (Math.random()*1000) % 2 == 0 ? -1 : 1)*Math.random();
}
/**
- @return 验证码字符个数
/
public int getVcodeLen() {
return vcodeLen;
}
/* - 设置验证码字符个数
- @param vcodeLen
/
public void setVcodeLen(int vcodeLen) {
this.width = (fontsize+3)vcodeLen+10;
this.vcodeLen = vcodeLen;
}
/ - @return 字体大小
/
public int getFontsize() {
return fontsize;
}
/* - 设置字体大小
- @param fontsize
/
public void setFontsize(int fontsize) {
this.width = (fontsize+3)vcodeLen+10;
this.height = fontsize+15;
this.fontsize = fontsize;
}
/ - @return 图片宽度
/
public int getWidth() {
return width;
}
/* - 设置图片宽度
- @param width
/
public void setWidth(int width) {
this.width = width;
}
/* - @return 图片高度
/
public int getHeight() {
return height;
}
/* - 设置图片高度
- @param height
/
public void setHeight(int height) {
this.height = height;
}
/* - @return 干扰线条数
/
public int getDisturbline() {
return disturbline;
}
/* - 设置干扰线条数
- @param disturbline
*/
public void setDisturbline(int disturbline) {
this.disturbline = disturbline;
}
- 验证码来源
}
登录界面
登陆后的主界面
再次声明此页面模板以及日后设计的网页模板素材都来源于网络