首先是用戶需求:
1.輸入用戶名密碼驗證碼
2.登錄成功跳轉success.jsp,展示username,歡迎您
3.登錄失敗跳轉回登錄頁面
*如賬號或密碼錯誤,提示賬號或密碼錯誤
*如驗證碼錯誤,提示驗證碼錯誤
程序編寫流程:
1.編寫login.html登錄頁面
username & password & 驗證碼輸入 三個輸入框
2.編寫驗證碼的servlet,可以參考我4月20日編寫的《隨機驗證碼生成》
3.編寫LoginServlet,含有獲取驗證碼、用戶封裝、判斷用戶名密碼驗證碼是否一致
*先不調用數據庫,直接拿輸出數據與字符判斷,如成功,在進行連接調用數據庫判斷
4.若程序運行成功,使用Druid數據庫連接池技術,操作mysql,
5.使用JDBCTemplate技術封裝JDBC
6.編寫操作數據表中User表的Uerdao類
7.改寫剛剛為了方便,進行賬號密碼直接判斷的程序,調用Uerdao類進行判斷
8.輸入用戶名密碼驗證碼
9.登錄成功跳轉success.jsp,展示username,歡迎您
10.登錄失敗跳轉回登錄頁面
*如賬號或密碼錯誤,提示賬號或密碼錯誤
*如驗證碼錯誤,提示驗證碼錯誤
首先是login.jsp頁面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>login</title>
<script>
window.onload = function(){
document.getElementById("img").onclick = function(){
this.src="/day16_loginTest/checkCodeServlet?time="+new Date().getTime();
}
}
</script>
<style>
div{
color: red;
}
</style>
</head>
<body>
<form action="/day16_loginTest/loginServlet" method="post">
<table>
<tr>
<td>用戶名</td>
<td><input type="text" name="username"></td>
</tr>
<tr>
<td>密碼</td>
<td><input type="password" name="password"></td>
</tr>
<tr>
<td>驗證碼</td>
<td><input type="text" name="checkCode"></td>
</tr>
<tr>
<td colspan="2"><img id="img" src="/day16_loginTest/checkCodeServlet"></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="登錄"></td>
</tr>
</table>
</form>
<div><%=request.getAttribute("cc_error") == null ? "" : request.getAttribute("cc_error")%></div>
<div><%=request.getAttribute("login_error") == null ? "" : request.getAttribute("login_error") %></div>
</body>
</html>
然后是編寫的驗證碼的servlet,需要注意的是需要將隨機生成的驗證碼字符存入session,與輸入的進行判斷
package cn.stormtides.servlet;
import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;
@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int width = 100;
int height = 50;
//1.創建一對象,在內存中圖片(驗證碼圖片對象)
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
//2.美化圖片
//2.1 填充背景色
Graphics g = image.getGraphics();//畫筆對象
g.setColor(Color.PINK);//設置畫筆顏色
g.fillRect(0,0,width,height);
//2.2畫邊框
g.setColor(Color.BLUE);
g.drawRect(0,0,width - 1,height - 1);
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789";
//生成隨機角標
Random ran = new Random();
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 4; i++) {
int index = ran.nextInt(str.length());
//獲取字符
char ch = str.charAt(index);//隨機字符
sb.append(ch);
//2.3寫驗證碼
g.drawString(ch+"",width/5*i,height/2);
}
String checkCode_session = sb.toString();
//將驗證碼存入session
request.getSession().setAttribute("checkCode_session",checkCode_session);
//2.4畫干擾線
g.setColor(Color.GREEN);
//隨機生成坐標點
for (int i = 0; i < 10; i++) {
int x1 = ran.nextInt(width);
int x2 = ran.nextInt(width);
int y1 = ran.nextInt(height);
int y2 = ran.nextInt(height);
g.drawLine(x1,y1,x2,y2);
}
//3.將圖片輸出到頁面展示
ImageIO.write(image,"jpg",response.getOutputStream());
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
然后為最主要的loginServlet.java,因為沒有調用數據庫,就直接和字符:"zhangsan","123"比較,在運行成功后對調用數據庫進行判斷
package cn.stormtides.servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
//獲取參數名稱獲取參數值
String username = request.getParameter("username");
String password = request.getParameter("password");
String checkCode = request.getParameter("checkCode");
//獲取生成的驗證碼
HttpSession session = request.getSession();
String checkCode_session = (String) session.getAttribute("checkCode_session");
//刪除session中存儲的驗證碼
session.removeAttribute("checkCode_session");
//忽略大小寫比較驗證碼
if (checkCode_session.equalsIgnoreCase(checkCode)){
//驗證碼正確
if ("zhangsan".equals(username)&&"123".equals(password)){
//登陸成功
//存儲信息,用戶信息
session.setAttribute("user",username);
//重定向到success.jsp
response.sendRedirect(request.getContextPath()+"/success.jsp");
}else{
//登錄失敗
//存儲提示信息到request
request.setAttribute("login_error","用戶名或密碼錯誤");
//轉發到登錄頁面
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}else {
//驗證碼錯誤
request.setAttribute("cc_error","驗證碼錯誤");
request.getRequestDispatcher("/login.jsp").forward(request,response);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);
}
}
在運行成功后,進行數據庫的有關操作
首先在數據庫中創建User表,
CREATE TABLE USER(
id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(32) UNIQUE NULL,
PASSWORD VARCHAR(32) NOT NULL
);
INSERT INTO USER(username,PASSWORD)VALUES
('superbaby','123');
首先創建用戶實體類User.java
package cn.stormtides.domain;
//用戶實體類
public class User {
private int id;
private String username;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
再進行編寫操作數據表中User表的類,依賴於Druid連接池與Template
package cn.stormtides.dao;
import cn.stormtides.domain.User;
import cn.stormtides.util.JDBCUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
/**
* 操作數據表中User表的類
*/
public class UserDao {
private JdbcTemplate template=new JdbcTemplate(JDBCUtils.getDataSource());
/**
* 登錄方法
* @param loginUser
* @return user
*/
public User login(User loginUser){
try{
//編寫sql
String sql="select * from user where username= ? and password=?";
//調用query方法
User user = template.queryForObject(sql,
new BeanPropertyRowMapper<User>(User.class),
loginUser.getUsername(), loginUser.getPassword());
return user;
}catch (DataAccessException e){
e.printStackTrace();
return null;
}
}
}
編寫JDBC工具類,使用Druid連接池
package cn.stormtides.util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class JDBCUtils {
private static DataSource ds;
static {
try {
//加載配置文件
Properties pro=new Properties();
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");
pro.load(is);
//初始化連接池對象
ds = DruidDataSourceFactory.createDataSource(pro);
}catch (IOException e){
e.printStackTrace();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 獲取連接池對象
*/
public static DataSource getDataSource(){
return ds;
}
/**
* 獲取連接Connection對象
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
}
配置文件
driverClassName=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/day14 username=root password=root initialSize=5 maxAction=10 maxWait=3000
最后改動LoginServlet.java文件調用頁面輸入的賬號密碼驗證碼與數據庫中的中的比較,就可以了
程序的原始代碼https://github.com/StormTides/reference/tree/master/day16_loginTest
