packagecom.qdu.sun;importjava.io.IOException;importjava.io.PrintWriter;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importjava.sql.*;publicclassLoginSvltextendsHttpServlet {privateString username;privateString password;publicLoginSvlt() {super();
}publicvoiddestroy() {super.destroy();//Just puts "destroy" string in log//Put your code here}/*** The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
*@paramrequest the request send by the client to the server
*@paramresponse the response send by the server to the client
*@throwsServletException if an error occurred
*@throwsIOException if an error occurred*//*** The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
*@paramrequest the request send by the client to the server
*@paramresponse the response send by the server to the client
*@throwsServletException if an error occurred
*@throwsIOException if an error occurred*/publicvoiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {
username=request.getParameter("username");
password=request.getParameter("password");//先定义变量,后使用和关闭Connection conn=null;//声明数据库连接对象Statement stmt=null;//声明数据库表达式对象ResultSet rs=null;//声明结果集对象try{//载入Mysql的驱动字符串Class.forName("com.mysql.jdbc.Driver");//获取数据库的连接conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/login","root","123456");//获取表达式对象实例stmt=conn.createStatement();
rs=stmt.executeQuery("select * from user where username='"+username+"'and password='"+password+"'");if(rs.next())
{
HttpSession session=request.getSession(true);
session.setAttribute("username", username);
response.sendRedirect("welcome.jsp");
}else{
response.sendRedirect("error.jsp");
}
}catch(Exception e) {
e.printStackTrace();
}
}/*** Initialization of the servlet.
*
*@throwsServletException if an error occurs*/publicvoidinit()throwsServletException {//Put your code here}
}