javaweb簡單的登入註冊功能實現
阿新 • • 發佈:2018-12-25
下面是使用者登入註冊流程圖
登陸介面
<%@ 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%>"> <title>My JSP 'index.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"> --> <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="3" align="center"><input type="submit" value="登入" style="width:130;height:30;"/></td></tr> </table> </form> <a href="regist.jsp"><font size="2"><i>沒有帳號?點選註冊</i></font></a> <font color="red" size="2"> ${msg }</font> </div> </center> </body> </html>
註冊介面
歡迎介面<%@ 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%>"> <title>My JSP 'regist.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"> --> </head> <body> <center> <div> <h1>註冊</h1> <form action="RegistServlet" method="post"> 請輸入帳號:<input type="text" name="username"><br/> 請輸入密碼:<input type="password" name="password"><br/> 請確認密碼:<input type="password" name="rpsw"><br/> <input type="submit" value="註冊"> </form> <font color="red" size="2"> ${msg }</font> </div> </center> </body> </html>
LoginServlet<%@ 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%>"> <title>My JSP 'welcome.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"> --> </head> <body> <h1>這是主頁</h1> <h2>${msg }</h2> </body> </html>
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wzc.loginDao.UserDao;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public 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");<span style="font-family: Arial, Helvetica, sans-serif;">//得到表單輸入的內容</span>
String svc =(String) request.getSession().getAttribute("sessionverify");
String psw =new UserDao().findUsername(username);
if(!svc.equalsIgnoreCase(verifyc)){
request.setAttribute("msg", "驗證碼錯誤!");
request.getRequestDispatcher("/index.jsp").forward(request, response);
return;
}
if(psw ==null){
request.setAttribute("msg", "沒有這個使用者!");
request.getRequestDispatcher("/index.jsp").forward(request, response);
return;
}
if(psw!=null&&!psw.equals(password)){
request.setAttribute("msg", "密碼錯誤請重新輸入!");
request.getRequestDispatcher("/index.jsp").forward(request, response);
return;
}
if(psw.equals(password)){
request.setAttribute("msg", "使用者:"+username+",歡迎訪問");
request.getRequestDispatcher("/welcome.jsp").forward(request, response);
//response.setHeader("Refresh","1;url=welcome.jsp");
}
}
}
RegistServlet
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wzc.loginDao.UserDao;
public class RegistServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public 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 rpsw = request.getParameter("rpsw");//得到表單輸入的內容
if(username==null||username.trim().isEmpty()){
request.setAttribute("msg", "帳號不能為空");
request.getRequestDispatcher("/regist.jsp").forward(request, response);
return;
}
if(password==null||password.trim().isEmpty()){
request.setAttribute("msg", "密碼不能為空");
request.getRequestDispatcher("/regist.jsp").forward(request, response);
return;
}
if(!password.equals(rpsw)){
request.setAttribute("msg", "兩次輸入的密碼不同");
request.getRequestDispatcher("/regist.jsp").forward(request, response);
return;
}
UserDao u = new UserDao();
u.addUser(username,password);//呼叫addUser()方法
request.setAttribute("msg", "恭喜:"+username+",註冊成功");
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
}
VerifyCodeServlet
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.wzc.utils.VerifyCode;
public class VerifyCodeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
VerifyCode vc = new VerifyCode();
BufferedImage image = vc.getImage(85,23);//設定驗證碼圖片大小
request.getSession().setAttribute("sessionverify", vc.getText());//將驗證碼文字儲存到session域
VerifyCode.output(image, response.getOutputStream());
}
}
VerifyCode
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', 'M',
'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' };
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);
}
}
UserDao
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao {
public String findUsername(String username){
String psw = null;
Connection con =null;
PreparedStatement pstmt =null;
ResultSet rs = null;
try {
String driver ="com.mysql.jdbc.Driver";
String url ="jdbc:mysql://localhost:3306/zhuce";
String user ="root";
String password ="root";<span style="font-family: Arial, Helvetica, sans-serif;">//改為自己的使用者名稱密碼和資料庫名</span>
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
String sql = "select * from zc where name=?";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, username);
rs = pstmt.executeQuery();
if(rs==null){
return null;
}
if(rs.next()){
psw=rs.getString("password");
}else{
psw=null;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if(pstmt!=null)pstmt.close();
if(con!=null)con.close();
}
catch (SQLException e) {
}
}
return psw;
}
public void addUser(String username,String psw){
Connection con =null;
PreparedStatement pstmt =null;
try {
String driver ="com.mysql.jdbc.Driver";
String url ="jdbc:mysql://localhost:3306/zhuce";
String user ="root";
String password ="root";//改為自己的使用者名稱密碼和資料庫名
Class.forName(driver);
con = DriverManager.getConnection(url, user, password);
String sql = "INSERT INTO ZC VALUES(?,?)";
pstmt = con.prepareStatement(sql);
pstmt.setString(1, username);
pstmt.setString(2, psw);
pstmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if(pstmt!=null)pstmt.close();
if(con!=null)con.close();
}
catch (SQLException e) {
}
}
}
//單獨測試使用
//public static void main(String[] args) {
//String psw =new UserDao().findUsername("345");
//System.out.println(psw);
//UserDao u = new UserDao();
//u.addUser("345", "345");
//}
}
建立的資料庫的user表有兩個屬性name,password 型別為varchar
點選下載原始碼