最新消息: 新版网站上线了!!!

javaWeb使用验证码实现简单登录

本文实例为大家分享了javaWeb使用验证码实现简单登录的具体代码,供大家参考,具体内容如下

简单的流程图  

1.用户给第一次访问login.jsp页面时,会想服务器发送两个请求,一个请求是显示图片,还有一个是显示表单

2.第一个请求发送后 服务器中verifyServlet处理,随机生成验证码图片,并保存到session中,然后响应给客户端

3.第二个请求后 服务器LoginServlet处理,获取表单验证码,以及session中的验证码,再判断两个验证码是否相等,相等就向下执行即 success.jsp,否则跳转到login.jsp页面

1.创建login.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
 <base href="<%=basePath%>" rel="external nofollow" >
 
 <title>My JSP 'login.jsp' starting page</title>
 
 <meta http-equiv="pragma" content="no-cache">
 <meta http-equiv="cache-control" content="no-cache">
 <meta http-equiv="expires" content="0"> 
 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
 <meta http-equiv="description" content="This is my page">
 <!--
 <link rel="stylesheet" type="text/css" href="styles.css" rel="external nofollow" >
 -->
 
 </head>
 
 <body>
 <%--本页面提供登录表单,还有显示错误信息 --%>
 <h1>登录</h1> 
 <%
 //读取uname的cookie
 String uname="";
 Cookie[] cs=request.getCookies();
 if(cs!=null){
  for(Cookie c:cs){
  if("uname".equals(c.getName())){
  uname=c.getValue();
  }
  }
 }
 %>
 
 <%
 String message="";
 String msg=(String)request.getAttribute("msg");
 if(msg!=null){
  message=msg;
  }
 %>
 
 <font color="red"><b><%=message %></b></font>
 <form action="/ServletDemo2/LoginServlet1" method="post">
  用户名:<input type="text" name="username" value=<%=uname %> /><br>
  密 码:<input type="password" name="pawword" /><br>
  验证码:<input type="text" name="verifycode" size="3">
  <img src="/ServletDemo2/VerifyServlet" >
  <!-- <a href="javascript:_change()" rel="external nofollow" >换一张</a> -->
 
  <input type="submit" value="登录" />
 
 </form>
 </body>
</html>

2.success.jsp(只是简单的展示)

<body>
 <h1>succ1</h1>
 <%
 String username=(String)session.getAttribute("username");
 if(username==null){
  /*
  向request域中保存错误信息,转发到login.jsp
  */
  request.setAttribute("msg", "请先登录再访问");
  request.getRequestDispatcher("/session2/login.jsp").forward(request, response);
  return;
 }
  %>
 
 欢迎登陆成功<%=username %>
 </body>

3.然后是VerifyServlet

 package com.klay.servlet.session;
 
import java.awt.image.BufferedImage;
import java.io.IOException;
 
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.klay.image.VerifyCode;
 
/**
 * Servlet implementation class VerifyServlet
 */
@WebServlet("/VerifyServlet")
public class VerfiyServlet extends HttpServlet
{
 private static final long serialVersionUID = 1L;
 
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  VerifyCode vc = new VerifyCode();
  BufferedImage image = vc.getImage();
  request.getSession().setAttribute("session_vcode", vc.getText());// 保存图片上的文本到session
 
  VerifyCode.output(image, response.getOutputStream());
 }
 
}

4.LoginServlet

package com.klay.servlet.session;
 
import java.io.IOException;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
 
public class LoginServlet extends HttpServlet
{
 
 /**
  * @Fields serialVersionUID : TODO(用一句话描述这个变量表示什么)
  */
 private static final long serialVersionUID = 1L;
 
 @Override
 protected void doPost(HttpServletRequest req, HttpServletResponse resp)
   throws ServletException, IOException
 {
  /**
   * 获取校验码
   */
  String sessionCode = (String) req.getSession()
    .getAttribute("session_vcode");
 
  String paraCode = req.getParameter("verifycode");
 
  if (!paraCode.equalsIgnoreCase(sessionCode))
  {
   req.setAttribute("msg", "验证码错误");
   req.getRequestDispatcher("/session2/login.jsp").forward(req, resp);
   // return是这里执行完,就不玩下执行了。
   return;
  }
 
  /**
   * 获取表单信息
   */
  req.setCharacterEncoding("utf-8");
 
  String username = req.getParameter("username");
  String password = req.getParameter("password");
 
  /**
   * 校验用户名和密码
   */
  if (!"kevin".equalsIgnoreCase(username))// 成功
  {
   Cookie cookie = new Cookie("uname", username);
   resp.addCookie(cookie);
 
   /*
    * 成功就保存用户信息到session,并重定向succ1.jsp
    */
   HttpSession session = req.getSession();
   session.setAttribute("username", username);
   resp.sendRedirect("/ServletDemo2/session2/succ1.jsp");
  }
  else
  {// 失败
   // 如果失败,保存错误信息到requset,转发到login.jsp
   // (服务器内部跳转只有一个request请求,重定向会有新的request,就不能获取错误信息)
   req.setAttribute("msg", "用户名或密码错误");
   RequestDispatcher rd = req
     .getRequestDispatcher("/session2/login.jsp");
   rd.forward(req, resp);// 转发
 
  }
 
 }
 
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持谷谷点程序。

转载请注明:谷谷点程序 » javaWeb使用验证码实现简单登录