JSP實現基本的註冊功能
阿新 • • 發佈:2018-11-15
目錄
這裡主要用JSP方式實現了基本的註冊功能。專案名稱為NWPU_JavaWeb_Project。專案目錄的組織結構為:
1.前端頁面
前端頁面比較簡陋,只實現了基本的跳轉以及輸入的功能。但有幾點需要注意的地方。
首先,要設定編碼方式,這裡設定編碼方式為UTF-8。
其次,在jsp頁面中有一段自動生成的程式碼:
這裡用out.print(path + "------" + basePath);方式輸出一下,在頁面上的輸出結果為:
因為專案名稱是:NWPU_JavaWeb_Project,所以這麼一輸出就瞭解path和basePath是什麼意思了。
index.jsp的程式碼(當前未實現登入功能):
<body> <center> This is my JSP's index page. <br> <a href="<%=path%>/user/admin/register.jsp">註冊</a> <br> <a href="<%=path%>/user/admin/login.jsp">登入</a> </center> </body>
register.jsp的程式碼:
<html> <head> <base href="<%=basePath%>"> <title>register 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"> <!-- 表單驗證 --> <script type="text/javascript"> function isValid(form){ if(form.username.value==""){ alert("使用者名稱不能為空!"); return false; } if(form.userpwd.value!=form.userpwd1.value){ alert("兩次輸入的密碼不同!"); return false; } if(form.userpwd.value==""){ alert("密碼不能為空!"); return false; } if(form.userpwd1.value==""){ alert("請再次輸入密碼!"); return false; } return true; } </script> </head> <body> <center> <form method="post" action="<%=path%>/servlet/UserServlet?param=1" onSubmit="return isValid(this);"> <table> <caption>使用者註冊</caption> <tr> <td>使用者名稱:</td> <td><input type="text" name="username" size="21"></td> </tr> <tr> <td>密碼:</td> <td><input type="password" name="userpwd" size="21"></td> </tr> <tr> <td>確認密碼:</td> <td><input type="password" name="userpwd1" size="21"></td> </tr> <tr> <td><input type="submit" value="註冊" /></td> <td><input type="reset" value="重置"></td> </tr> </table> </form> </center> </body> </html>
2.實體類beans
User.java的程式碼:
package com.nwpu.beans;
public class User {
private String userName;
private String userPWD;
public User(String userName, String userPWD) {
this.userName = userName;
this.userPWD = userPWD;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPWD() {
return userPWD;
}
public void setUserPWD(String userPWD) {
this.userPWD = userPWD;
}
}
3.工具類Dao
UserDao.java的程式碼:
package com.nwpu.dao;
import java.sql.Connection;
import java.sql.Statement;
import com.nwpu.beans.User;
import com.nwpu.db.DBUtil;
public class UserDao {
// 使用者註冊
public int register(User user) {
int work = -1;
Connection conn = DBUtil.getConnection();
Statement stmt = null;
try {
stmt = conn.createStatement();
String sql = "INSERT INTO user(username, userpwd) VALUES('"
+ user.getUserName() + "','" + user.getUserPWD() + "')";
System.out.println("------註冊使用者:------\n" + sql);
work = stmt.executeUpdate(sql);
if (work > 0) {
System.out.println("------註冊成功------");
} else {
System.out.println("------註冊失敗------");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
DBUtil.closeConnection(stmt, conn);
}
return work;
}
}
4.Servlet類
UserServlet.java的程式碼:
package com.nwpu.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.nwpu.beans.User;
import com.nwpu.dao.UserDao;
public class UserServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int param = Integer.parseInt(request.getParameter("param"));
switch (param) {
// 註冊user
case 1:
this.register(request, response);
break;
// 查詢user
case 2:
break;
default:
break;
}
}
// 註冊
private void register(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
int work = -1;
request.setCharacterEncoding("UTF-8");
//response.setCharacterEncoding("UTF-8");//並沒有用
PrintWriter out = response.getWriter();
// 獲取物件
String userName = new String(request.getParameter("username").getBytes(
"ISO-8859-1"), "UTF-8");
System.out.print(userName+"---");
String userPWD = request.getParameter("userpwd");
System.out.print(userPWD+"---");
String userPWD1 = request.getParameter("userpwd1");
System.out.println(userPWD1);
// 伺服器驗證
/*
if (!isValid(userName, userPWD, userPWD1)) {
out.print("註冊失敗!");
return;
}
*/
// 列印
System.out.println(userName + "***" + userPWD);
// 注入物件
User user = new User(userName, userPWD);
UserDao dao = new UserDao();
work = dao.register(user);// 返回受影響的條數
if (work > 0) {
String msg="註冊成功!";
String url="index.jsp";
//加了,彈窗就不亂碼了
out.print("<html><head><meta charset='UTF-8'>");
out.println("<script>");
out.println("alert('" + msg + "');");
out.println("window.location='" + url + "'");
out.println("</script>");
out.print("</head></html>");
}
out.flush();
out.close();
}
private boolean isValid(String userName, String userPWD, String userPWD1) {
if (userName == "") {
return false;
}
if (userPWD != userPWD1) {
return false;
}
if (userPWD == "") {
return false;
}
if (userPWD1 == "") {
return false;
}
return true;
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public UserServlet() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void init() throws ServletException {
// Put your code here
}
}
5.JDBC工具類
DBUtil.java的程式碼:
package com.nwpu.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @author yylin
*
*/
public class DBUtil {
// 連線mySql資料庫
private static String mySqlDriver = "com.mysql.jdbc.Driver";// 資料庫連線字串
// “nwpu_db”是資料庫名
// ?characterEncoding=utf-8 設定jdbc連線的編碼方式以保證插入資料不會亂碼
private static String mySqlURL = "jdbc:mysql://localhost:3306/nwpu_db?characterEncoding=UTF-8";
private static String mySqlUserName = "root";
private static String mySqlUserPSW = "123654";
// 連線SQLServer資料庫
private static String sqlServerDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver";// 資料庫連線字串
private static String sqlServerURL = "jdbc:sqlserver://localhost:1434; DatabaseName=testJDBC";// “testJDBC”是資料庫名
private static String sqlServerUserName = "sa";
private static String sqlServerUserPSW = "123654";
// 連線Oracle資料庫
private static String oracleDriver = "oracle.jdbc.driver.OracleDriver";// 資料庫連線字串
private static String oracleSqlURL = "jdbc:oracle:thin:@localhost:1521:orcl";// “orcl”是資料庫名
private static String oracleSqlUserName = "scott";
private static String oracleSqlUserPSW = "tiger";
// 需要連線的資料庫字串
private static String driverName = mySqlDriver;
private static String DBURL = mySqlURL;
private static String userName = mySqlUserName;
private static String userPSW = mySqlUserPSW;
// 連線資料庫
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(driverName);// 載入JDBC驅動
conn = DriverManager.getConnection(DBURL, userName, userPSW);// 連線資料庫
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
// 關閉連線,Statement方法
public static void closeConnection(ResultSet rs, Statement stmt,
Connection conn) {
try {
if (rs != null) {
rs.close();
rs = null;
}
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
// 關閉連線,PreparedStatement方法
public static void closeConnection(PreparedStatement pstmt, Connection conn) {
try {
if (pstmt != null) {
pstmt.close();
pstmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//關閉連線,Statement方法
public static void closeConnection(Statement stmt, Connection conn) {
// TODO Auto-generated method stub
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
//關閉連線,conn方法
public static void closeConnection(Connection conn) {
// TODO Auto-generated method stub
try {
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
6.XML檔案
xml檔案程式碼:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<!-- 類名 -->
<servlet-name>UserServlet</servlet-name>
<!-- 所在的包 -->
<servlet-class>com.nwpu.servlet.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UserServlet</servlet-name>
<!-- 訪問的網址 -->
<url-pattern>/servlet/UserServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>