1. 程式人生 > >用servlet寫的學生登入註冊

用servlet寫的學生登入註冊

①資料庫

CREATE TABLE `member` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `pass` varchar(20) NOT NULL,
  `age` int(3) DEFAULT NULL,
  `sex` varchar(2) DEFAULT NULL,
  `hobby` varchar(20) DEFAULT NULL COMMENT '愛好',
  `ipaddr` varchar(20) DEFAULT NULL,
  `sheng` varchar(10) DEFAULT
NULL, `info` text, PRIMARY KEY (`id`) )

②首頁:

<body>
    <h1>學生管理系統</h1>

    <form action="login" method="post">
    <table>
        <tr>
            <td>使用者名稱:</td>
            <td><input type="text" name="username"></td>
        </tr
>
<tr> <td>密碼:</td> <td><input type="password" name="pass"></td> </tr> <tr> <td><input type="submit" value="登入"> </td> <td><a href="reg.html">沒有賬號?點我註冊</a
>
</td> </tr> </table> </form> </body>

③註冊:

<body>
   <h1>使用者註冊</h1>
   <form action="reg" method="post">
        使用者名稱:<input type="text" name="username"><br>
        密碼:<input type="password" name="pass"><br>
        重複密碼:<input type="password" name="pass2"><br>
        年齡:<input type="text" name="age"><br>
        性別:男<input type="radio" name="sex" value="男"> 
                   女<input type="radio" name="sex" value="女"> 
        <br>
        愛好:
        旅遊 <input type="checkbox" name="hobby" value="旅遊"> 
        程式設計 <input type="checkbox" name="hobby" value="程式設計"> 
        美食 <input type="checkbox" name="hobby" value="美食"> 
        <br>
        所在省份:<select name="sheng">
                    <option value="湖北">湖北</option>
                    <option value="湖南">湖南</option>
                    <option value="河北">河北</option>
                    <option value="河南">河南</option>
                </select><br>
        個人簡介:<textarea rows="6" cols="35" name="info"></textarea>
        <br>
        <input type="submit" value="註冊">
   </form>

  </body>

④連線資料庫的工具類:

package com.bright;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class JDBCUtil {

    private String url;     //url地址
    private String dbuser;  //資料庫的使用者名稱
    private String dbpass;  //資料庫的登入密碼

    public String getUrl() {
        return url;
    }
    public void setUrl(String url) {
        this.url = url;
    }
    public String getDbuser() {
        return dbuser;
    }
    public void setDbuser(String dbuser) {
        this.dbuser = dbuser;
    }
    public String getDbpass() {
        return dbpass;
    }
    public void setDbpass(String dbpass) {
        this.dbpass = dbpass;
    }

    public JDBCUtil() {
        super();
    }

    public JDBCUtil(String url, String dbuser, String dbpass) {
        super();
        this.url = url;
        this.dbuser = dbuser;
        this.dbpass = dbpass;
    }

    //靜態程式碼塊,載入驅動
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    //對外提供一個連線資料庫的方法
    public Connection getConnection() throws Exception{
        return DriverManager.getConnection(this.url, this.dbuser, this.dbpass);
    }
}

⑤定義一個使用者類:

package com.bright;

public class User {
    private int id;
    private String username;
    private String pass;
    private int age;
    private String sex;
    private String hobby;
    private String sheng;
    private String ipaddr;
    private String info;

    public User() {
        super();
    }   
    public User(String username, String pass, int age, String sex,
            String hobby, String sheng, String ipaddr, String info) {
        super();
        this.username = username;
        this.pass = pass;
        this.age = age;
        this.sex = sex;
        this.hobby = hobby;
        this.sheng = sheng;
        this.ipaddr = ipaddr;
        this.info = info;
    }

    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPass() {
        return pass;
    }
    public void setPass(String pass) {
        this.pass = pass;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getHobby() {
        return hobby;
    }
    public void setHobby(String hobby) {
        this.hobby = hobby;
    }
    public String getSheng() {
        return sheng;
    }
    public void setSheng(String sheng) {
        this.sheng = sheng;
    }
    public String getIpaddr() {
        return ipaddr;
    }
    public void setIpaddr(String ipaddr) {
        this.ipaddr = ipaddr;
    }
    public String getInfo() {
        return info;
    }
    public void setInfo(String info) {
        this.info = info;
    }
}

⑥使用者類的處理:

package com.bright;

import java.sql.*;

//註冊的時候儲存使用者(通過使用者的id)
public class UserDao {

    //因為這個操作類就是對資料庫進行操作,所有要連線資料庫
    private JDBCUtil util;

    public JDBCUtil getUtil() {
        return util;
    }

    public void setUtil(JDBCUtil util) {
        this.util = util;
    }

    //
    public void saveUser(User user){

        Connection conn = null;
        PreparedStatement stat = null;

        try {
            String sql = "insert into member values (null,?,?,?,?,?,?,?,?)";
            conn = util.getConnection();        //建立連線
            stat = conn.prepareStatement(sql);  //建立預處理物件

            //儲存資料(有幾個問好,就存幾個)
            stat.setString(1, user.getUsername());
            stat.setString(2, user.getPass());
            stat.setInt(3, user.getAge());
            stat.setString(4, user.getSex());
            stat.setString(5, user.getHobby());
            stat.setString(6, user.getIpaddr());
            stat.setString(7, user.getSheng());
            stat.setString(8, user.getInfo());

            stat.executeUpdate();//儲存

        } catch (Exception e) {
            e.printStackTrace();
        }finally{

            try {
                if(conn!=null&!conn.isClosed()){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }

    //登入時,通過使用者名稱找到這個物件,因為查詢到的是一個物件,所有返回一個user
    public User getUserByName(String uname){
        User user = null;

        Connection conn = null;
        PreparedStatement stat = null;
        ResultSet res = null;

        try {
            String sql = "select * from member where username = ?";
            conn = util.getConnection();
            stat = conn.prepareStatement(sql);

            stat.setString(1, uname);

            //把查詢到的資料放到結果集中
            res = stat.executeQuery();//查詢

            //如果查詢到,就將結果集中的資料儲存到使用者中
            if(res.next()){
                user = new User();
                user.setId(res.getInt("id"));
                user.setAge(res.getInt("age"));
                user.setUsername(res.getString("username"));
                user.setPass(res.getString("pass"));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally{

            try {
                if(conn!=null&!conn.isClosed()){
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        return user;
    }   
}

⑦處理登入:

package com.bright;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //獲取請求引數
        req.setCharacterEncoding("utf8");
        String username = req.getParameter("username");
        String pass = req.getParameter("pass");

        resp.setContentType("text/html;charset=utf8");
        PrintWriter out = resp.getWriter();

        //如果使用者名稱和密碼不為空,並且長度大於0就執行if語句--->判斷查詢到的user--->判斷密碼是否一致
        if(username!=null&&username.length()>0&&pass!=null&&pass.length()>0){

            //要連線資料庫,先從配置表中獲取初始化引數傳給JDBSUtil的建構函式
            ServletContext ctx = this.getServletContext();
            String url = ctx.getInitParameter("url");
            String dbuser = ctx.getInitParameter("dbuser");
            String dbpass = ctx.getInitParameter("dbpass");

            JDBCUtil util = new JDBCUtil(url, dbuser, dbpass);      

            //然後將util作為引數傳給操作類
            UserDao dao = new UserDao();
            dao.setUtil(util);

            //呼叫操作類的通過使用者名稱查詢使用者
            User user = dao.getUserByName(username);

            if(user!=null){
                if(user.getPass().equals(pass)){
                    out.println("<h1>恭喜你!登入成功!進入了學生管理系統!</h1>");
                }else{
                    out.println("<h1>登入失敗!密碼錯誤!</h1>");
                    out.println("<br><a href='index.jsp'>點此登入</a>");
                }
            }else{
                out.println("<h1>登入失敗!使用者名稱錯誤!</h1>");
                out.println("<br><a href='index.jsp'>點此登入</a>");
            }

        }else{
            out.println("<h1>登入失敗!使用者名稱/密碼錯誤!</h1>");
            out.println("<br><a href='index.jsp'>點此登入</a>");
        }


        out.flush();
        out.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(req, resp);
    }

}

⑧處理註冊:

package com.bright;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class RegServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {

        //提交方式為post
        req.setCharacterEncoding("utf8");

        //接收請求中的引數
        String username = req.getParameter("username");
        String pass = req.getParameter("pass");
        String pass2 = req.getParameter("pass2");
        String age = req.getParameter("age");
        String sex = req.getParameter("sex");
        String[] hobbys = req.getParameterValues("hobby");
        String hobby = "";
        for(int i=0;i<hobbys.length;i++){
            if(i!=hobbys.length-1){
                hobby += hobbys[i]+",";
            }else{
                hobby += hobbys[i];
            }
        }
        String sheng = req.getParameter("sheng");
        String info = req.getParameter("info");
        String ipaddr = req.getRemoteAddr();

        int iage = -1;
        try {
            iage = Integer.parseInt(age);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        resp.setContentType("text/html;charset=utf8");
        PrintWriter out = resp.getWriter();

        //輸入校驗
        if(username!=null&&username.length()>5&&pass!=null&&pass.length()>5&&pass.equals(pass2)&&iage>=0){

            //要連線資料庫,先從配置表中獲取初始化引數傳給JDBSUtil的建構函式
            ServletContext ctx = this.getServletContext();
            String url = ctx.getInitParameter("url");
            String dbuser = ctx.getInitParameter("dbuser");
            String dbpass = ctx.getInitParameter("dbpass");         
            JDBCUtil util = new JDBCUtil(url, dbuser, dbpass);

            //userdao--->util--->資料庫
            //然後將util作為引數傳給操作類
            UserDao dao = new UserDao();
            dao.setUtil(util);

            //將獲取的的引數存到uer中,呼叫操作類中的方法儲存
            User user = new User(username, pass, iage, sex, hobby, sheng, ipaddr, info);
            dao.saveUser(user);

            out.println("<h1>恭喜你!註冊成功</h1>");
            out.println("<br><a href='index.jsp'>點此登入</a>");
        }else{

            out.println("<h1>引數有誤,註冊失敗!</h1>");
            out.println("<br><a href='reg.html'>重新註冊</a>");

        }

        out.flush();
        out.close();


    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(req, resp);
    }       
}

⑨配置資訊:

<?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> 
  <context-param>
    <param-name>url</param-name>
    <param-value>jdbc:mysql:///servlet</param-value>
  </context-param>
  <context-param>
    <param-name>dbuser</param-name>
    <param-value>root</param-value>
  </context-param>
  <context-param>
    <param-name>dbpass</param-name>
    <param-value>123</param-value>
  </context-param>

  <servlet>
    <servlet-name>RegServlet</servlet-name>
    <servlet-class>com.bright.RegServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>RegServlet</servlet-name>
    <url-pattern>/reg</url-pattern>
  </servlet-mapping>

  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.bright.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login</url-pattern>
  </servlet-mapping>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>