一、登录页面主要代码:login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<body>
<form id="form1" name="form1" method="post" action="servlet/LoginServlet">
<table width="260" border="1" align="center">
<tr>
<td width="64">用户:</td>
<td width="180"><input type="text" name="username" /></td>
</tr>
<tr>
<td>密码:</td>
<td> <input type="password" name="userpass" /></td>
</tr>
<tr>
<td> </td>
<td>
<input type="submit" name="Submit2" value="登录" />
<input type="reset" name="Submit" value="重置" />
</td>
</tr>
</table>
</form>
</body>
二、对用户登录进行的操作类:loginDao.java
package com.login;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.db.dbpool; //数据库连接包
public class loginDao { //对用户登录进行的操作类
Connection myCon=null;
PreparedStatement pst=null;
ResultSet rs=null;
//管理员登录验证方法
public boolean CheckLogin(String username,String userpass)
{
boolean bool=false;
dbpool pool=new dbpool(); //实例化数据库连接
myCon=pool.getConnection(); //调用连接方法
String sql="select * from td_user where uname='"+username+"' and upass='"+userpass+"'";;
try {
pst=myCon.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next())
{
bool=true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bool;
}
}
三、登录的servlet主要代码:LoginServlet.java
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.login.loginDao; //对登录验证操作的类
public class LoginServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//管理员登录验证
request.setCharacterEncoding("gb2312");
String username=request.getParameter("username"); //获取登录表单数据
String userpass=request.getParameter("userpass");
loginDao lodo=new loginDao(); //声明操作类,调用验证方法
boolean bool=lodo.CheckLogin(username, userpass);
if(bool)
{ //通过验证,登录成功 跳转到目标页面
response.sendRedirect("index.jsp");
}else{
response.sendRedirect("login.jsp");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}