使用JSP完成用户注册

本文讲解使用JSP完成用户注册,数据库是MySQL5.7。

1 下载mysql驱动包

下载mysql驱动包

2 创建表

在MySQL的test数据库建立t_user表:

CREATE TABLE `t_user` (
   `id` int(11) NOT NULL AUTO_INCREMENT,
   `username` varchar(50) DEFAULT NULL,
   `password` varchar(50) DEFAULT NULL,
   PRIMARY KEY (`id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8

3 编写index.jsp

index.jsp提供用户填写注册信息的表单:

<%@ page language="java" contentType="text/html;charset=utf-8" %>
<html>
<html>
<head>
    <meta charset="utf-8">
    <title>一点教程网-使用JSP完成用户注册</title>
</head>
<body>

<h1>使用JSP完成CRUD</h1>
<form action="process.jsp" method="post">

    用户名:<input type="text" name="username"/><br/><br/>
    密码:<input type="password" name="password"/><br/><br/>
    <br/>
    <input type="submit" value="注册"/>

</form>

</body>
</html>

4 编写process.jsp

process.jsp用于调用Dao的注册方法

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="com.yiidian.dao.UserDao"%>
<html>
<head>
    <title>一点教程网-使用JSP完成用户注册</title>
</head>
<body>
<%
    //设置请求参数中文编码
    request.setCharacterEncoding("utf-8");
%>
<jsp:useBean id="user" class="com.yiidian.domain.User"/>
<jsp:setProperty property="*" name="user"/>

<%
    int status=UserDao.register(user);
    if(status>0)
        out.print("你已经注册成功啦");

%>

</body>
</html>

5 编写User实体

User.java 用于封装注册表单数据:

package com.yiidian.domain;

/**
 * 一点教程网 - http://www.yiidian.com
 */
public class User {
   private String username;
   private String password;

    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;
    }
}

6 编写UserDao

UserDao 提供注册方法,负责保存用户信息到数据库:

package com.yiidian.dao;

import com.yiidian.domain.User;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

/**
 * 一点教程网 - http://www.yiidian.com
 */
public class UserDao {

    public static Connection getConnection(){
        Connection con=null;
        try{
            Class.forName("com.mysql.jdbc.Driver");
            con= DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
        }catch(Exception e){System.out.println(e);}
        return con;
    }

    public static int register(User user){
        int status=0;
        try{
            Connection con=getConnection();
            PreparedStatement ps=con.prepareStatement(
                    "insert into t_user(username,password) values(?,?)");
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());
            status=ps.executeUpdate();
        }catch(Exception e){
            System.out.println(e);
        }
        return status;
    }


}

7 运行测试

 

推荐好课