1.新建mysql数据库 create database spring;
切换数据库 use spring;
新建表 create table user (id int(3) auto_increment not null primary key,username varchar(20),password varchar(20));
2.写程序
Stringpath=request.getContextPath();StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";Stringusername=request.getParameter("username");Stringpassword=request.getParameter("password");Stringpassword2=request.getParameter("password");
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection("jdbc:mysql://localhost/spring","root","123456");StringsqlQuery= "select count(*) from user where username = ?";
PreparedStatement psQuery=conn.prepareStatement(sqlQuery);
psQuery.setString(1, username);
ResultSet rs=psQuery.executeQuery();
rs.next();intcount=rs.getInt(1);if(count> 0){
response.sendRedirect("registerFail.jsp");
psQuery.close();
conn.close();
return ;
}Stringsql= "insert into user values(null, ? ,? )";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
ps.executeUpdate();
ps.close();
conn.close();
response.sendRedirect("registerSuccess.jsp");%>
4. 在register.jsp中展示
用户名:
密码:
确认密码:
添加User和UserManager类,实现deal.jsp中的功能
1. com.liu.registration.model
package com.liu.registration.model;
public class User {
int id;
String username;
String password;
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 getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
2.com.liu.registration.service
package com.liu.registration.service;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import com.liu.registration.model.User;
public class UserManager {
public boolean exists(User u) throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/spring","root","123456");
String sqlQuery = "select count(*) from user where username = ?";
PreparedStatement psQuery = conn.prepareStatement(sqlQuery);
psQuery.setString(1, u.getUsername());
ResultSet rs = psQuery.executeQuery();
rs.next();
int count = rs.getInt(1);
psQuery.close();
conn.close();
System.out.println("count = " + count);
if (count > 0 ){
return true;
} else{
return false;
}
}
public void add(User u) throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/spring","root","123456");
String sql = "insert into user values(null, ? ,? )";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString(1, u.getUsername());
ps.setString(2, u.getPassword());
ps.executeUpdate();
ps.close();
conn.close();
}
}
总结