用servlet進行用戶名和密碼校驗
目錄結構:
一、在Email_Login.jsp中,創建表單
當輸入賬號和密碼,提交到${pageContext.request.contextPath }/LoginTestServlet"
二、創建servlet:LoginTestServlet
代碼如下
- 修改編碼方式
- 使用request.getParameter()方法獲取表單中的name和password
- 實例化UserServiceImpl方法,調用其方法findUserByNameAndPwd(User user),返回值為int num,如果數據庫中包含符合條件的User,則num的值大於零,頁面轉到郵箱界面(由於僅為模擬情況,實際操作其轉到百度首頁)
- 調用UserService、UserDao等請看後續
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("test/html;charset=utf-8");
request.setCharacterEncoding("utf-8");
//獲取前臺的數據
String name=null;
name=request.getParameter("name");
System.out.println(name);
String password=null;
password=request.getParameter("password");
//查詢數據庫中與name和password匹配的數量,不等於零代表正確
int num=0;
UserService uService=new UserServiceImpl();
num=uService.getUserByNameAndPwd(name,password);
if(num==0) {
System.out.println("密碼錯誤,請檢查賬號和密碼");
request.getRequestDispatcher("/EmailLogin.jsp").forward(request, response);
}else {
System.out.println("密碼正確,歡迎");
request.getRequestDispatcher("/EmailLogin.jsp").forward(request, response);
}
三、創建UserService接口及其實現類UserServiceImpl
四、創建UserDao接口及其實現類UserDaoImpl類
使用JDBC方法在User表中對比是否存在相應的用戶,返回int值給LoginTestServlet交給其判斷
public class UserDaoImpl implements UserDao{
@Override
public int getUserByNameAndPwd(String name, String password) {
// TODO Auto-generated method stub
//使用JDBC實現
int count=0;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection=DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/db1?useUnicode=true&characterEncoding=utf-8","root","123");
PreparedStatement pStatement=connection.prepareStatement("select count(*) from user where name=‘"+name+"‘"+"and password=‘"+password+"‘");
ResultSet rSet=pStatement.executeQuery();
while(rSet.next()) {count++;}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return count;
}
}
五、運行效果
密碼正確
用戶名和密碼正確,重定向到http://www.baidu.com
用servlet進行用戶名和密碼校驗