针对需要验证码登录以及注册案例

来源:互联网 发布:世界征服者3 全将 数据 编辑:程序博客网 时间:2024/06/05 00:19

因为之前自己有做过登录的案例,现在进一步一下具有验证码的登录:

登录页面:

<%@ page language="java" contentType="text/html; charset=utf-8"
 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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>登录页面</title>
<script type="text/javascript">
function change(){
 var img = document.getElementById("verify");
 img.src = "VerifyCodeServlet?a="+new Date().getTime();
}
</script>
</head>
<body>
<center>
<div>
 <h1>歡迎登陸</h1>
 <form action="LoginServlet" method="post">
  <table>
   <tr>
    <td width="66" align="right"><font size="3">賬號: </font></td>
    <td colspan="2"><input type="text" name="username"
     value="${username}" style="width: 200; height: 25;" /></td>
   </tr>
   <tr>
    <td align="right"><font size="3">密碼: </font></td>
    <td colspan="2"><input type="text" name="password"
      style="width: 200; height: 25;" /></td>
   </tr>
   <tr>
    <td align="right"><font size="3">驗證碼:</font></td>
    <td width="108" valign="middle"><input type="text"
     name="verifycode" style="width: 100; height: 25;" /></td>
    <td width="90" valign="middle"><a href="javascript:change()">
      <img src="VerifyCodeServlet" id="verify" border="0">
    </a></td>
   </tr>
    <tr>
    <td colspan="1.5" align="right"><input type="submit" value="登陸"
     style="width: 130; height: 30;" /></td>
     
     
     <td  colspan="1" align="left">
     <input type="button"value="返回" onclick="window.location.href ='index.jsp';"/></td>
   </tr>
   
   
  </table>
 </form>
   <a href="register.jsp"><font size="2"><i>沒有賬號?請點擊注冊</i></font></a>
 <!--<input type="button"value="註冊" onclick="window.location.href ='register.jsp';"/>-->
 <font color="red" size="2">${msg}</font>
 </div>
</center>
</body>
</html>

注册页面:
<%@ page language="java" contentType="text/html; charset=utf-8"
 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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<base href="<%=basePath%>">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>注冊頁面</title>
</head>
<body>
 <form action="RegistServlet" method = "post">
 请输入账号:<input type = "text" name="username"><br>
 请输入密码:<input type ="password" name="pwd"> <br>
 请确认密码:<input type ="password" name="rpwd"><br>
 <input type="submit" value="注册"/>
 <input type="button"value="返回" onclick="window.location.href ='index.jsp';"/>
 
 </form>
 <font color="red" size="2">${msg}</font>
</body>
</html>


登录完成页面:
<%@ page language="java" contentType="text/html; charset=utf-8"
 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" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Welcome</title>
</head>
<body>
 <h1>這是主頁</h1>
 <h2>${msg}</h2>
</body>
</html>

注册完成页面:
<%@ page language="java" contentType="text/html; charset=utf-8"
 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" "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>注册成功!!</h1>
 <h2>${msg}</h2>
</body>
</html>

登录Servlet:
package com.ibm.servlet;
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.ibm.dao.UserDao;
/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 /**
  * @see HttpServlet#HttpServlet()
  */
 public LoginServlet() {
  super();
  // TODO Auto-generated constructor stub
 }
 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  response.getWriter().append("Served at: ").append(request.getContextPath());
 }
 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setCharacterEncoding("utf-8");
  response.setContentType("text/html;charset=utf-8");
  String username = request.getParameter("username");
  String password = request.getParameter("password");
  String verifyc = request.getParameter("verifycode");
  String svc = (String) request.getSession().getAttribute("sessionverify");
  String pwd = new UserDao().findUsername(username);
  if (!svc.equalsIgnoreCase(verifyc)) {
   request.setAttribute("msg", "驗證碼有無,請再次輸入!");
   request.getRequestDispatcher("index.jsp").forward(request, response);
   return;
  }
  if (pwd==null) {
   request.setAttribute("msg", "您目前还不是咱们 的用户请点击注册!!!");
   request.getRequestDispatcher("index.jsp").forward(request, response);
   return;
  }
  if (pwd != null && !pwd.equals(password)) {
   request.setAttribute("msg", "密碼錯誤請重新輸入!");
   request.getRequestDispatcher("index.jsp").forward(request, response);
   return;
  }
  if (pwd.equals(password)) {
   request.setAttribute("msg", "用戶" + username + ",歡迎訪問!");
   request.getRequestDispatcher("welcome.jsp").forward(request, response);
  }
 }
 
}

注册servlet:
package com.ibm.servlet;
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.ibm.dao.UserDao;
/**
 * Servlet implementation class RegistServlet
 */
@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 /**
  * @see HttpServlet#HttpServlet()
  */
 public RegistServlet() {
  super();
  // TODO Auto-generated constructor stub
 }
 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  // TODO Auto-generated method stub
  response.getWriter().append("Served at: ").append(request.getContextPath());
 }
 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  *      response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  request.setCharacterEncoding("utf-8");
  response.setContentType("text/html;charset = utf-8");
  String username = request.getParameter("username");
  String pwd = request.getParameter("pwd");
  String rpwd = request.getParameter("rpwd");
  //注冊処判定
  if (username == null || username.trim().isEmpty()) {
   request.setAttribute("msg", "賬號不能爲空");
   request.getRequestDispatcher("register.jsp").forward(request, response);
   return;
  }
  if (pwd == null || pwd.trim().isEmpty()) {
   request.setAttribute("msg", "密碼不能爲空!");
   request.getRequestDispatcher("register.jsp").forward(request, response);
   return;
  }
  
  if (!pwd.equals(rpwd)) {
   request.setAttribute("msg", "兩次密碼不一致!");
   request.getRequestDispatcher("register.jsp").forward(request, response);
   return;
  }
  UserDao ud = new UserDao();
  ud.addUser(username, pwd);
  request.setAttribute("msg","恭喜"+ username+",注册成功!!");
  request.getRequestDispatcher("rewelcome.jsp").forward(request, response);
 }
}

验证码servlet:
package com.ibm.servlet;
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.ibm.co.VerifyCode;
/**
 * Servlet implementation class VerifyCodeServlet
 */
@WebServlet("/VerifyCodeServlet")
public class VerifyCodeServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
      
    /**
     * @see HttpServlet#HttpServlet()
     */
    public VerifyCodeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     VerifyCode vc = new VerifyCode();
     BufferedImage image = vc.getImage(80, 20);
     request.getSession().setAttribute("sessionverify", vc.getText());
     VerifyCode.output(image, response.getOutputStream());
  
 }
 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  doGet(request, response);
 }
}

DAO包:
package com.ibm.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao {
 @SuppressWarnings("finally")
 public String findUsername(String username) {
  String pwd = null;
  Connection con = null;
  PreparedStatement pstmt = null;
  ResultSet rs = null;
  try {
   String url = "jdbc:mysql://localhost:3306/dm";
   String user = "root";
   String password = "123456";
   Class.forName("com.mysql.jdbc.Driver");
   con = DriverManager.getConnection(url, user, password);
   String sql = "select * from regist where username =?";
   pstmt = con.prepareStatement(sql);
             pstmt.setString(1, username);
   rs = pstmt.executeQuery();
   if (rs == null) {
    return null;
   }
   if (rs.next()) {
    pwd = rs.getString("pwd");
   } else {
    pwd = null;
   }
  } catch (SQLException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null)
     pstmt.close();
    if (con != null)
     con.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   return pwd;
  }
 }
 // 插入數據
 public void addUser(String username, String pwd) {
  Connection con = null;
  PreparedStatement pstmt = null;
  try {
   String driver = "com.mysql.jdbc.Driver";
   String url = "jdbc:mysql://localhost:3306/dm";
   String user = "root";
   String password = "123456";
   Class.forName(driver);
   try {
    con = DriverManager.getConnection(url, user, password);
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   String sql = "INSERT INTO Regist VALUES(?,?)";
   try {
    pstmt = con.prepareStatement(sql);
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   try {
    pstmt.setString(1, username);
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   try {
    pstmt.setString(2, pwd);
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   try {
    pstmt.executeUpdate();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
  } catch (ClassNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } finally {
   try {
    if (pstmt != null)
     pstmt.close();
    if (con != null)
     con.close();
   } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
   }
   finally{
     try {
      if(pstmt !=null)
      pstmt.close();
      if(con!=null) con.close();
     } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
    
   }
  }
 }
 // 測試
// public static void main(String[] args) {
//  String pwd = new UserDao().findUsername("123");
//  System.out.println(pwd);
//  UserDao ud = new UserDao();
//  ud.addUser("小明", "122321");
//  System.out.println("============" + ud);
// }
}

验证码生成:
package com.ibm.co;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;
import javax.imageio.ImageIO;
public class VerifyCode {
 public static final char[] CHARS ={
   '2','3','4','5','6','7','8','9',
   'A','B','C','D','E','F','G','H','J','K','L'
   ,'Z','X','C','V','B','N','M'
 };
 //随机生成;
 public static Random random = new Random();
 public String getRandomString(){
  StringBuffer buffer = new StringBuffer();
  for(int i = 0;i<4;i++){
   buffer.append(CHARS[random.nextInt(CHARS.length)]);
  }
  return buffer.toString();
  
 }
 
 public Color getRandomColor(){
  return new Color(random.nextInt(255),random.nextInt(255),random.nextInt(255));
  
 }
 
 public Color getReverseColor(Color c){
  return new Color(255-c.getRed(),255-c.getGreen(),255-c.getBlue());
  }
 
 String text = getRandomString();
 public String getText(){
  return text;
  
 }
 public BufferedImage getImage(int width,int height){
  Color color = getRandomColor();
  Color reverse = getReverseColor(color);
  BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
  Graphics2D g = bi.createGraphics();
  g.setFont(new Font(Font.SANS_SERIF,Font.BOLD,20));
  g.setColor(color);
  g.fillRect(0, 0, width, height);
  g.setColor(reverse);
  g.drawString(text, 10, 22);
  for(int i =0,n=random.nextInt(80); i < n;i++){
   g.drawRect(random.nextInt(width), random.nextInt(height), 1, 1);
  }
  return bi;
  
 }
 
 public static void output(BufferedImage image,OutputStream out) throws IOException{
  ImageIO.write(image, "JPEG", out);
  
 }
}


原创粉丝点击