注册JSP:
servlet类<注:需在WEB.XML中配置servlet>:
public class RegisServlet extends HttpServlet {
private String driverClass=null;
private String url=null;
private String dbUserName=null;
private String dbPassword=null;
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String name=request.getParameter("userName");
String password=request.getParameter("password");
Connection conn = null;
PreparedStatement psta=null;
try {
conn = DriverManager.getConnection(url, dbUserName, dbPassword);
conn.setAutoCommit(false);
String sql = " insert into user(name,password) values (?,?)";
psta = conn.prepareStatement(sql);
psta.setString(1, name.trim());
psta.setString(2, password.trim());
psta.execute();
conn.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
} finally {
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
}
}
if(psta!=null){
try {
psta.close();
} catch (SQLException e) {
}
}
}
//浏览器回应
PrintWriter out = response.getWriter();
StringBuffer strb = new StringBuffer();
strb.append("").append("").append("
").append("用户列表")
.append("").append("").append("");
strb.append("
");
strb.append("");
strb.append("");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
out.print(strb.toString());
out.flush();
out.close();
}
public void init() throws ServletException {
InputStream is = RegisServlet.class.getClassLoader()
.getResourceAsStream("com/jdbc.properties");
Properties p = new Properties();
try {
p.load(is);
} catch (IOException e) {
e.printStackTrace();
}
this.driverClass = p.getProperty("driverClass").trim();
this.url = p.getProperty("url").trim();
this.dbUserName = p.getProperty("userName").trim();
this.dbPassword = p.getProperty("password").trim();
try {
Class.forName(driverClass);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
mysql数据库连接类:
public class TestJdbc {
public static void main(String[] args) {
InputStream is = RegisServlet.class.getClassLoader()
.getResourceAsStream("com/jdbc.properties");
Properties p = new Properties();
try {
p.load(is);
} catch (IOException e) {
e.printStackTrace();
}
String driverClass = p.getProperty("driverClass").trim();
String url = p.getProperty("url").trim();
String userName = p.getProperty("userName").trim();
String password = p.getProperty("password").trim();
try {
Class.forName(driverClass);
Connection conn =DriverManager.getConnection(url,userName,password);
System.out.println(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
}
JDBC.properties文件:
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/userdb
userName=root
password=root