Servlet +JSP+Javabean 實現使用者登入註冊
阿新 • • 發佈:2019-02-10
目錄結構:
程式碼:
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"> function check(){ var uname = document.getElementById("uname").value; var upassword = document.getElementById("upassword").value; if(uname==""){ alert("使用者名稱為空!"); return false; } if(upassword==""){ alert("密碼為空!"); return false; } } if(window.top!=window){ window.top.location = "Login"; } </script> </head> <body> <center> <h1>使用者登入</h1> <hr/> <form action="${pageContext.request.contextPath }/Login" method="post" onsubmit="return check()"> <table border="0" width="400px"> <tr> <td align="right">使用者名稱:</td> <td><input type="text" id="uname" name="username" style="width: 180px"/></td> </tr> <tr> <td align="right">密 碼:</td> <td><input type="password" id="upassword" name="password" style="width: 180px"/></td> </tr> <tr> <td align="right"><input type="submit" value="登入"/></td> <td><input type="reset" value="重置"/></td> <td><a href="${pageContext.request.contextPath }/Register.jsp">尚未註冊,註冊使用者</a></td> </tr> <tr> <td></td> <td><font color="red">${message}</font></td> </tr> </table> </form> </center> </body> </html>
Register.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"> function check(){ var uname = document.getElementById("uname").value; var upassword = document.getElementById("upassword").value; var upasswordtwo = document.getElementById("upasswordtwo").value; var phone = document.getElementById("phone").value; var email = document.getElementById("email").value; if(uname==""){ alert("使用者名稱為空!"); return false; } if(upassword==""){ alert("密碼為空!"); return false; } if(upasswordtwo==""){ alert("請再次輸入密碼!"); return false; } if(upassword != upasswordtwo){ alert("兩次密碼不一致!"); return false; } if(phone==""){ alert("電話號碼為空!"); return false; } if(email==""){ alert("電子郵箱為空!"); return false; } } if(window.top!=window){ window.top.location = "Login"; } </script> </head> <body> <center> <h1>使用者註冊</h1> <hr/> <form action="${pageContext.request.contextPath }/Register" method="post" onsubmit="return check()"> <table border="0" width="420px"> <tr> <td align="right">使用者名稱:</td> <td><input type="text" id="uname" name="username" style="width: 180px"/></td> </tr> <tr> <td align="right">密 碼:</td> <td><input type="password" id="upassword" name="password" style="width: 180px"/></td> </tr> <tr> <td align="right">確認密碼:</td> <td><input type="password" id="upasswordtwo" name="passwordtwo" style="width: 180px"/></td> </tr> <tr> <td align="right">手機號碼:</td> <td><input type="text" id="phone" name="phone" style="width: 180px"/></td> </tr> <tr> <td align="right">電子郵箱:</td> <td><input type="text" id="email" name="email" style="width: 180px"/></td> </tr> <tr> <td align="right"><input type="submit" value="提交註冊"/></td> <td><input type="reset" value="重置"/></td> <td><a href="${pageContext.request.contextPath }/login.jsp">已經註冊,直接登入</a></td> </tr> <tr> <td></td> <td><font color="red">${register}</font></td> </tr> </table> </form> </center> </body> </html>
Main.jsp
<%@page import="java.util.Date"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!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"> function doLogout(){ //訪問LogoutServlet登出當前登入的使用者 window.parent.location.href="${pageContext.request.contextPath}/Logout"; //以父容器的形式跳出frameset框架 } var timerID = null; var timerRunning = false; function showtime() { var now = new Date(); // var now = new Date().format("yyyy-MM-dd HH:mm:ss"); // document.clock.thetime.value = now.toString(); document.clock.thetime.value = now.toLocaleString(); timerID = setTimeout("showtime()", 1000); timerRunning = true; } </script> </head> <body style="background-color: gray;" onload="showtime()"> <center> <form name=clock> <c:if test="${user!=null}"> 歡迎您:${user.user_name} <input type="button" value="退出登陸" onclick="doLogout()" /> </c:if> <input name=thetime style="font-size: 15px;color:#FF3030;border:0" size=20 /> </form> </center> </body> </html>
RegisterSuss.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>
</head>
<body>
<center>
<h1>恭喜您,註冊成功!</h1>
<hr/>
<a href="${pageContext.request.contextPath }/login.jsp">登入賬戶</a>
</center>
</body>
</html>
User.java
package com.bean;
public class User {
private int user_id; //使用者id
private String user_name; //使用者名稱
private String user_password; //使用者密碼
private int user_phone; //使用者電話
private String user_email; //使用者郵箱
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public String getUser_name() {
return user_name;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
public String getUser_password() {
return user_password;
}
public void setUser_password(String user_password) {
this.user_password = user_password;
}
public int getUser_phone() {
return user_phone;
}
public void setUser_phone(int user_phone) {
this.user_phone = user_phone;
}
public String getUser_email() {
return user_email;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
}
UserDao.java(資料訪問層)
package com.dao;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import com.bean.User;
import com.utils.DButil;
public class UserDao {
//新增
public void AddUser(User user){
try{
QueryRunner runner = new QueryRunner(DButil.open());
String sql = "insert into user(user_name,user_password,user_phone,user_email) values(?,?,?,?)";
Object params[] = {user.getUser_name(),user.getUser_password(),user.getUser_phone(),user.getUser_email()};
System.out.println("新增使用者成功!");
runner.update(sql, params);
}catch (Exception e) {
System.out.println("新增使用者失敗!");
throw new RuntimeException(e);
}
}
//查詢是否存在使用者
public User find(String user_name){
try{
QueryRunner runner = new QueryRunner(DButil.open());
String sql = "select * from user where user_name= ?";
System.out.println("查詢成功!");
return (User) runner.query(sql, user_name, new BeanHandler(User.class));
}catch (Exception e) {
System.out.println("查詢失敗!");
throw new RuntimeException(e);
}
}
//登入驗證
public User login(String user_name, String user_password) {
try{
QueryRunner runner = new QueryRunner(DButil.open());
String sql="select * from user where user_name=? and user_password=? ";
Object params[] = {user_name,user_password};
System.out.println("查詢資料成功!");
return (User)runner.query(sql, params, new BeanHandler(User.class));
}catch (Exception e) {
System.out.println("查詢資料失敗!");
throw new RuntimeException(e);
}
}
}
EncodingFilter.java(編碼過濾器)
package com.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class EncodingFilter implements Filter {
private String encoding;
public EncodingFilter() {
// TODO Auto-generated constructor stub
}
public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
request.setCharacterEncoding(encoding);
//fc.getServletContext().log("你的編碼為UTF-8");
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
encoding=fConfig.getInitParameter("encoding");
//this.fc=fConfig;
}
}
Login.java
package com.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.bean.User;
import com.dao.UserDao;
@WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
public Login() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//設定編碼
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Type","text/html; charset=utf-8");
String user_name = request.getParameter("username");
String user_password = request.getParameter("password");
UserDao dao = new UserDao();
User user = dao.login(user_name, user_password);
if(user != null){
System.out.println("登入成功!");
request.getSession().setAttribute("user", user); //用session儲存使用者資訊
request.getRequestDispatcher("JSP/Main.jsp").forward(request, response);
}
else{
request.getSession().setAttribute("message", "使用者名稱或密碼錯誤!");
//response.getWriter().write("<script language='javascript'>alert('使用者名稱或密碼不正確!')</script>");
//request.getRequestDispatcher("/login.jsp").forward(request, response);
response.sendRedirect(request.getContextPath()+"/login.jsp");
}
}
}
Logout.java
package com.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;
@WebServlet("/Logout")
public class Logout extends HttpServlet {
private static final long serialVersionUID = 1L;
public Logout() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//移除儲存在session中的user物件,實現登出功能
request.getSession().removeAttribute("user");
request.getSession().removeAttribute("message");
response.sendRedirect(request.getContextPath()+"/login.jsp");
}
}
Register.java
package com.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.bean.User;
import com.dao.UserDao;
@WebServlet("/Register")
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
public Register() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//設定編碼
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setHeader("Content-Type","text/html; charset=utf-8");
String user_name = request.getParameter("username");
String user_password = request.getParameter("password");
String user_phone = request.getParameter("phone");
int phone = Integer.parseInt(user_phone);
String email = request.getParameter("email");
User user = new User();
user.setUser_name(user_name);
user.setUser_password(user_password);
user.setUser_phone(phone);
user.setUser_email(email);
UserDao dao = new UserDao();
User us = dao.find(user_name);
// System.out.println("您的使用者名稱:"+us.getUser_name());
if(us!=null){
request.setAttribute("register", "該使用者已經存在!");
request.getRequestDispatcher("Register.jsp").forward(request, response);
}
else{
dao.AddUser(user);
request.getRequestDispatcher("JSP/RegisterSuss.jsp").forward(request, response);
request.getSession().removeAttribute("register");
}
}
}
Time.java(系統時鐘)
package com.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Time {
public static void main(String[] args) {
// TODO Auto-generated method stub
time();
}
public static String time(){
Date date = new Date(System.currentTimeMillis());
for (int i = 0; i < 100000000; i++ ) {
try {
Thread.sleep(1000);
date.setTime(System.currentTimeMillis());
String time = new SimpleDateFormat("yyyy年 MM月 dd日 HH時 mm分 ss秒").format(date);
System.out.println("當前時間: " + time.toString());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return time();
}
}
截圖:
Project說明:本模組是採用Servlet+JSP+JavaBean設計的使用者註冊登入模組,資料庫採用C3P0資料庫連線池,資料庫連線配置檔案在src目錄下的c3p0-config.xml檔案中。註冊登入的驗證結果皆在客戶端顯示。在經過前端頁面處理提交的使用者註冊失敗主要是該使用者名稱稱已存在,登入失敗是因為使用者名稱或密碼錯誤,當用戶要退出登入時,點選"退出登入"按鈕即可。