天天看點

JSP+JAVABEAN+SERVLET模式的注冊執行個體實作

MVC模式即Model-View-Controller模式。

Servlet用來處理請求的事務,充當控制器(Controller即C)的角色,Servlet負責響應使用者對業務邏輯的請求并根據使用者的請求行為,決定将哪個JSP頁面發送給客戶。

JSP頁面處于表現層,也就是視力(View即V)的角色。

JavaBean則負責資料的處理,也就是模型(Model即M)的角色。

初始的請求由Servlet來處理,Servlet調用商業邏輯和資料處理代碼,并建立Bean來表示相應的結果(模型)。然後Servlet确定哪個頁面适合于表達這些特定的結果,并将請求轉發到相應的頁面(JSP頁面即為視圖),由Servlet确定哪個業務邏輯适用,應該用哪個JSP頁面相應結果(Servlet就是控制器)。

注冊執行個體:

配置檔案配置SERVLET的調用

/PetStore/WebRoot/WEB-INF/web.xml

<servlet>  

<servlet-name>reg</servlet-name>  

<servlet-class>cn.wy.CtrlServlet.reg</servlet-class>  

</servlet>  

<servlet-mapping>  

<url-pattern>/reg</url-pattern>  

</servlet-mapping> 

前端jsp頁面

/PetStore/WebRoot/register.jsp

代碼  

<%@ page contentType="text/html; charset=gb2312" language="java" import="cn.wy.Pet.User" errorPage="" %> 

<jsp:useBean id="user" scope="page" class="cn.wy.Pet.User"/> 

<%   

//權限預設不是超級管理者  

boolean isAdmin = false ;  

String actionStr = "";  

if (session.getAttribute("user") != null)  

    {  

        user = (User)session.getAttribute("user");  

        //取出權限  

        if (user.getUPopedom() ==0)  

            isAdmin = true ;  

    }  

    String qFile = request.getRequestURI();  

    System.out.println(qFile);  

    //說明是超級管理者,并在背景添加使用者  

    if ("/admin/default.jsp".equals(qFile))  

        actionStr = "../" ;  

%> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 

<html xmlns="http://www.w3.org/1999/xhtml"> 

<head> 

<meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 

<title>寵物商店會員注冊</title> 

<style type="text/css"> 

<!--  

.STYLE1 {  

    color: #FF0000;  

    font-weight: bold;  

}  

.STYLE2 {color: #FF0000}  

.STYLE3 {  

    font-size: 18px;  

--> 

</style> 

</head> 

<body style="font-size:12px"> 

<form id="form1" name="form1" method="post" action="<%=actionStr%>reg"> 

  <p align="center"><br /> 

    <span class="STYLE3">使用者注冊</span></p> 

  <table width="582" height="302" border="1" align="center" cellpadding="0" cellspacing="0" bordercolor="#BCACD2"> 

    <tr> 

      <td width="80" align="right">使用者名:</td> 

      <td width="496" align="left"><input name="userName" type="text" id="userName" size="16" maxlength="16" /> 

      <span class="STYLE1">*</span> 3~16位字母或者數字(如:8hack)</td> 

    </tr> 

      <td align="right">密碼:</td> 

      <td align="left"><input name="password1" type="text" id="password1" size="16" maxlength="16" /> 

      <span class="STYLE1">*  </span> 3~16位字母或者數字(如:abc123)</td> 

      <td align="right">确認密碼:</td> 

      <td align="left"><input name="password2" type="text" id="password2" size="16" maxlength="16" /> 

      <span class="STYLE1">*</span> 必須和上面輸入的密碼相同</td> 

      <td align="right">電子郵件:</td> 

      <td align="left"><input name="email" type="text" id="email" maxlength="20" /> 

      <span class="STYLE1">*</span> 找回密碼和聯系用(如:[email protected])</td> 

      <td align="right">聯系電話:</td> 

      <td align="left"><input name="tel" type="text" id="tel" size="20" maxlength="20" /> 

      如(0871-8888888,13888853113)</td> 

      <td align="right">聯系位址:</td> 

      <td align="left"><input name="address" type="text" id="address" maxlength="50" /></td> 

        <%  

        if (isAdmin)//如果是管理者就顯示出下拉清單  

        {  

        %> 

      <td height="26" align="right">權限:</td> 

      <td align="left"> 

        <select name="popedom" id="popedom"> 

            <option value="0">超級管理者</option>          

            <option value="1">會員</option> 

        </select> 

    </td> 

        }else//否則就插入一個蘊藏域  

        <input type="hidden" name="popedom" value="1"> 

        }  

      <td height="42" align="right"> </td> 

      <td align="left"><span class="STYLE2">為了友善聯系和管理請認真填寫你的資訊,帶星号的必須填寫</span></td> 

      <td height="40" colspan="2" align="center"><input type="submit" name="Submit" value="确認注冊" /> 

            

      <input type="reset" name="Submit2" value="重新填寫" /></td> 

  </table> 

</form> 

</body> 

</html> 

servlet類

/PetStore/src/cn/wy/CtrlServlet/reg.java

package cn.wy.CtrlServlet;  

import cn.wy.DBConnection;  

import java.io.*;  

import java.sql.*;  

import javax.servlet.ServletException;  

import javax.servlet.http.*;  

// Referenced classes of package cn.wy.CtrlServlet:  

//            login  

public class reg extends HttpServlet  

{  

    public reg()  

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)  

        throws ServletException, IOException  

        PrintWriter out;  

        DBConnection dbc=null;  

        String userName;  

        String psd;  

        String email;  

        String tel;  

        String address;  

        int popedom;  

        response.setContentType("text/html;charset=UTF-8");  

        out = response.getWriter();  

        try{  

        dbc = new DBConnection();  

        PreparedStatement ps = null;  

        userName = request.getParameter("userName");  

        psd = login.encrypt(request.getParameter("password1").toString());  

        email = request.getParameter("email");  

        tel = request.getParameter("tel");  

        address = request.getParameter("address");  

        popedom = Integer.parseInt(request.getParameter("popedom"));  

        if (userName != null && psd != null && email != null)  

        ps = dbc.getCon().prepareStatement("insert into [User](UName,Upass,UEmail,UTel,UAddress,UPopedom) values(?,?,?,?,?,?)");  

        ps.setString(1, userName);  

        ps.setString(2, psd);  

        ps.setString(3, email);  

        ps.setString(4, tel);  

        ps.setString(5, address);  

        ps.setInt(6, popedom);  

        ps.execute();  

        System.out.print("新使用者注冊:" + request.getParameter("userName") + "  ");  

        out.print("<script>alert('恭喜您:注冊成功!現已經登入到網站!');history.go(-1)</script>");  

        if (dbc != null)  

            dbc.dbClose();  

        catch(SQLException ex)  

        out.print("<script>alert('注冊失敗!資料庫連接配接錯誤!');history.go(-1)</script>");  

        ex.printStackTrace();  

    protected void doGet(HttpServletRequest request, HttpServletResponse response)  

        processRequest(request, response);  

    protected void doPost(HttpServletRequest request, HttpServletResponse response)  

    public String getServletInfo()  

        return "Short description";  

資料庫連接配接類

/PetStore/src/cn/wy/DBConnection.java

package cn.wy;  

import java.io.PrintStream;  

import java.sql.Connection;  

import java.sql.DriverManager;  

public class DBConnection  

    private String mySqlDriver;  

    private String mySqlUrl;  

    private String mdbDrStr;  

    private String mdbUrl;  

    long time;  

    private String SQLDRIVER;  

    private String SQLURL;  

    public Connection conn;  

    boolean Conectde;  

    public DBConnection()  

        mySqlDriver = "org.gjt.mm.mysql.Driver";  

        mySqlUrl = "jdbc:mysql://localhost/petstore?user=root&password=5455&useUnicode=true&characterEncoding=8859_1";  

        mdbDrStr = "sun.jdbc.odbc.JdbcOdbcDriver";  

        mdbUrl = "jdbc:odbc:pet";  

        SQLDRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver";  

        SQLURL = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=PetStore";  

        conn = null;  

        Conectde = false;  

        time = System.currentTimeMillis();  

        try 

            Class.forName(SQLDRIVER).newInstance();  

            if (conn == null)  

            {  

                conn = DriverManager.getConnection(SQLURL, "sa", "123456");  

                Conectde = true;  

                System.out.print("<");  

            }  

        catch (Exception e)  

            e.printStackTrace();  

    public Connection getCon()  

        return conn;  

    public void dbClose()  

            if (Conectde)  

                conn.close();  

                Conectde = false;  

                System.out.print(System.currentTimeMillis() - time);  

                System.out.print(">  ");  

JavaBean類

/PetStore/src/cn/wy/Pet/User.java

package cn.wy.Pet;  

public class User  

    private int userID;  

    private String UName;  

    private String UPass;  

    private String UEmail;  

    private String UTel;  

    private String UAddress;  

    private String URegDate;  

    private String ALastTime;  

    private int UPopedom;  

    private int UAppearCount;  

    private int URestoreCount;  

    private boolean login;  

    public User()  

        login = false;  

    public boolean isLogin()  

        return login;  

    public void setLogin(boolean isLogin)  

        login = isLogin;  

    public void setURestoreCount(int URestoreCount)  

        this.URestoreCount = URestoreCount;  

    public int getURestoreCount()  

        return URestoreCount;  

    public void setUAppearCount(int UAppearCount)  

        this.UAppearCount = UAppearCount;  

    public int getUAppearCount()  

        return UAppearCount;  

    public void setUserID(int userID)  

        this.userID = userID;  

    public void setUPopedom(int UPopedom)  

        this.UPopedom = UPopedom;  

    public void setALastTime(String ALastTime)  

        this.ALastTime = ALastTime;  

    public void setURegDate(String URegDate)  

        this.URegDate = URegDate;  

    public void setUAddress(String UAddress)  

        this.UAddress = UAddress;  

    public void setUTel(String UTel)  

        this.UTel = UTel;  

    public void setUEmail(String UEmail)  

        this.UEmail = UEmail;  

    public void setUPass(String UPass)  

        this.UPass = UPass;  

    public void setUName(String UName)  

        this.UName = UName;  

    public int getUserID()  

        return userID;  

    public int getUPopedom()  

        return UPopedom;  

    public String getALastTime()  

        return ALastTime;  

    public String getURegDate()  

        return URegDate;  

    public String getUAddress()  

        return UAddress;  

    public String getUTel()  

        return UTel;  

    public String getUEmail()  

        return UEmail;  

    public String getUPass()  

        return UPass;  

    public String getUName()  

        return UName;  

本文轉自linzheng 51CTO部落格,原文連結:http://blog.51cto.com/linzheng/1080779