java登陆验证码与JS无刷新验证

最近公司的项目的登陆模块由我负责,所以就做了个登陆小功能进行练手,其包括了用jQuery对用户名和密码进行不为null验证,和出于安全性考虑加了一个验证码的校验

别的不说先上代码

controller层

CreateImage.java

package com.controller;



import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.io.IOException;

import java.util.Random;



import javax.imageio.ImageIO;

import javax.servlet.ServletException;

import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;



public class CreateImage extends HttpServlet {





	/**

	 * 

	 */

	private static final long serialVersionUID = 1L;



	public void doGet(HttpServletRequest request, HttpServletResponse response)

			throws ServletException, IOException {



		// 获取session

		HttpSession session = null;

		// 控制图片不被缓存

		response.setHeader("expires", -1+"");

		response.setHeader("cache-control", "no-cache");

		response.setHeader("pragma", "no-cache");



		// 在内存中创建一个图片对象

		BufferedImage image = new BufferedImage(80,20,BufferedImage.TYPE_INT_RGB);

		// 设置图片

		Graphics  gra = image.getGraphics();



		// 设置背景

		gra.setColor(Color.BLACK);

		gra.fillRect(0, 0, 80, 20);



		// 设置字体和颜色

		gra.setColor(Color.WHITE);

		gra.setFont(new Font(null,Font.BOLD,14));



		// 给图片上绘制随机的数据

		String code =  createStr(4);

		gra.drawString(code, 5, 15);



		// 存储到session

		session = request.getSession(true);

		session.setAttribute("code", code);

		// 获取字节输出流

		ServletOutputStream out = response.getOutputStream();



		// 输出图片到浏览器客户端

		ImageIO.write(image, "jpg", out);



		// 释放资源

		out.close();



		// 目标是生成一个图片【数字和文本】

		}



		private String createStr(int i) {

		// 定义随机数据的范围

		String data = "ABCDEFGHJKLMNabcretfghwYyk1234567890";

		// 定义一个随机对象

		Random random = new Random();



		// 定义可变的字符串缓冲区对象

		StringBuffer sb = new StringBuffer();



		// 循环

		for (int j = 0; j < i; j++) {

			int index = random.nextInt(data.length() - 1);

			char c = data.charAt(index);

			sb.append(c);

		}

		return sb.toString();

		}



	public void doPost(HttpServletRequest request, HttpServletResponse response)

			throws ServletException, IOException {

		this.doGet(request, response);

	}



}

 该java代码创建一个image对象,也就是画一个图,图的上面添加了4(注:这4不是固定的,可以是5,6,7等,随你定)个随机数,再把这个验证码code放到session域中

在登陆验证的时候与jsp页面传过来的验证码进行校验,相等的话就验证成功。

下面是登陆页面:

login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"

    pageEncoding="UTF-8"%>

<!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>登陆</title>

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>

<script type="text/javascript" src="js/jquery.validate.js"></script></head>

<script type="text/javascript">

	$(function(){

		$("form").validate({

			debug : false,

			rules : {

				name : {

					required : true,

				},

				password : {

					required : true

				}

			},

			messages : {

				name : {

					required : "用户名不能为空!",

				},

				password : {

					required : "密码不能为空!"

				}

			}



		});

	});

</script>





<body>

<center>

	<h1>登陆页面</h1>

	<form action="login.action" method="post">

		用户名:<input type="text" name="name"><br>

		密  码:<input type="password" name="password"><br>

		验证码:<input type="text" name="code" /><br>

		<img src="${pageContext.request.contextPath}/CreateImage"/>  <a href="loginForward.action">看不清,换一张</a><br>

		<input type="submit" value="登陆">

	</form>

	<h2><font color="red">${error }</font></h2>

</center>

</body>

</html>

 以上代码有js验证,可以无刷新的校验用户和密码是否为空。(注:需要添加jquery-1.3.2.min.js和jquery.validate.js两个插件)这里很有趣,我遇到了一个问题(以前都没注意),那就是这两个插件调用的时候是要有顺序的,jquery-1.3.2.min.js要放在jquery.validate.js前面,才能生效。

UserController.java

package com.controller;



import java.awt.Color;

import java.awt.Font;

import java.awt.Graphics;

import java.awt.image.BufferedImage;

import java.io.IOException;

import java.util.List;

import java.util.Random;



import javax.ejb.CreateException;

import javax.imageio.ImageIO;

import javax.servlet.ServletException;

import javax.servlet.ServletOutputStream;

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 com.bean.User;

import com.dao.UserDaoImpl;



/**

 * 基于注解的SpringMVC+ibatis的CRUD

 * @author Saiteam

 *

 */

@Controller

public class UserController {

	

	private UserDaoImpl userDao = new UserDaoImpl();



	@RequestMapping(value="/list.action")

	public String list(HttpServletRequest request) throws Exception{

		List<User> user = userDao.list();

		request.setAttribute("users", user);

		return "list";

	}

	@RequestMapping(value="/saveForward.action")

	public String saveForward(HttpServletRequest request){

		return "add";

	}

	@RequestMapping(value="/add.action")

	public String add(HttpServletRequest request) throws Exception{

		request.setCharacterEncoding("UTF-8");

		User user = new User();

		user.setName(request.getParameter("name"));

		user.setPassword(request.getParameter("password"));

		user.setSex(request.getParameter("sex"));

		user.setAddress(request.getParameter("address"));

		user.setPhone(request.getParameter("phone"));

		user.setEmail(request.getParameter("email"));

		userDao.save(user);

		request.setAttribute("users", userDao.list());

		return "list";

	}

	

	@RequestMapping(value="/delete.action")

	public String delete(HttpServletRequest request) throws Exception{

		int id = Integer.parseInt(request.getParameter("id"));

		userDao.delete(id);

		request.setAttribute("users", userDao.list());

		return "list";

	}

	

	@RequestMapping(value="/update.action")

	public String update(HttpServletRequest request) throws Exception{

		request.setCharacterEncoding("UTF-8");

		User user = new User();

		user.setId(Integer.parseInt(request.getParameter("id")));

		user.setName(request.getParameter("name"));

		user.setPassword(request.getParameter("password"));

		user.setSex(request.getParameter("sex"));

		user.setAddress(request.getParameter("address"));

		user.setPhone(request.getParameter("phone"));

		user.setEmail(request.getParameter("email"));

		userDao.update(user);

		request.setAttribute("users", userDao.list());

		return "list";

	}

	

	@RequestMapping(value="/get.action")

	public String get(HttpServletRequest request) throws Exception{

		int id = Integer.parseInt(request.getParameter("id"));

		request.setAttribute("user", userDao.get(id));

		return "update";

	}

	

	/*

	 * 登陆功能

	 */

	@RequestMapping(value="login.action")

	public String login(HttpServletRequest request) throws Exception{

		

		request.setCharacterEncoding("UTF-8");

		String name = request.getParameter("name");

		String password = request.getParameter("password");

		String userCode = request.getParameter("code");

		

		

		//测试

		System.out.println("-------name-----------"+name);

		System.out.println("-------password-----------"+password);

		System.out.println("-------userCode-----------"+userCode);

		

		

		User model = userDao.login(name, password);

		//测试

		System.out.println("-------------model--------"+model);

			if(model != null && !model.equals("")){

				//判断验证码是否为空

				if(userCode==null || "".equals(userCode)){

					request.setAttribute("error", "请填写验证码!");

					return "forward:/login.jsp";

				}

				//从session中获取code验证码 1.先获取session

				HttpSession session = request.getSession(false);

				//判断session是否为空

				if(session == null){

					System.out.println("服务器session为null不处理添加用户的逻辑。");

					return "forward:/login.jsp";

				}

				//2.获取session中的code

				String serverCode = (String) session.getAttribute("code");

				//判断

				if(serverCode == null || "".equals(serverCode)){

					System.out.println("服务器中的校验码为null不处理添加用户的逻辑!");

					return "forward:/login.jsp";

				}

				

				//判断jsp页面传来的验证码与后台服务器session中带的验证码是否相等

				if(userCode.equals(serverCode)){

					request.setAttribute("users", userDao.list());

					return "list";

				}else{

					request.setAttribute("error", "验证码错误!");

					return "forward:/login.jsp";

				}

			}else{

				request.setAttribute("error", "用户或密码错误!");

				return "forward:/login.jsp";

			}

		

	}

	

	//实现注册功能

	@RequestMapping(value="register.action")

	public String register(HttpServletRequest request) throws Exception{

		request.setCharacterEncoding("UTF-8");

		User user = new User();

		user.setName(request.getParameter("name"));

		user.setPassword(request.getParameter("password"));

		user.setSex(request.getParameter("sex"));

		user.setAddress(request.getParameter("address"));

		user.setPhone(request.getParameter("phone"));

		user.setEmail(request.getParameter("email"));

		userDao.save(user);

		return "forward:/index.jsp";

	}

	

	

	/**

	 * 跳转到登陆页面

	 * @param request

	 * @return

	 */

	@RequestMapping(value="loginForward.action")

	public String loginForwad(HttpServletRequest request){

		return "forward:/login.jsp";

	}

	/**

	 * 转发到注册页面

	 * @param request

	 * @return

	 */

	@RequestMapping(value="rgf.action")

	public String registerForwad(HttpServletRequest request){

		return "forward:/register.jsp";

	}

	

	

	

}

 我在controller层使用了SpringMVC框架,在DAO层使用了Ibatis框架,做了CRUD的功能,代码就比较乱了,该层获取浏览器传来的参数,包括name(用户名),password(密码)和code(验证码),对他们进行校验,校验成功就能获得下一步的操作了。

以上仅仅是个人的一些经验,欢迎大家一起交流。

你可能感兴趣的:(java)