日期:2014-05-20 浏览次数:20771 次
<%@ page language="java" contentType="text/html; charset=gb2312"
pageEncoding="gb2312"%>
<html>
<head>
<title>123 </title>
</head>
<body>
<h2 align="center">
登陆界面
</h2>
<br>
<div align="center">
<form action="LoginServlet" method="post">
用户名:
<input type="text" name="userName" />
密码:
<input type="password" name="userPassword" />
<br>
<input type="submit" value="登录" />
<input type="reset" value="重置" />
</form>
</div>
<font color="red">
<%
String result=(String)request.getAttribute("error");
if(result!=null)
{
if("NOUSER".equals(result))
{
out.println("用户不存在");
}else{
out.println("密码错误");
}
}
%>
</font>
</body>
</html>
package news.control;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import news.logic.LoginLogicBean;
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userName=request.getParameter("userName");
String userPwd=request.getParameter("userPassword");
LoginLogicBean loginBean=new LoginLogicBean();
String result=loginBean.verify(userName, userPwd);
if("OK".equals(result))
{
request.getSession().setAttribute("user","userName");
request.getRequestDispatcher("/list.jsp").forward(request,response);
}else if("PWD".equals("result"))
{
request.setAttribute("error", "PWD");
request.getRequestDispatcher("/index.jsp").forward(request,response);
}else
{
request.setAttribute("error", "NOUSER");
request.getRequestDispatcher("/index.jsp").forward(request,response);
}
}
}
package news.logic; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import news.comm.DataSource; public class LoginLogicBean { //用户名不存在密码就不用判断了 public String verify(String userName,String userPwd) { String result=null; Connection conn=null; Statement st=null; ResultSet rs=null; conn=DataSource.getConnection(); try { st=conn.createStatement(); rs=st.executeQuery("select password from user where username='"+userName+"'"); if(rs.next()) { if(userPwd.equals(rs.getString("password"))) { result="OK"; }else { result="PWD"; } } else{ result="no user"; } } catch (SQLException e) { e.printStackTrace(); }finally { try { if(rs!=null)rs.close(); if(st!=null)st.close(); } catch (SQLException e) { e.printStackTrace(); } } return result; } }