作为项目的开始,首先进行简单的登录检测,同时加入了拦截器机制。
1、建立User.java类
package cn.mldn.szq.model;
import java.io.Serializable;
public class User implements Serializable {
private Integer userId;
private String userName;
private String userPass;
}
有了基础的User类之后,为其建立相应的DAO接口,同时使用MyBatis中的注解形式来完成接口方法的实现
登录验证中,一般会加入验证码机制,而验证码直接在控制层进行验证,所以只需要验证用户输入的用户名和密码,而在实际的开发中有这样几种方式来提示用户:①单独验证用户名和密码,然后将相应的提示提示给用户。②同时验证用户名和密码 ,只有当两个都相同的时候才可以进行登录。第一种方式可以对用户进行精确地信息提示,而后一种只能模糊的提示用户。本次使用了第二种验证方式。
2、建立IUserDAO.java接口
package cn.mldn.szq.mapper;
import org.apache.ibatis.annotations.Select;
import cn.mldn.szq.model.User;
public interface IUserDAO {
@Select("SELECT t.userid AS userId,t.username AS userName,t.userpwd AS userPass"
+" FROM t_user t"
+ " WHERE t.username=#{userName} AND t.userpwd=#{userPass}")
public User findByIdAndPwd(User vo);
}
考虑到后面在验证用户成功之后需要保存相关的用户信息,所以在DAO中直接将所有的用户信息都查询出来。
3、建立IUserService.java接口,以及其实现子类IUserServiceImpl.java类
package cn.mldn.szq.service;
import cn.mldn.szq.model.User;
public interface IUserService {
public User validateUser(User vo);
}
package cn.mldn.szq.service.impl;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import cn.mldn.szq.mapper.IUserDAO;
import cn.mldn.szq.model.User;
import cn.mldn.szq.service.IUserService;
@Service
public class UserServiceImpl implements IUserService {
@Resource
private IUserDAO userDAO;
@Override
public User validateUser(User vo) {
if (vo != null) {
if (vo.getUserName() != null && !"".equals(vo.getUserName()) && vo.getUserPass() != null
&& !"".equals(vo.getUserPass())) {
return this.userDAO.findByIdAndPwd(vo);
}
}
return null;
}
}
有了业务层的支持之后,可以建立相应的controller,此处需要建立两个controller,一个是进行验证码的生成与验证的YanzhengmaController.java,而另一个用于的登录检测的控制LoginController.java
4、建立YanzhengmaController.java和LoginController.java,用户登录成功后,为了方便后面的检测,所以需要将查询出来的用户信息存放在session属性范围中。
package cn.mldn.szq.controller.login;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.mldn.szq.model.User;
import cn.mldn.szq.service.IUserService;
@Controller
@RequestMapping("logincontroller")
public class LoginController {
@Resource
private IUserService userService;
@RequestMapping("login")
@ResponseBody
public int login(HttpServletRequest request,User vo){
int flag = 0;
HttpSession session = request.getSession(true);
session.removeAttribute("uid");
User user = this.userService.validateUser(vo);
//用户登录成功,需要将用户的ID存放在Session属性范围中,以供拦截器和其他操作检测
if(user != null){
session.setAttribute("uid", user.getUserId());
flag = 1;
}
System.out.println(session.getAttribute("uid"));
return flag;
}
}
package cn.mldn.szq.controller.code;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import cn.mldn.szq.util.VerifyCodeUtils;
@Controller
@RequestMapping("/code")
public class YanzhengmaController {
@RequestMapping("init")
public void findAllWhere(HttpServletRequest request,String f, HttpServletResponse response) {
response.setHeader("Pragma", "No-cache");
response.setHeader("Cache-Control", "no-cache");
response.setDateHeader("Expires", 0);
response.setContentType("image/jpeg");
//生成随机字串
String verifyCode = VerifyCodeUtils.generateVerifyCode(4);
//存入会话session
HttpSession session = request.getSession(true);
//删除以前的
session.removeAttribute("yanzhengma");
session.setAttribute("yanzhengma", verifyCode.toLowerCase());
//生成图片
int w = 150, h = 50;
try {
VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);
} catch (IOException e) {
e.printStackTrace();
}
}
//验证验证码
@RequestMapping("validatecode")
@ResponseBody
public int isyanzhengma(HttpServletRequest request,String yanzhengma) {
HttpSession session = request.getSession(true);
String yanzhengmasession=(String)session.getAttribute("yanzhengma");
int flag=0;
if(yanzhengmasession!=null&&yanzhengmasession.equalsIgnoreCase(yanzhengma)){
flag=1;
}
return flag;
}
}
至此,后台代码基本就结束了,开始建立前台页面,而本次的页面比较简单,并没有加入样式的控制,同时使用了jQuery来进行控制判断,如下的login.ftl文件
5、建立login.ftl文件
<#assign base=request.contextPath/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form id="loginForm">
<div>
用户名:<input type="text" id="userName"/></br>
密 码:<input type="password" id="userPass"/></br>
验证码:<input type="text" maxlength="4" id="code"/>
<img src="${base}/code/init" id="codeImg"/><span id="codeImgSpan"></span></br>
<input type="button" value="登录" id="subBut"/>
</div>
</form>
<script type="text/javascript" src="${base}/plugins/jquery.min.js"></script>
<script>
//点击验证码图片切换验证码
$("#codeImg").on("click",function(){
$(this).prop("src","${base}/code/init?temp="+Math.random());
});
//接收验证码验证后的返回结果,用于登录检测时使用
var iscode = 0;
//进行验证码验证
$("#code").on("blur",function(){
var data = $(this).val();
$.ajax({
url:"${base}/code/validatecode",
data:{yanzhengma:data},
dataType:"json",
success:function(data){
//记录验证结果
iscode = data;
if(data == 0){
$("#codeImgSpan").html("<font color='red'>验证码错误!</font>");
}else{
$("#codeImgSpan").empty();
}
}
});
});
//进行登录验证
$("#subBut").on("click",function(){
if(iscode == 0){
alert("请确认验证码");
}else{
var userNameval = $("#userName").val();
var userPassval = $("#userPass").val();
if(userNameval != '' && userPassval != ''){
$.ajax({
url:"${base}/logincontroller/login",
data:{"userName":userNameval,"userPass":userPassval},
type:"get",
dataType:"json",
success:function(data){
console.log(data);
if(data == 0){
alert("用户名或密码错误!");
}else{
alert("登录成功");
location.href="${base}/index";
}
}
});
}else{
alert("用户名密码不能空!");
}
}
});
</script>
</body>
</html>
第一次接触这种ftl文件,“<#assign base=request.contextPath/>”用来设置项目的名称,而后访问其他路径的时候使用“${base}/logincontroller/login”,相当于jsp中的“<%=reqeust.getContextPath()%>”。
当登录操作完成后,就需要加入拦截器的操作,因为在web.xml文件中配置的核心控制器的映射路径为“/*”,也就是会对所有访问的路径都进行拦截,所以还需要建立一个针对于frameset框架以及登录页面的控制器来设置访问的路径
6、建立frameset页面框架index.ftl以及IndexController.java
package cn.mldn.szq.controller.index;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class IndexController {
@RequestMapping("/")
String login() {
return "login";
}
@RequestMapping("index")
String index() {
return "index";
}
@RequestMapping("top")
String top(){
return "top";
}
@RequestMapping("left")
String left(){
return "left";
}
}
例:index.ftl如下
<#assign base=request.contextPath/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<frameset rows="15%,*">
<frame src="${base}/top" name="">
<frameset cols="15%,*">
<frame src="${base}/left" name="">
<frame src="" name="bbb">
</frameset>
</html>
top.ftl
<#assign base=request.contextPath/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1 align="center">新书到了小伙伴们快来看啊!!!<h1/>
</body>
</html>
left.ftl
<#assign base=request.contextPath/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="${base}/book/list" target="bbb">书籍列表</a><br>
<a href="${base}/book/toAddftl" target="bbb">添加书籍</a><br>
</body>
</html>
7、建立相应的拦截器LoginInterceptor.java,需要实现HandlerInterceptor接口并且覆写preHandler()方法,需要获取之前在登录成功之后保存在session属性范围中的“uid”属性,如果能够获取到“uid”的值,说明用户已经登录,否则进行拦截
package cn.mldn.szq.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
}
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object arg2) throws Exception {
if(null != request.getSession().getAttribute("uid")){ //不拦截
return true;
}else{
//重定向到登录页
response.sendRedirect(request.getContextPath() + "/");
return false;
}
}
}
当定义好自己的拦截器之后,还需要在spring-mvc.xml文件中进行相关的配置,如下
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/> <!--对所有的路径进行拦截-->
<mvc:exclude-mapping path="/"/> <!--访问的“/”路径不拦截-->
<mvc:exclude-mapping path="/logincontroller/**"/> <!--登录操作不拦截-->
<mvc:exclude-mapping path="/code/**"/> <!--验证码操作不拦截-->
<mvc:exclude-mapping path="/plugins/**"/> <!--要访问的jQuery文件不拦截-->
<bean class="cn.mldn.szq.interceptor.LoginInterceptor" />
</mvc:interceptor>
</mvc:interceptors>
这样一个完整的登录检测操作就已经配置完成,只要用户处于非登录状态,就不能执行其他操作。
8、在验证码控制层中调用了生成验证码的类VerifyCodeUtils.java如下
package cn.mldn.szq.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Random;
import javax.imageio.ImageIO;
public class VerifyCodeUtils{
//使用到Algerian字体,系统里没有的话需要安装字体,字体只显示大写,去掉了1,0,i,o几个容易混淆的字符
public static final String VERIFY_CODES = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
private static Random random = new Random();
/**
* 使用系统默认字符源生成验证码
* @param verifySize 验证码长度
* @return
*/
public static String generateVerifyCode(int verifySize){
return generateVerifyCode(verifySize, VERIFY_CODES);
}
/**
* 使用指定源生成验证码
* @param verifySize 验证码长度
* @param sources 验证码字符源
* @return
*/
public static String generateVerifyCode(int verifySize, String sources){
if(sources == null || sources.length() == 0){
sources = VERIFY_CODES;
}
int codesLen = sources.length();
Random rand = new Random(System.currentTimeMillis());
StringBuilder verifyCode = new StringBuilder(verifySize);
for(int i = 0; i < verifySize; i++){
verifyCode.append(sources.charAt(rand.nextInt(codesLen-1)));
}
return verifyCode.toString();
}
/**
* 生成随机验证码文件,并返回验证码值
* @param w
* @param h
* @param outputFile
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, File outputFile, int verifySize) throws IOException{
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, outputFile, verifyCode);
return verifyCode;
}
/**
* 输出随机验证码图片流,并返回验证码值
* @param w
* @param h
* @param os
* @param verifySize
* @return
* @throws IOException
*/
public static String outputVerifyImage(int w, int h, OutputStream os, int verifySize) throws IOException{
String verifyCode = generateVerifyCode(verifySize);
outputImage(w, h, os, verifyCode);
return verifyCode;
}
/**
* 生成指定验证码图像文件
* @param w
* @param h
* @param outputFile
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, File outputFile, String code) throws IOException{
if(outputFile == null){
return;
}
File dir = outputFile.getParentFile();
if(!dir.exists()){
dir.mkdirs();
}
try{
outputFile.createNewFile();
FileOutputStream fos = new FileOutputStream(outputFile);
outputImage(w, h, fos, code);
fos.close();
} catch(IOException e){
throw e;
}
}
/**
* 输出指定验证码图片流
* @param w
* @param h
* @param os
* @param code
* @throws IOException
*/
public static void outputImage(int w, int h, OutputStream os, String code) throws IOException{
int verifySize = code.length();
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
Random rand = new Random();
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
Color[] colors = new Color[5];
Color[] colorSpaces = new Color[] { Color.WHITE, Color.CYAN,
Color.GRAY, Color.LIGHT_GRAY, Color.MAGENTA, Color.ORANGE,
Color.PINK, Color.YELLOW };
float[] fractions = new float[colors.length];
for(int i = 0; i < colors.length; i++){
colors[i] = colorSpaces[rand.nextInt(colorSpaces.length)];
fractions[i] = rand.nextFloat();
}
Arrays.sort(fractions);
g2.setColor(Color.GRAY);// 设置边框色
g2.fillRect(0, 0, w, h);
Color c = getRandColor(200, 250);
g2.setColor(c);// 设置背景色
g2.fillRect(0, 2, w, h-4);
//绘制干扰线
Random random = new Random();
g2.setColor(getRandColor(160, 200));// 设置线条的颜色
for (int i = 0; i < 20; i++) {
int x = random.nextInt(w - 1);
int y = random.nextInt(h - 1);
int xl = random.nextInt(6) + 1;
int yl = random.nextInt(12) + 1;
g2.drawLine(x, y, x + xl + 40, y + yl + 20);
}
// 添加噪点
float yawpRate = 0.05f;// 噪声率
int area = (int) (yawpRate * w * h);
for (int i = 0; i < area; i++) {
int x = random.nextInt(w);
int y = random.nextInt(h);
int rgb = getRandomIntColor();
image.setRGB(x, y, rgb);
}
shear(g2, w, h, c);// 使图片扭曲
g2.setColor(getRandColor(100, 160));
int fontSize = h-4;
Font font = new Font("Algerian", Font.ITALIC, fontSize);
g2.setFont(font);
char[] chars = code.toCharArray();
for(int i = 0; i < verifySize; i++){
AffineTransform affine = new AffineTransform();
affine.setToRotation(Math.PI / 4 * rand.nextDouble() * (rand.nextBoolean() ? 1 : -1), (w / verifySize) * i + fontSize/2, h/2);
g2.setTransform(affine);
g2.drawChars(chars, i, 1, ((w-10) / verifySize) * i + 5, h/2 + fontSize/2 - 10);
}
g2.dispose();
ImageIO.write(image, "jpg", os);
}
private static Color getRandColor(int fc, int bc) {
if (fc > 255)
fc = 255;
if (bc > 255)
bc = 255;
int r = fc + random.nextInt(bc - fc);
int g = fc + random.nextInt(bc - fc);
int b = fc + random.nextInt(bc - fc);
return new Color(r, g, b);
}
private static int getRandomIntColor() {
int[] rgb = getRandomRgb();
int color = 0;
for (int c : rgb) {
color = color << 8;
color = color | c;
}
return color;
}
private static int[] getRandomRgb() {
int[] rgb = new int[3];
for (int i = 0; i < 3; i++) {
rgb[i] = random.nextInt(255);
}
return rgb;
}
private static void shear(Graphics g, int w1, int h1, Color color) {
shearX(g, w1, h1, color);
shearY(g, w1, h1, color);
}
private static void shearX(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(2);
boolean borderGap = true;
int frames = 1;
int phase = random.nextInt(2);
for (int i = 0; i < h1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(0, i, w1, 1, (int) d, 0);
if (borderGap) {
g.setColor(color);
g.drawLine((int) d, i, 0, i);
g.drawLine((int) d + w1, i, w1, i);
}
}
}
private static void shearY(Graphics g, int w1, int h1, Color color) {
int period = random.nextInt(40) + 10; // 50;
boolean borderGap = true;
int frames = 20;
int phase = 7;
for (int i = 0; i < w1; i++) {
double d = (double) (period >> 1)
* Math.sin((double) i / (double) period
+ (6.2831853071795862D * (double) phase)
/ (double) frames);
g.copyArea(i, 0, 1, h1, 0, (int) d);
if (borderGap) {
g.setColor(color);
g.drawLine(i, (int) d, i, 0);
g.drawLine(i, (int) d + h1, i, h1);
}
}
}
public static void main(String[] args) throws IOException{
File dir = new File("F:/demo");
int w = 200, h = 80;
for(int i = 0; i < 50; i++){
String verifyCode = generateVerifyCode(4);
File file = new File(dir, verifyCode + ".jpg");
outputImage(w, h, file, verifyCode);
}
}
}