Servlet案例4:使用者註冊,servlet案例
資料庫準備:
CREATE DATABASE web;USE web;CREATE TABLE `user` ( `uid` VARCHAR(64) NOT NULL, `username` VARCHAR(20) DEFAULT NULL, `password` VARCHAR(20) DEFAULT NULL, `name` VARCHAR(20) DEFAULT NULL, `email` VARCHAR(30) DEFAULT NULL, `telephone` VARCHAR(20) DEFAULT NULL, `birthday` VARCHAR(20) DEFAULT NULL, `sex` VARCHAR(10) DEFAULT NULL, `state` INT(11) DEFAULT NULL, `code` VARCHAR(64) DEFAULT NULL, PRIMARY KEY (`uid`))
View Code
對應的類:
package register;public class User { private String uid; private String username; private String password; private String name; private String email; private String sex; private String birthday; public String getUid() { return uid; } public void setUid(String uid) { this.uid = uid; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getBirthday() { return birthday; } public void setBirthday(String birthday) { this.birthday = birthday; } @Override public String toString() { return "User [uid=" + uid + ", username=" + username + ", password=" + password + ", name=" + name + ", email=" + email + ", sex=" + sex + ", birthday=" + birthday + "]"; }}View Code
註冊登入頁面很簡單,一個表單即可,這裡省略
servlet:
package register;import java.io.IOException;import java.lang.reflect.InvocationTargetException;import java.sql.SQLException;import java.util.Map;import java.util.UUID;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.dbutils.QueryRunner;public class RegisterServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //中文亂碼的解決 request.setCharacterEncoding("UTF-8"); //中文亂碼的解決原理 /* String username = request.getParameter("username"); username = new String(username.getBytes("iso8859-1"),"UTF-8"); */ // 擷取資料 // 將資料封裝(使用BeanUtils自動封裝) Map<String, String[]> properties = request.getParameterMap(); User user = new User(); try { BeanUtils.populate(user, properties); } catch (IllegalAccessException | InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } // users對象封裝完畢,手動封裝主鍵uid(使用uuid) user.setUid(UUID.randomUUID().toString()); // 註冊的方法 regist(user); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public void regist(User user) { QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "insert into user values(?,?,?,?,?,?,?,?,?,?)"; try { runner.update(sql, user.getUid(), user.getUsername(), user.getPassword(), user.getName(), user.getEmail(), null, user.getBirthday(), user.getSex(), null, null); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }}View Code
抽取的串連池工具類:
package register;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;import javax.sql.DataSource;import com.mchange.v2.c3p0.ComboPooledDataSource;public class DataSourceUtils { private static DataSource dataSource = new ComboPooledDataSource(); private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>(); // 直接可以擷取一個串連池 public static DataSource getDataSource() { return dataSource; } // 擷取連線物件 public static Connection getConnection() throws SQLException { Connection con = tl.get(); if (con == null) { con = dataSource.getConnection(); tl.set(con); } return con; } // 開啟事務 public static void startTransaction() throws SQLException { Connection con = getConnection(); if (con != null) { con.setAutoCommit(false); } } // 交易回復 public static void rollback() throws SQLException { Connection con = getConnection(); if (con != null) { con.rollback(); } } // 提交並且 關閉資源及從ThreadLocall中釋放 public static void commitAndRelease() throws SQLException { Connection con = getConnection(); if (con != null) { con.commit(); // 事務提交 con.close();// 關閉資源 tl.remove();// 從線程綁定中移除 } } // 關閉資源方法 public static void closeConnection() throws SQLException { Connection con = getConnection(); if (con != null) { con.close(); } } public static void closeStatement(Statement st) throws SQLException { if (st != null) { st.close(); } } public static void closeResultSet(ResultSet rs) throws SQLException { if (rs != null) { rs.close(); } }}View Code
c3p0-config.xml設定檔:
<?xml version="1.0" encoding="UTF-8"?><c3p0-config> <default-config> <property name="user">root</property> <property name="password">xuyiqing</property> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql:///web</property> </default-config> </c3p0-config>
View Code
注意匯入相關jar包
web.xml設定檔:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>WEB5</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>RegisterServlet</display-name> <servlet-name>RegisterServlet</servlet-name> <servlet-class>register.RegisterServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>RegisterServlet</servlet-name> <url-pattern>/register</url-pattern> </servlet-mapping></web-app>
View Code