用戶訪問註冊頁面時,填好註冊信息以後點擊提交按鈕時會將表單提交信息給RegistServlet.java進行後臺處理,後臺在執行完邏輯以後會把執行結果返回到jsp頁面。css
POST請求html
<!-- action:請求的路徑 ,method:請求方式 --> <form action="/RegistServlet" method="POST">
咱們在 jsp頁面申請一個塊結構來顯示後臺的驗證信息,位置位於表單上方java
<!-- 若是出現錯誤將在表單頂部顯示 --> <td colspan="2" style="text-align:center;color:green"> <%=request.getAttribute("errMsg")==null?"":request.getAttribute("errMsg") %> </td>
後臺服務器接受到表單請求以後,會執行驗證邏輯,將符合要求的的用戶信息保存到後臺數據庫中,不符合邏輯的的信息將不會保存,並將錯誤返回到客戶端 jsp頁面。mysql
須要導入兩個jar包,進行數據庫操做的時候須要。web
jsp註冊頁面及後臺服務器代碼:sql
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML> <html> <head> <title>歡迎註冊BinGou</title> <meta http-equiv="Content-type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="css/regist.css"/> </head> <body> <!-- action:請求的路徑 ,method:請求方式 --> <form action="/RegistServlet" method="POST"> <h1>歡迎註冊BinGou</h1> <table> <tr><!-- 若是出現錯誤將在表單頂部顯示 --> <td colspan="2" style="text-align:center;color:green"> <%=request.getAttribute("errMsg")==null?"":request.getAttribute("errMsg") %> </td> </tr> <tr> <td class="tds">用戶名:</td> <td> <input type="text" name="username" /> </td> </tr> <tr> <td class="tds">密碼:</td> <td> <input type="password" name="password" /> </td> </tr> <tr> <td class="tds">確認密碼:</td> <td> <input type="password" name="password2"/> </td> </tr> <tr> <td class="tds">暱稱:</td> <td> <input type="text" name="nickname"/> </td> </tr> <tr> <td class="tds">郵箱:</td> <td> <input type="text" name="email"/> </td> </tr> <tr> <td class="tds">驗證碼:</td> <td> <input type="text" name="valistr"/> <img src="img/regist/yzm.jpg" width="" height="" alt="" /> </td> </tr> <tr> <td class="sub_td" colspan="2" class="tds"> <input type="submit" value="註冊用戶"/> </td> </tr> </table> </form> </body> </html>
package cn.bingou.web; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.bingou.util.JDBCUtils; import cn.bingou.util.WebUtils; public class RegistServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // 1.請求亂碼問題 // 請求亂碼-POST請求 req.setCharacterEncoding("utf-8"); // 應答亂碼問題 resp.setContentType("text/html;charset=utf-8"); // 2.接收表單參數 String username = req.getParameter("username"); String password = req.getParameter("password"); String password2 = req.getParameter("password2"); String nickname = req.getParameter("nickname"); String email = req.getParameter("email"); String valistr = req.getParameter("valistr"); // 3.驗證表單 // 1)非空驗證 if(WebUtils.isEmpty(username)){ // 用戶名爲空驗證 // 向request做用域中添加錯誤提示信息 req.setAttribute("errMsg", "用戶名不能爲空!"); // 將請求轉發給regist.jsp,forward():請求轉發 req.getRequestDispatcher("/regist.jsp").forward(req, resp); // 若是用戶輸入爲空,直接返回 return; } if(WebUtils.isEmpty(password)){ // 密碼爲空驗證 req.setAttribute("errMsg", "密碼不能爲空!"); req.getRequestDispatcher("/regist.jsp").forward(req, resp); return; } if(WebUtils.isEmpty(nickname)){ // 暱稱爲空驗證 req.setAttribute("errMsg", "暱稱不能爲空!"); req.getRequestDispatcher("/regist.jsp").forward(req, resp); return; } if(WebUtils.isEmpty(email)){ // 郵箱爲空驗證 req.setAttribute("errMsg", "郵箱不能爲空!"); req.getRequestDispatcher("/regist.jsp").forward(req, resp); return; } if(WebUtils.isEmpty(valistr)){ // 驗證碼爲空驗證 req.setAttribute("errMsg", "驗證碼不能爲空!"); req.getRequestDispatcher("/regist.jsp").forward(req, resp); return; } // 2)密碼一致驗證 if(!password.equals(password2)){ // 若是密碼與確認密碼不同,則輸出錯誤 req.setAttribute("errMsg", "密碼不一致"); req.getRequestDispatcher("/regist.jsp").forward(req, resp); return; } // 3)郵箱格式驗證 // abc@123.163.com String reg="^\\w+@\\w+(\\.\\w+)+$"; if(!email.matches(reg)){ req.setAttribute("errMsg", "郵箱格式不符"); req.getRequestDispatcher("/regist.jsp").forward(req, resp); return; } // 4)用戶名是否存在 String sql1="select * from user where username=?"; Connection conn = null; PreparedStatement ps = null; ResultSet rs=null; try { conn=JDBCUtils.getConnections(); ps=conn.prepareStatement(sql1); ps.setString(1, username); rs=ps.executeQuery(); while(rs.next()){ // 尋找用戶名,直到找到爲止 req.setAttribute("errMsg", "用戶名已存在"); req.getRequestDispatcher("/regist.jsp").forward(req, resp); return; } } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException("驗證用戶名時數據庫出現異常:"+e.getMessage()); } finally{ JDBCUtils.close(conn, ps, rs); } // 5)驗證碼驗證 // 4.數據存入數據庫 // 驗證信息沒有問題,將用戶提交的註冊信息提交到數據庫 String sql2="insert into user values(null,?,?,?,?)"; Connection conn2=null; PreparedStatement ps2=null; try { conn2=JDBCUtils.getConnections(); ps2=conn2.prepareStatement(sql2); ps2.setString(1, username); ps2.setString(2, password); ps2.setString(3, nickname); ps2.setString(4, email); ps2.executeUpdate(); int i=ps.executeUpdate(); if(i>0){ // 保存成功-提示成功信息,定時刷新到首頁 resp.getWriter().write("<h1 style='text-align:center;color:red'>恭喜您,註冊成功!3秒後自動跳轉首頁</h1>"); // 實現定時刷新 resp.setHeader("refresh", "3;url="+req.getContextPath()+"/index.jsp"); }else{ req.setAttribute("errMsg", "註冊出現異常,請稍後重試..."); req.getRequestDispatcher("/regist.jsp").forward(req, resp); return; } } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException("註冊數據出現異常:"+e.getMessage()); } finally{ JDBCUtils.close(conn2, ps2, rs); } } public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
package cn.bingou.util; public class WebUtils { /** * 驗證字符串是否爲null或是空格的方法 * @param str 被驗證的字符串 * @return true-字符串爲null或者trim以後爲空串 * false-不爲null且trim後不爲空串 */ public static boolean isEmpty(String str){ if(str==null || "".equals(str.trim())){ return true; } return false; } }
package cn.bingou.util; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import com.mchange.v2.c3p0.ComboPooledDataSource; public class JDBCUtils { // 獲取c3p0數據庫鏈接池對象 private static ComboPooledDataSource ds=new ComboPooledDataSource(); /** * 經過數據庫鏈接池獲取一個鏈接對象 * @return 一個鏈接對象 或 null; */ public static Connection getConnections(){ Connection conn=null; try { conn=ds.getConnection(); } catch (SQLException e) { e.printStackTrace(); } return conn; } /** * 關閉數據庫佔用的資源 * @param conn * @param ps * @param rs */ public static void close(Connection conn,Statement ps, ResultSet rs){ if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } if(ps!=null){ try { ps.close(); } catch (SQLException e) { e.printStackTrace(); } } if(rs!=null){ try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
數據庫:數據庫
-- 建立庫 easymall create database bingou; -- 使用easymall庫 use bingou; -- 建立user表 id int,用戶名,密碼,暱稱,郵箱 create table user( id int primary key auto_increment, -- id username varchar(50), -- 用戶名 password varchar(50), -- 密碼 nickname varchar(50), -- 暱稱 email varchar(50) -- 郵箱 ); -- 添加測試數據 insert into user values(null,'admin','123','炒雞管理員','admin@123.com'); insert into user values(null,'張飛','123','管理員','admin@123.com');
配置文件:服務器
<?xml version="1.0" encoding="UTF-8"?> <c3p0-config> <default-config> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/bingou</property> <property name="user">root</property> <property name="password">root</property> </default-config> </c3p0-config>
演示過程:框架
第一步:啓動Tomcat服務器和數據庫jsp
第二部:訪問www.bingou.com
第三步:點擊註冊
第四步:輸入信息註冊,此時數據庫已經保存了用戶註冊信息
出現錯誤:HTTP Status 500 - 註冊數據出現異常:No operations allowed after statement closed.
緣由: 配置文件路徑寫錯