登录界面设计与实现

效果图

1、主要的html代码如下:其中有一些不规范的地方请勿模仿,譬如JS代码也夹杂在其中,本人建议尽量把JS代码单独写在一个文件中,有利于后期维护,当然代码看起来也美观

<form action="login">
				<div class="jx-l-user">
					<div class="jx-l-tt" style="">
						<span>账号登录</span>
					</div>
					<div class="jx-l-ui">
						<div id="u-name" class="jx-user">
							<input id="username" class="u-input" type="text" placeholder="用户名" name="username" /> <b style="background-image: url(img/uh.png);"></b>
							<br>
							<span id="username-message" style="color:red;"></span>
							<script type="text/javascript">
								$("#username").blur(function () {
									if ($("#username").val() != "") {
										$("#username-message").empty();
									}
								});
							</script>
						</div>
						<div id="u-pass" class="jx-user">
							<input id="password" class="u-pass" type="password" placeholder="........" name="password" /> <b style="background-image: url(img/pw.png);"></b><br>
							<span id="password-message" style="color:red;"></span>
							<script type="text/javascript">
								$("#password").blur(function () {
									if ($("#password").val() != "") {
										$("#password-message").empty();
									}
								});
							</script>
						</div>
						<div class="jx-table">
							<div class="row">
								<div class="cell" id="cell">
									<input id="u-ver" type="text" name="input" placeholder="验证码" />
									<span id="code_message" style="color:red;"></span>
									<script type="text/javascript">
										$("#u-ver").blur(function () {
											if ($("#u-ver").val() != "") {
												$("#code_message").empty();
											}
										});
									</script>
								</div>
								<div class="cell" style="width: 58%;">
									<img id="verificationImg" alt="验证码" onclick="load()" />
									<a href="javascript:reload();"><label>换一张</label></a>
								</div>
							</div>
							<div class="row">
								<div class="cell" style="color: #FFFFFF;">
									<input type="checkbox" id="remember_me" />记住账号
								</div>
								<div class="cell">
									<input id="login" type="button" class="login" value="登录" onclick="submitlogin()">
								</div>
							</div>
						</div>
						<div id="error_login" style="color:red;text-align: center;line-height: 10px;"></div>
					</div>
				</div>
			</form>

2、jQuery实现用户名,密码,验证码非空判定

if ($('#username').val() == "") {
				$("#username-message").html("请输入用户名");
				return false;
			}
			if ($('#password').val() == "") {
				$("#password-message").html("请输入密码");
				return false;
			}
			if ($('#u-ver').val() == "") {
				$("#code_message").html("请输入验证码");
				return false;
			}

3、jQuery加载验证码的方式

//加载验证码图片
		$(document).ready(function () {
			load();
		});

		function load() {
			$("#verificationImg").attr("src", "imageServlet?date=" + new Date());
		}
		function reload() {
			load();
		};

4、后台生成验证码代码

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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * 生成验证码图片
 */
public class ImgVerficationServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("utf-8");
		response.setContentType("image/JPG");
		BufferedImage bfi = new BufferedImage(80,25,BufferedImage.TYPE_INT_RGB);
		Graphics g = bfi.getGraphics();
		g.fillRect(0, 0, 80, 25);
		
		//验证码字符范围
		char[] ch = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
		Random r = new Random(); 
		int index;  
				StringBuffer sb = new StringBuffer(); //保存字符串
				for(int i=0; i<4; i++){
					index = r.nextInt(ch.length);
					g.setColor(new Color(r.nextInt(255),r.nextInt(255),r.nextInt(255)));
					Font font = new Font("宋体", 30, 20);
					g.setFont(font);
					g.drawString(ch[index]+"", (i*20)+2, 23);
					sb.append(ch[index]);
				}
				
				// 添加噪点
			    int area = (int) (0.02 * 80 * 25);
			    for(int i=0; i<area; ++i){
			        int x = (int)(Math.random() * 80);
			        int y = (int)(Math.random() * 25);
			        bfi.setRGB(x, y, (int)(Math.random() * 255));
			    }
			    
			  /*//设置验证码中的干扰线
			    for (int i = 0; i < 6; i++) {  
				      //随机获取干扰线的起点和终点
				      int xstart = (int)(Math.random() * 80);
				      int ystart = (int)(Math.random() * 25);
				      int xend = (int)(Math.random() * 80);
				      int yend = (int)(Math.random() * 25);
				      g.setColor(interLine(1, 255));
				      g.drawLine(xstart, ystart, xend, yend);
				    }*/
			   HttpSession session=request.getSession();  //保存到session
				session.setAttribute("verificationCode", sb.toString());
				ImageIO.write(bfi, "JPG", response.getOutputStream());  //写到输出流
	}
	
	/**
	   * 获取随机的颜色值,r,g,b的取值在Low到High之间
	   * @param L 左区间
	   * @param R 右区间
	   * @return 返回随机颜色值
	   */
	  private static Color interLine(int Low, int High){
	    if(Low > 255)
	    	Low = 255;
	    if(High > 255)
	    	High = 255;
	    if(Low < 0)
	    	Low = 0;
	    if(High < 0)
	    	High = 0;
	    int interval = High - Low; 
	    int r = Low + (int)(Math.random() * interval);
	    int g = Low + (int)(Math.random() * interval);
	    int b = Low + (int)(Math.random() * interval);
	    return new Color(r, g, b);
	  }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

5、登录ajax请求

$.ajax({
				url: "login.da",//servlet路径
				type: "post",//提交方式
				dataType: "json",
				async: true,
				contentType: "application/x-www-form-urlencoded;charset=utf-8",
				data: {
					"username": $('#username').val(),
					"password": $('#password').val(),
					"u-ver": $('#u-ver').val(),
				},//传入的数据为输入的登录名
				//传入验证码
				success: function (data) {
					if (data == "0") {
						window.location.href = "index.html";
					}
					if (data == "2") {
						//alert("用户名或密码错误,请重新登陆");
						$("#error_login").html("用户名或密码错误,请重新登陆");
						$('#username').empty();
						$('#username').empty();
					}
					if (data == "1") {
						//验证码错误
						$("#code_message").html("验证码错误");
						$('#u-ver').val() = "";
						load();
					}
				}
			})

 6、后台Servlet代码

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	//执行登录用户密码验证
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//设置接收参数的字符集
				request.setCharacterEncoding("utf-8");
				response.setContentType("text/html");
				response.setCharacterEncoding("utf-8");
				PrintWriter out=response.getWriter();
				
				String username=request.getParameter("username");
				String password=request.getParameter("password");
				//获取前台输入的验证码
				String code=request.getParameter("u-ver");
				
				String path=request.getRequestURI();
				String pathstring=path.substring(path.lastIndexOf("/"), path.lastIndexOf("."));
				
				//得到数据源工厂实例
				LoginDao loginDao=(LoginDao) DbFactory.getInstance();
				JSONObject resultObject=new JSONObject();
				String message = null;
				//登陆
				if(pathstring.equals("/login")){
					//获取session中的属性
					HttpSession session=request.getSession();
					String verficationCode=(String) session.getAttribute("verificationCode");
					try{
						if(loginDao.validatelogin(username, password)){
							//登陆成功给session赋值
							if(verficationCode.equalsIgnoreCase(code)){
								session.setAttribute("userinfo",username);
								message="0";
							}else{
								message="1";
							}
						}else {
							message="2";
						}
					}catch(Exception ex){
						ex.printStackTrace(); 
					}finally {
						out.println(message);
						out.close();
					}
				}
	}

7、Dao层数据

public class LoginDaoImpl implements LoginDao{

	public boolean validatelogin(String userName, String password) {
		Connection conn=null;
		PreparedStatement prepareStatement=null;
		ResultSet result=null;
		conn=DbUtils.getConnection();
		boolean flag=false;
		try {
			prepareStatement=conn.prepareStatement("select employeeName,password from employee where employeeName=? and password=? ");
			prepareStatement.setString(1,userName);
			prepareStatement.setString(2,password);
			
			result=prepareStatement.executeQuery();
			flag=result.next();
		}catch(Exception ex){
			ex.printStackTrace();
		}finally{
			if (conn!=null) {
				DbUtils.close(result, prepareStatement, conn);
			}
		}	
		return flag;
	}
}

8、web.xml配置文件

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值