//*****RegisterServlet.java*******
//完成用户自助注册任务。将用户名,密码,邮箱等信息保存至MySQL数据库,参数传入由JSP文件SelfRegister.jsp完成。
1 importjava.io.IOException;2 importjava.io.PrintWriter;3 importjava.sql.Connection;4 importjava.sql.DriverManager;5 importjava.sql.SQLException;6 importjava.sql.Statement;7
8 importjavax.servlet.RequestDispatcher;9 importjavax.servlet.ServletException;10 importjavax.servlet.annotation.WebServlet;11 importjavax.servlet.http.HttpServlet;12 importjavax.servlet.http.HttpServletRequest;13 importjavax.servlet.http.HttpServletResponse;14
15 /**
16 * Servlet implementation class RegisterServlet17 */
18 @WebServlet("/RegisterServlet")19 public class RegisterServlet extendsHttpServlet {20 private static final long serialVersionUID = 1L;21
22 /**
23 *@seeHttpServlet#HttpServlet()24 */
25 publicRegisterServlet() {26 super();27 //TODO Auto-generated constructor stub
28 }29
30 /**
31 *@seeHttpServlet#service(HttpServletRequest request, HttpServletResponse response)32 */
33 protected void service(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {34 //TODO Auto-generated method stub
35 String DBDRIVER = "com.mysql.jdbc.Driver";36 String DBURL = "jdbc:mysql://localhost:3306/test";37 String DBUSER = "root";38 String DBPASS = "sap123";39
40 Connection con = null;41 Statement stmt = null;42 String username = request.getParameter("username");43 String password = request.getParameter("pass");44 String email = request.getParameter("email");45
46 if(username != null)47 {48 try{49 Class.forName(DBDRIVER);50 } catch(ClassNotFoundException e) {51 //TODO Auto-generated catch block
52 e.printStackTrace();53 }54 try{55 con =DriverManager.getConnection(DBURL,DBUSER,DBPASS);56 } catch(SQLException e) {57 //TODO Auto-generated catch block
58 e.printStackTrace();59 }60
61 try{62 stmt =con.createStatement();63 } catch(SQLException e1) {64 //TODO Auto-generated catch block
65 e1.printStackTrace();66 }67
68
69
70
71 try{72 stmt.executeUpdate("insert into userData values('" + username + "','" + password +"','"+ email +"')");73 } catch(SQLException e1) {74 //TODO Auto-generated catch block
75 e1.printStackTrace();76 }77
78
79 try{80 con.close();81 } catch(SQLException e) {82 //TODO Auto-generated catch block
83 e.printStackTrace();84 }85
86
91 }92
93
94
95 RequestDispatcher rd;96
97 rd = request.getRequestDispatcher("/LoginPage.jsp");98 try{99 rd.forward(request, response);100 return;101 }catch(Exception e){}102
103 //response.sendRedirect("http://www.baidu.com");104 //response.sendRedirect("/Login/LoginPage.jsp");
105 }106
107 }