日期:2014-05-17 浏览次数:20884 次
public class Login extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
try {
//中文乱码
response.setContentType("text/html;charset=gb2312");
PrintWriter pw=response.getWriter();
//返回登陆界面
pw.println("<html>");
pw.println("<body>");
//得到error信息
String info=request.getParameter("info");
if (info!=null) {
pw.println("<h1>你的用户名或是密码错误</h1>");
}
pw.println("<h1>登陆界面</h1>");
pw.println("<form action=Logincl method=post>");
pw.println("用户名:<input type=text name='username' /><br/>");
pw.println("密码:<input type=password name=password /><br/>");
pw.println("<input type=submit value=login /><br/>");
pw.println("</form>");
pw.println("</body>");
pw.println("</html");
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class Logincl extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
// 业务逻辑
try {
request.setCharacterEncoding("GBK");
// 接收用户名和密码
String username = request.getParameter("username");
String pwd = request.getParameter("password");
// 连接数据库
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:sjbitdb", "epet", "bdqn");
pstmt = conn
.prepareStatement("select * from master where loginname=? and pwd=?");
pstmt.setString(1, username);
pstmt.setString(2, pwd);
rs = pstmt.executeQuery();
// 验证
if (rs.next()) {
// 合法(跳转到welcome)
response.sendRedirect("Welcome?username="+username+"&pwd="
+ pwd);
System.out.println("username"+username);//此处在控制台显示 仍然能够打印出 张三
} else {
// 不合法
response.sendRedirect("Login");// 写你要跳到的servlet的url
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if (rs!=null) {
rs.close();
}
if (pstmt!=null) {
pstmt.close();
}
if (conn!=null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response) {
doGet(request, response);
}
}
public class Welcome extends HttpServlet {