JSP实现数据库登录
数据库没有问题,已经准备好,但是测试的时候,无论输入的用户名密码是否和数据库匹配,都无法登录成功,肯定大神指导!!!!
1.登录页面
login.jsp
<form action="loginCheckServlet" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="user"/></td>
</tr>
<tr>
<td>密 码:</td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td><input type="submit" value="提交"/></td>
<td><input type="reset" value="重置"/></td>
</tr>
</table>
</form>
2.检测是否和数据库匹配
UserCheck.java
public class UserCheck {
private Connection con;
private PreparedStatement pstm;
public boolean login(String name,String pwd) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
boolean flag=false;
try {
//Q MySQL Java
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
try {
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/USER", "root",
"");
st = con.createStatement();
String sql="select * from userlist where username=? and userpwd =?";
pstm = this.con.prepareStatement(sql);
pstm.setString(1, name);
pstm.setString(2, pwd);
rs = pstm.executeQuery();
if(rs.next()){
flag=true;
}
} catch(Exception e){
e.printStackTrace();
}
return flag;
}
}
3.实现跳转页面
LoginCheckServle.tjava
@WebServlet(name = "loginCheckServlet", urlPatterns = { "/loginCheckServlet" })
public class LoginCheckServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("GBK");
HttpSession session = request.getSession();
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
String name1 = (String) session.getAttribute("name");
UserCheck uc = new UserCheck();
boolean f = false;
if(pwd!=null&&name!=null&&name1==null){
f = uc.login(name, pwd);
}else if(name1!=null){
f=true;
}
if (f) {
session.setAttribute("name", name);
session.setAttribute("pwd", pwd);
ServletContext app = this.getServletContext();
RequestDispatcher rd = app.getRequestDispatcher("/loginSuccess.jsp");
rd.forward(request,response);
} else {
ServletContext app = this.getServletContext();
RequestDispatcher rd = app.getRequestDispatcher("/login.jsp");
rd.forward(request,response);
}
}
}