关于srevlet
/*
* Created on 2004-9-14
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package login;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
/**
* @author Administrator
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class Login_server extends HttpServlet {
private static final String CONTENT_TYPE = "text/html; charset=GB2132";
private Connection conn=null;
public void init() throws ServletException {
}
//Process the HTTP Get request
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType(CONTENT_TYPE);
PrintWriter out=response.getWriter();
HttpSession session=request.getSession(true);
//从session中得到数据库连接
conn=(Connection)session.getAttribute("mpsConn");
//如果没有数据库连接,新建一个连接,并且加如session中
try{
if(conn==null){
String url1="jdbc:odbc:SELLSYSTEM";
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
conn = DriverManager.getConnection(url1,"","");
session.setAttribute("mps",conn);
}
}
catch(Exception e){
System.out.println(e);
}
//根据用户输入查找
String sql="select * from user where userName='"+request.getParameter("user")+"'";
try{
Statement stm=conn.createStatement();
ResultSet result=stm.executeQuery(sql);
String tempPassword=new String();
String userId=new String();
while(result.next()){
tempPassword=result.getString("password");
userId=result.getString("userId");
}
//于用户填入的密码作比较
if(tempPassword==request.getParameter("password")){
session.setAttribute("userName",request.getParameter("user"));
session.setAttribute("userId",userId);
gotoPage("../index.jsp",request,response);
}else{
out.println("<html>");
out.println("<body>");
out.println("<head><title></title></head>");
out.println("<p>"+"您输入的帐号或密码错误!</p>");
out.println("<p><a href='../index.jsp'>"+"请返回...</a></p>");
out.println("</body></html>");//这里出现乱码!怎么回事?
}
}catch(Exception e){
System.err.println(e);
}
}
//该方法用于定位新的页面
public void gotoPage(String address,
HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispacher = getServletContext().getRequestDispatcher(address);
dispacher.forward(request, response);
}
}