Util工具类
public class DBUtil {
static {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConn() {
Connection conn = null;
try {
conn = DriverManager.getConnection(
"jdbc:sqlserver://localhost:1433;databaseName=School",
"sa", "1");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static void close(Connection conn, PreparedStatement ps, ResultSet rs) {
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (ps != null)
ps.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
注册页面相关代码
InsertServlet.java
public class InsertServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 请求编码设置utf-8
request.setCharacterEncoding("utf-8");
// 请求响应设置utf-8
response.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String userName = request.getParameter("userName");
String pwd = request.getParameter("pwd");
String ageStr = request.getParameter("age");
Integer age = Integer.parseInt(ageStr);
boolean isTrue = false;
Connection conn = DBUtil.getConn();
String sql = "insert into student(name,userName,pwd,age) values (?,?,?,?)";
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql)