day13複習
功能分析
頁面及功能概述
JSP:
login.jsp 登錄頁面
regist.jsp 註冊頁面,服務器表單驗證,註冊成功添加跳轉到登錄的超鏈接,驗證碼
Servlet
RegistServlet
VerifyCodeServlet
Service
UserException 用戶異常
UserService 與用戶相關的業務類
VerifyCode 驗證碼類,個人編寫的,也可以使用itcast包中的驗證碼類
Dao:
JdbcUtils 數據庫連接工具類,單例模式
UserDao 與用戶相關的數據類
Domain:
User(對應數據庫,還要對應表單)
所導jar包
項目目錄結構
數據庫設計
略,選用SQLServer,UserDemo數據庫中Users(username,password)表
註冊流程圖
Domain層實現
user類
/*
* dao-與用戶相關的實體類
* 對應數據庫,還對應相應表單
*/
public class User {
private String username;
private String password;
private String verifyCode;
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;
}
public String getVerifyCode() {
return verifyCode;
}
public void setVerifyCode(String verifyCode) {
this.verifyCode = verifyCode;
}
public User() {
super();
}
public User(String username, String password, String verifyCode) {
super();
this.username = username;
this.password = password;
this.verifyCode = verifyCode;
}
@Override
public String toString() {
return "User [username=" + username + ", password=" + password + ", verifyCode=" + verifyCode + "]";
}
}
Dao層實現
JdbcUtils類
/*
* 連接SQLServer數據庫的工具類
* 單例模式
*/
public final class JdbcUtils {
private String url = "jdbc:sqlserver://127.0.0.1:1433;DatabaseName=UserDemo";
private String user = "sa";
private String password = "123456";
private JdbcUtils() {
super();
}
private static JdbcUtils instance = null;
//獲取實例
public static JdbcUtils getInstance() {
if(instance==null) {
synchronized (JdbcUtils.class) {//併發知識 加鎖
if(instance==null) {//雙重檢查
instance=new JdbcUtils();//延遲加載
}
}
}
return instance;
}
//靜態代碼段,實現註冊驅動
static {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
} catch (Exception e) {
// TODO: handle exception
throw new ExceptionInInitializerError(e);
}
}
//獲得連接
public Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
//釋放資源
public void free(ResultSet rs, PreparedStatement psmt, Connection con) {
try {
if(rs!=null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
psmt.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
UserDao類
/*
* 與用戶相關的數據類
*/
public class UserDao {
/*
* 根據用戶名查詢
* 1.調用JdbcUtils獲得連接
* 2.得到prepareStatement
* 3.對佔位符進行設值
* 4.得到結果並處理
* 5.釋放資源
*/
public User searchUser(String username) {
Connection con = null;
PreparedStatement psmt = null;
ResultSet rs = null;
String sql = "select * from users where username like ?";
JdbcUtils ju = JdbcUtils.getInstance();
try {
con = ju.getConnection();
psmt=con.prepareStatement(sql);
psmt.setString(1, username);
rs = psmt.executeQuery();
User u = new User();
while(rs.next()) {
u.setUsername(rs.getString(1));
u.setPassword(rs.getString(2));
}
return u;
} catch (SQLException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
} finally {
ju.free(rs, psmt, con);
}
}
/*
* 插入用戶
*/
public void addUser(User user) {
Connection con = null;
PreparedStatement psmt = null;
ResultSet rs = null;
JdbcUtils ju = JdbcUtils.getInstance();
String addSql = "insert into users values(?,?)";
try {
con = ju.getConnection();
psmt= con.prepareStatement(addSql);
psmt.setString(1, user.getUsername());
psmt.setString(2, user.getPassword());
psmt.execute();
System.out.println("插入成功");
} catch (Exception e) {
// TODO: handle exception
throw new RuntimeException(e);
} finally {
ju.free(rs, psmt, con);
}
}
}
Service層實現
UserException類
/*
* 用戶異常類
*/
public class UserException extends Exception {
public UserException() {
// TODO Auto-generated constructor stub
}
public UserException(String arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public UserException(Throwable arg0) {
super(arg0);
// TODO Auto-generated constructor stub
}
public UserException(String arg0, Throwable arg1) {
super(arg0, arg1);
// TODO Auto-generated constructor stub
}
}
UserService
public class UserService {
UserDao ud =new UserDao();
/*
* 註冊功能
* 使用用戶名去查詢,如果返回null,完成添加
* 如果返回不是空 拋出異常
*/
public void regist(User user) throws UserException {
User _user = ud.searchUser(user.getUsername());
if(_user.getUsername()!=null) throw new UserException("用戶名"+user.getUsername()+"已被註冊");
ud.addUser(user);
}
}
VerifyCode類
public class VerifyCode {
private int w = 70;
private int h = 35;
private Random r = new Random();
private String[] fontNames = {"宋體","華文楷體","微軟雅黑","楷體_GB2312"};
//可選字符,無1liI;
private String codes = "23456789abcdefghjkmnopqrstuvwxyzABCDEFGHJKLMNOPQRSTUVWXYZ";
//背景色
private Color bgColor = new Color(255,255,255);
//驗證碼上的文本
private String text;
//隨機獲得顏色
private Color randomColor() {
int R = r.nextInt(150);
int G = r.nextInt(150);
int B = r.nextInt(150);
return new Color(R,G,B);
}
//獲得隨機字體
private Font randomFont() {
int index = r.nextInt(fontNames.length);//隨機得到字體數組中的一個
String fontName = fontNames[index];
int style = r.nextInt(4);//生成隨機樣式:0(無樣式),1(粗體),2(斜體),3(粗體加斜體)
int size = r.nextInt(5)+24;//生成隨機字號,24~28
return new Font(fontName, style, size);
}
//畫干擾線
private void drawLine (BufferedImage image) {
int num = 3;//一共畫三條
Graphics2D g2 = (Graphics2D) image.getGraphics();
for (int i = 0; i < num; i++) {//生成兩個點的座標
int x1 = r.nextInt(w);
int y1 = r.nextInt(h);
int x2 = r.nextInt(w);
int y2 = r.nextInt(h);
g2.setStroke(new BasicStroke(1.5F));
g2.setColor(Color.BLUE);//藍色干擾線
g2.drawLine(x1, y1, x2, y2);//畫線
}
}
//隨機生成一個字符
private char randomChar() {
int index = r.nextInt(codes.length());
return codes.charAt(index);//獲取字符串的第index個字符
}
private BufferedImage createImg() {
BufferedImage image = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) image.getGraphics();
g2.setColor(this.bgColor);
g2.fillRect(0, 0, w, h);
return image;
}
//調用這個方法得到驗證碼
public BufferedImage getImg() {
BufferedImage image = createImg();//創建圖片緩衝區
Graphics2D g2 = (Graphics2D) image.getGraphics();//得到繪製環境
StringBuilder sb = new StringBuilder();//用來裝載生成的驗證碼文本
//向圖片中畫4個字符
for (int i = 0; i < 4; i++) {
String s =randomChar() + "";//隨機生成一個字母
sb.append(s);//把字母添加到sb中
float x = i*1.0F *w/4;//設置當前字符的x軸座標
g2.setFont(randomFont());//設置隨機字體
g2.setColor(randomColor());//設置隨機顏色
g2.drawString(s, x, h-5);//畫圖
}
this.text = sb.toString();//把生成的字符串賦給this.text
drawLine(image);//添加干擾線
return image;
}
//返回驗證碼圖片上的文本
public String getText() {
return text;
}
//保存圖片到指定的輸出流
public static void output(BufferedImage image, OutputStream out) throws IOException {
ImageIO.write(image,"JPEG",out);
}
}
Servlet層實現
VerifyCode類
@WebServlet("/VerifyCodeServlet")
public class VerifyCodeServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//生成圖片
//保存圖片上的文本到Session域中
//把圖片響應給客戶端
VerifyCode vc = new VerifyCode();
BufferedImage bi = vc.getImg();
VerifyCode.output(bi, response.getOutputStream());
request.getSession().setAttribute("session_code", vc.getText());
}
}
RegistServlet類
@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//處理編碼
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//依賴UserService
UserService us =new UserService();
/*
* 封裝表單數據到User對象中
*
*/
User form = CommonUtils.toBean(request.getParameterMap(), User.class);
/*
* 服務器端表單驗證
* 1.創建一個Map,用來裝載所有表單錯誤信息
* 2.在校驗過程中,如果失敗,向map添加錯誤信息,其中key爲表單字段名
* 3.校驗之後查看map長度是否大於0,如果大於零證明有錯誤信息,保存map到request中,
* 4.保存form到request中,轉發到regist.jsp中
* 5.如果map爲空,向下執行
*/
Map<String,String> errors = new HashMap<String,String>();
//用戶名格式校驗
String username = form.getUsername();//獲取表單中的username
if(username == null||username.trim().isEmpty()) {
errors.put("username", "用戶名不能爲空!");
}else if(username.length() < 3||username.length() > 15) {
errors.put("username", "用戶名長度必須在3~15之間!");
}
//密碼格式校驗
String password = form.getPassword();//獲取表單中的password
if(password == null||password.trim().isEmpty()) {
errors.put("password", "密碼不能爲空!");
}else if(password.length() < 3||password.length() > 15) {
errors.put("password", "密碼長度必須在3~15之間!");
}
//對驗證碼進行校驗
String sessionCode = (String)request.getSession().getAttribute("session_code");
String verifyCode = form.getVerifyCode();//獲取表單中的VerifyCode
if(verifyCode == null||verifyCode.trim().isEmpty()) {
errors.put("verifyCode", "驗證碼不能爲空!");
}else if(verifyCode.length() != 4) {
errors.put("verifyCode", "驗證碼長度必須爲4!");
}else if(verifyCode.equalsIgnoreCase(sessionCode) ) {
errors.put("verifyCode", "驗證碼錯誤!");
}
//判斷map是否爲空,不爲空說明有問題
if(errors != null && errors.size() > 0) {//健壯性
/*
* 1.保存errors到request域
* 2.保存form到request域,用於回顯
* 3.轉發到regist.jsp
*/
request.setAttribute("errors", errors);
request.setAttribute("user", form);
request.getRequestDispatcher("/user/regist.jsp").forward(request, response);
return;
}
/*
* 調用us的方法 傳遞form過去
* 得到異常:獲取異常信息,保存到request域中,轉發到regist.jsp中顯示
* 沒有異常:輸出註冊成功
*/
try {
us.regist(form);
response.getWriter().print("<h2>註冊成功!</h2> <a href='" +
request.getContextPath()+"/user/login.jsp" +
"'>點擊這裏去登陸</a>");
} catch (UserException e) {
//獲取異常信息保存到request域中,並且轉發到註冊頁面
request.setAttribute("msg", e.getMessage());
request.setAttribute("user", form);//用來在表單中回顯,EL表達式特點,沒有啥也不顯示,不是NULL
request.getRequestDispatcher("/user/regist.jsp").forward(request, response);
}
}
}
頁面代碼實現
regist.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function _change(){
/*
得到img元素
修改其src爲/LoginDemo/VerifyCodeServet
*/
var imgEle = document.getElementById("img");
imgEle.src = "${pageContext.request.contextPath }/VerifyCodeServlet?a="+new Date().getTime();//不加個時間會因爲瀏覽器緩存而更換失敗
}
</script>
</head>
<body>
<%--<c:url value='/RegistServlet'/> --%>
<%--${pageContext.request.contextPath }/RegistServlet --%>
<%
String message = " ";
String msg = (String)request.getAttribute("msg");
if(msg !=null){
message = msg;
}
%>
<h1>註冊</h1>
<font color="red"><b><%= message%></b></font>
<form method="post" action="${pageContext.request.contextPath }/RegistServlet">
用戶名:<input type="text" name="username" value="${user.username}"/>${errors.username }<br/>
密 碼:<input type="password" name="password" value="${user.password}"/>${errors.password }<br/>
驗證碼:<input type="text" name="verifyCode" size="3"/>
<img id="img" src="${pageContext.request.contextPath }/VerifyCodeServlet"/>
<a href="javascript:_change()">換一張</a>${errors.verifyCode }<br/>
<input type="submit" value="註冊" />
</form>
</body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%--${pageContext.request.contextPath }/LoginServlet --%>
<form method="post" action="<c:url value='/LoginServlet'/>">
用戶名:<input type="text" name="username"/><br/>
密 碼:<input type="password" name="password"/><br/>
<input type="button" value="登錄"/>
</form>
</body>
</html>