天天看點

java實作登入注冊案例_案例:使用者的注冊和登入功能

知識點

①MVC設計模式

②檔案上傳功能

③驗證碼的校驗

什麼是MVC?

java實作登入注冊案例_案例:使用者的注冊和登入功能

JavaWeb開發曆程

java實作登入注冊案例_案例:使用者的注冊和登入功能

案例實作

1)環境搭建

使用者注冊

- 使用者資訊的儲存

- 使用者頭像的上傳

java實作登入注冊案例_案例:使用者的注冊和登入功能

如果注冊成功會跳轉到登陸頁面

java實作登入注冊案例_案例:使用者的注冊和登入功能

建立一個工程

java實作登入注冊案例_案例:使用者的注冊和登入功能

将樣式,圖檔和頁面放到webcontent目錄下

java實作登入注冊案例_案例:使用者的注冊和登入功能

将需要用到的jar包放到lib目錄中

java實作登入注冊案例_案例:使用者的注冊和登入功能

将工程釋出到tomcat

java實作登入注冊案例_案例:使用者的注冊和登入功能

2)使用者清單初始化

這個案例将賬戶資料存放在了集合中放到servlet的全局域.

知識點:監聽器

java實作登入注冊案例_案例:使用者的注冊和登入功能

domain 實體類:User類

service 接口,用于處理業務邏輯

utils 工具類

listener 監聽器:初始化使用者資訊監聽器

servlet servlet類

User.java

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

1 packagecom.imooc.domain;2

3 public classUser {4 privateString username;5 privateString password;6

7 privateString path;8

9 publicString getUsername() {10 returnusername;11 }12

13 public voidsetUsername(String username) {14 this.username =username;15 }16

17 publicString getPassword() {18 returnpassword;19 }20

21 public voidsetPassword(String password) {22 this.password =password;23 }24

25 publicString getPath() {26 returnpath;27 }28

29 public voidsetPath(String path) {30 this.path =path;31 }32

33 @Override34 publicString toString() {35 return "User [username=" + username + ", password=" + password + ", path=" + path + "]";36 }37

38

39 }

View Code

監聽器

java實作登入注冊案例_案例:使用者的注冊和登入功能

3)注冊頁面的表單校驗

注冊頁面的form表單

java實作登入注冊案例_案例:使用者的注冊和登入功能

script标簽

java實作登入注冊案例_案例:使用者的注冊和登入功能

4)使用者資訊儲存

java實作登入注冊案例_案例:使用者的注冊和登入功能

form表單

java實作登入注冊案例_案例:使用者的注冊和登入功能

接口

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

注冊servlet

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

5)上傳檔案功能

java實作登入注冊案例_案例:使用者的注冊和登入功能

原理分析:

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

但這時接收到的請求參數隻有檔案名,沒有檔案

增加enctype屬性

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

原理:拿到請求後,對請求做一個相應的解析

fileload簡介:

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

UploadServlet

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

1 packagecom.imooc.servlet;2

3 importjava.io.FileOutputStream;4 importjava.io.IOException;5 importjava.io.InputStream;6 importjava.io.OutputStream;7 importjava.util.List;8

9 importjavax.servlet.ServletException;10 importjavax.servlet.annotation.WebServlet;11 importjavax.servlet.http.HttpServlet;12 importjavax.servlet.http.HttpServletRequest;13 importjavax.servlet.http.HttpServletResponse;14

15 importorg.apache.commons.fileupload.FileItem;16 importorg.apache.commons.fileupload.FileUploadException;17 importorg.apache.commons.fileupload.disk.DiskFileItemFactory;18 importorg.apache.commons.fileupload.servlet.ServletFileUpload;19

20 @WebServlet("/UploadServlet")21 public class UploadServlet extendsHttpServlet {22 private static final long serialVersionUID = 1L;23

24 protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {25

26 //1.建立磁盤檔案項工廠

27 DiskFileItemFactory diskFileItemFactory = newDiskFileItemFactory();28 //2.建立核心解析類

29 ServletFileUpload fileUpload = newServletFileUpload(diskFileItemFactory);30 //3.解析請求對象,将請求分成幾個部分(FileItem)

31 try{32 List list=fileUpload.parseRequest(request);33 //4.周遊集合獲得每個部分的對象

34 for(FileItem fileItem:list){35 //判斷是普通項還是檔案上傳項

36 if(fileItem.isFormField()){37 //普通項38 //獲得普通項的名稱:

39 String name =fileItem.getFieldName();40 //獲得普通項的值:

41 String value = fileItem.getString("UTF-8");42 System.out.println(name+" "+value);43 }else{44 //檔案上傳項45 //獲得檔案的名稱:

46 String fileName =fileItem.getName();47 //獲得檔案的輸入流:

48 InputStream is =fileItem.getInputStream();49 //需要将檔案寫入到伺服器的某個路徑即可:

50 String path = getServletContext().getRealPath("/upload");51 System.out.println(path);52 //建立輸出流 與 輸入流進行對接:

53 OutputStream os = new FileOutputStream(path+"\\"+fileName);54 int len = 0;55 byte[] b = new byte[1024];56 while((len = is.read(b))!=-1){57 os.write(b, 0, len);58 }59 is.close();60 os.close();61 }62 }63 } catch(FileUploadException e) {64 //TODO Auto-generated catch block

65 e.printStackTrace();66 }67

68 }69

70 protected void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {71 doGet(request, response);72 }73

74 }

View Code

6)使用者頭像上傳

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

1 packagecom.imooc.web.servlet;2

3 importjava.io.FileOutputStream;4 importjava.io.IOException;5 importjava.io.InputStream;6 importjava.io.OutputStream;7 importjava.util.HashMap;8 importjava.util.List;9 importjava.util.Map;10

11 importjavax.servlet.ServletException;12 importjavax.servlet.annotation.WebServlet;13 importjavax.servlet.http.HttpServlet;14 importjavax.servlet.http.HttpServletRequest;15 importjavax.servlet.http.HttpServletResponse;16

17 importorg.apache.commons.fileupload.FileItem;18 importorg.apache.commons.fileupload.FileUploadException;19 importorg.apache.commons.fileupload.disk.DiskFileItemFactory;20 importorg.apache.commons.fileupload.servlet.ServletFileUpload;21

22 importcom.imooc.domain.User;23 importcom.imooc.service.UserService;24 importcom.imooc.service.impl.UserServiceImpl;25 importcom.imooc.utils.UploadUtils;26

27 @WebServlet("/RegistServlet")28 public class RegistServlet extendsHttpServlet {29 private static final long serialVersionUID = 1L;30

31 protected voiddoGet(HttpServletRequest request, HttpServletResponse response)32 throwsServletException, IOException {33 //接收資料34 //建立Map集合用于儲存資料:

35 Map map = new HashMap();36 //檔案上傳的代碼:37 //1.建立磁盤檔案項工廠

38 DiskFileItemFactory diskFileItemFactory = newDiskFileItemFactory();39 //2.建立核心解析類

40 ServletFileUpload fileUpload = newServletFileUpload(diskFileItemFactory);41 //3.解析請求對象,将請求分成幾個部分(FileItem)

42 try{43 List list =fileUpload.parseRequest(request);44 //4.周遊集合獲得每個部分的對象

45 for(FileItem fileItem : list) {46 //判斷是普通項還是檔案上傳項

47 if(fileItem.isFormField()) {48 //普通項--使用者名(username--輸入的值) 密碼 确認密碼49 //獲得普通項的名稱:

50 String name =fileItem.getFieldName();51 //獲得普通項的值:

52 String value = fileItem.getString("UTF-8");53 //儲存資料:

54 map.put(name, value);55 } else{56 //檔案上傳項57 //獲得檔案的名稱:

58 String fileName =fileItem.getName();59 //獲得唯一檔案名:

60 String uuidFileName =UploadUtils.getUuidFileName(fileName);61 //獲得檔案的輸入流:

62 InputStream is =fileItem.getInputStream();63 //需要将檔案寫入到伺服器的某個路徑即可:

64 String path = getServletContext().getRealPath("/upload");65 System.out.println(path);//D:/xxx/ddd/66 //顯示圖檔

java實作登入注冊案例_案例:使用者的注冊和登入功能

67 //建立輸出流 與 輸入流進行對接:

68 String url = path + "\\" +uuidFileName;69 map.put("path", request.getContextPath()+"/upload/"+uuidFileName);70 OutputStream os = newFileOutputStream(url);71 int len = 0;72 byte[] b = new byte[1024];73 while ((len = is.read(b)) != -1) {74 os.write(b, 0, len);75 }76 is.close();77 os.close();78 }79 }80 } catch(FileUploadException e) {81 //TODO Auto-generated catch block

82 e.printStackTrace();83 }84

85 //封裝資料

86 User user = newUser();87 user.setUsername(map.get("username"));88 user.setPassword(map.get("password"));89

90 user.setPath(map.get("path"));91 System.out.println(user);92 //處理資料

93 UserService userService = newUserServiceImpl();94 //從ServletContext域中擷取使用者的集合即可

95 List userList = (List) getServletContext().getAttribute("userList");96 userService.regist(userList, user);97 System.out.println(userList);98 //顯示處理結果

99 response.sendRedirect(request.getContextPath() + "/login.jsp");100 }101

102 protected voiddoPost(HttpServletRequest request, HttpServletResponse response)103 throwsServletException, IOException {104 doGet(request, response);105 }106

107 }

View Code

7)解決檔案名重名問題

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

1 packagecom.imooc.utils;2

3 importjava.util.UUID;4

5 public classUploadUtils {6

7 public staticString getUuidFileName(String fileName){8 //解決檔案重名的問題:9 //a.jpg -- 獲得字尾名.jpg -- 生成一段随機字元串将a替換掉 xxdfwerw.jpg

10 int idx = fileName.lastIndexOf(".");11 String exName = fileName.substring(idx);//.jpg12 //生成随機字元串:

13 String uuidFileName = UUID.randomUUID().toString().replace("-", "")+exName;14

15 returnuuidFileName;16 }17

18 public static voidmain(String[] args) {19 System.out.println(UploadUtils.getUuidFileName("a.jpg"));20 }21 }

View Code

8)登入功能

使用者資訊查詢

java實作登入注冊案例_案例:使用者的注冊和登入功能

loginservlet

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

1 packagecom.imooc.web.servlet;2

3 importjava.io.IOException;4 importjava.util.List;5

6 importjavax.servlet.ServletException;7 importjavax.servlet.annotation.WebServlet;8 importjavax.servlet.http.HttpServlet;9 importjavax.servlet.http.HttpServletRequest;10 importjavax.servlet.http.HttpServletResponse;11

12 importcom.imooc.domain.User;13 importcom.imooc.service.UserService;14 importcom.imooc.service.impl.UserServiceImpl;15

16 @WebServlet("/LoginServlet")17 public class LoginServlet extendsHttpServlet {18 private static final long serialVersionUID = 1L;19

20 protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {21

22 //接收資料:

23 String username = request.getParameter("username");24 String password = request.getParameter("password");25 //封裝資料:

26 User user = newUser();27 user.setUsername(username);28 user.setPassword(password);29 //處理資料:完成登陸.

30 UserService userService = newUserServiceImpl();31 //獲得使用者清單的集合:

32 List userList = (List)getServletContext().getAttribute("userList");33 User existUser =userService.login(userList,user);34 //顯示結果:

35 if(existUser == null){36 //登入失敗

37 request.setAttribute("msg", "使用者名或密碼錯誤!");38 request.getRequestDispatcher("/login.jsp").forward(request, response);39 }else{40 //登入成功41 //将使用者資訊儲存:

42 request.getSession().setAttribute("existUser", existUser);43 response.sendRedirect(request.getContextPath()+"/index.jsp");44 }45 }46

47 protected void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {48 doGet(request, response);49 }50

51 }

View Code

接口實作類

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

1 packagecom.imooc.service.impl;2

3 importjava.util.List;4

5 importcom.imooc.domain.User;6 importcom.imooc.service.UserService;7

8 public class UserServiceImpl implementsUserService {9

10 @Override11 public void regist(ListuserList, User user) {12 //儲存使用者資訊:

13 userList.add(user);14 }15

16 @Override17 public User login(ListuserList, User user) {18

19 for(User existUser : userList) {20 if(existUser.getUsername().equals(user.getUsername()) &&existUser.getPassword().equals(user.getPassword())){21 returnexistUser;22 }23 }24

25 return null;26 }27

28 }

View Code

首頁頭部:設定登入成功和失敗的樣式

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

1

2

登入

3

注冊

4

5

6

7

java實作登入注冊案例_案例:使用者的注冊和登入功能

8

9

View Code

9)驗證碼的生成與校驗

概述

java實作登入注冊案例_案例:使用者的注冊和登入功能

生成

java實作登入注冊案例_案例:使用者的注冊和登入功能

驗證碼生成準備工作:

servlet

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

1 packagecom.imooc.web.servlet;2

3 importjava.awt.Color;4 importjava.awt.Font;5 importjava.awt.Graphics;6 importjava.awt.Graphics2D;7 importjava.awt.image.BufferedImage;8 importjava.io.IOException;9 importjava.util.Random;10

11 importjavax.imageio.ImageIO;12 importjavax.servlet.ServletException;13 importjavax.servlet.annotation.WebServlet;14 importjavax.servlet.http.HttpServlet;15 importjavax.servlet.http.HttpServletRequest;16 importjavax.servlet.http.HttpServletResponse;17

18 @WebServlet("/CheckImgServlet1")19 public class CheckImgServlet1 extendsHttpServlet {20 private static final long serialVersionUID = 1L;21

22 protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {23

24 }25

26 protected void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {27 doGet(request, response);28 }29

30 }

View Code

頁面

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

1

2 pageEncoding="UTF-8"%>

3

4

5

6

7

Insert title here

8

9

10

11 驗證碼:

java實作登入注冊案例_案例:使用者的注冊和登入功能

12

13

14

15

View Code

将記憶體中圖檔顯示到浏覽器

servlet

字母随機旋轉一定角度

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

1 packagecom.imooc.web.servlet;2

3 importjava.awt.Color;4 importjava.awt.Font;5 importjava.awt.Graphics;6 importjava.awt.Graphics2D;7 importjava.awt.image.BufferedImage;8 importjava.io.IOException;9 importjava.util.Random;10

11 importjavax.imageio.ImageIO;12 importjavax.servlet.ServletException;13 importjavax.servlet.annotation.WebServlet;14 importjavax.servlet.http.HttpServlet;15 importjavax.servlet.http.HttpServletRequest;16 importjavax.servlet.http.HttpServletResponse;17

18 @WebServlet("/CheckImgServlet1")19 public class CheckImgServlet1 extendsHttpServlet {20 private static final long serialVersionUID = 1L;21

22 protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {23 int width = 120;24 int height = 30;25 //步驟一:在記憶體中生成一張圖檔

26 BufferedImage bufferedImage = newBufferedImage(width,height,BufferedImage.TYPE_INT_RGB);27 //步驟二:操作該圖檔,設定背景色及繪制邊框

28 Graphics graphics =bufferedImage.getGraphics();29 //設定背景色

30 graphics.setColor(Color.YELLOW);31 graphics.fillRect(0, 0, width, height);32 //繪制邊框

33 graphics.setColor(Color.BLUE);34 graphics.drawRect(0, 0, width-1, height-1);35

36 //步驟三:生成随機的四個字母或數字,寫入到圖檔中

37 Graphics2D g2d =(Graphics2D)graphics;38 g2d.setColor(Color.BLACK);39 g2d.setFont(new Font("宋體",Font.BOLD,18));//a 4 3 r

40

41 String words = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";42 Random random = newRandom();43 int x = 10;44 for(int i=0;i<4;i++){45 int idx =random.nextInt(words.length());46 //獲得指定位置的字元

47 char ch =words.charAt(idx);48 //旋轉的角度 -30 到 30 之間

49 int jiaodu = random.nextInt(60) - 30;50 //将角度轉化成弧度:

51 double theta = jiaodu * Math.PI / 180;52 g2d.rotate(theta, x, 20);53 g2d.drawString(String.valueOf(ch), x, 20);54 g2d.rotate(-theta, x, 20);55

56 x+=30;57 }58 //步驟四:将記憶體中的圖檔,進行輸出

59 ImageIO.write(bufferedImage, "jpg", response.getOutputStream());60 }61

62 protected void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {63 doGet(request, response);64 }65

66 }

View Code

添加幹擾線以及設定字母随機顔色

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

1 packagecom.imooc.web.servlet;2

3 importjava.awt.Color;4 importjava.awt.Font;5 importjava.awt.Graphics;6 importjava.awt.Graphics2D;7 importjava.awt.image.BufferedImage;8 importjava.io.IOException;9 importjava.util.Random;10

11 importjavax.imageio.ImageIO;12 importjavax.servlet.ServletException;13 importjavax.servlet.annotation.WebServlet;14 importjavax.servlet.http.HttpServlet;15 importjavax.servlet.http.HttpServletRequest;16 importjavax.servlet.http.HttpServletResponse;17

18

21 @WebServlet("/CheckImgServlet")22 public class CheckImgServlet extendsHttpServlet {23

24 public voiddoGet(HttpServletRequest request, HttpServletResponse response)25 throwsServletException, IOException {26

27 int width = 120;28 int height = 30;29

30 //步驟一 繪制一張記憶體中圖檔

31 BufferedImage bufferedImage = newBufferedImage(width, height,32 BufferedImage.TYPE_INT_RGB);33

34 //步驟二 圖檔繪制背景顔色 ---通過繪圖對象

35 Graphics graphics = bufferedImage.getGraphics();//得到畫圖對象 --- 畫筆36 //繪制任何圖形之前 都必須指定一個顔色

37 graphics.setColor(getRandColor(200, 250));38 graphics.fillRect(0, 0, width, height);39

40 //步驟三 繪制邊框

41 graphics.setColor(Color.WHITE);42 graphics.drawRect(0, 0, width - 1, height - 1);43

44 //步驟四 四個随機數字

45 Graphics2D graphics2d =(Graphics2D) graphics;46 //設定輸出字型

47 graphics2d.setFont(new Font("宋體", Font.BOLD, 18));48

49 String words =

50 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";51 //String words = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1\u53e3\u653e\u513f\u5e38\u6c14\u4e94\u7b2c\u4f7f\u5199\u519b\u5427\u6587\u8fd0\u518d\u679c\u600e\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u6027\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6797\u505c\u606f\u53e5\u533a\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6";

52 Random random = new Random();//生成随機數53

54 //定義x坐标

55 int x = 10;56 for (int i = 0; i < 4; i++) {57 //随機顔色

58 graphics2d.setColor(new Color(20 + random.nextInt(110), 20 +random59 .nextInt(110), 20 + random.nextInt(110)));60 //旋轉 -30 --- 30度

61 int jiaodu = random.nextInt(60) - 30;62 //換算弧度

63 double theta = jiaodu * Math.PI / 180;64

65 //生成一個随機數字

66 int index = random.nextInt(words.length()); //生成随機數 0 到 length - 167 //獲得字母數字

68 char c =words.charAt(index);69

70 //将c 輸出到圖檔

71 graphics2d.rotate(theta, x, 20);72 graphics2d.drawString(String.valueOf(c), x, 20);73 graphics2d.rotate(-theta, x, 20);74 x += 30;75 }76

77 //步驟五 繪制幹擾線

78 graphics.setColor(getRandColor(160, 200));79 intx1;80 intx2;81 inty1;82 inty2;83 for (int i = 0; i < 30; i++) {84 x1 =random.nextInt(width);85 x2 = random.nextInt(12);86 y1 =random.nextInt(height);87 y2 = random.nextInt(12);88 graphics.drawLine(x1, y1, x1 + x2, x2 +y2);89 }90

91 //将上面圖檔輸出到浏覽器 ImageIO

92 graphics.dispose();//釋放資源

93 ImageIO.write(bufferedImage, "jpg", response.getOutputStream());94

95 }96

97

98 public voiddoPost(HttpServletRequest request, HttpServletResponse response)99 throwsServletException, IOException {100 doGet(request, response);101 }102

103

112 private Color getRandColor(int fc, intbc) {113 //取其随機顔色

114 Random random = newRandom();115 if (fc > 255) {116 fc = 255;117 }118 if (bc > 255) {119 bc = 255;120 }121 int r = fc + random.nextInt(bc -fc);122 int g = fc + random.nextInt(bc -fc);123 int b = fc + random.nextInt(bc -fc);124 return newColor(r, g, b);125 }126

127 }

View Code

實作驗證碼看不清更換一張的功能

頁面

浏覽器有緩存 要更換每次請求的路徑 才能實作點選更換圖檔

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

校驗

checkImgServlet

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

1 packagecom.imooc.web.servlet;2

3 importjava.awt.Color;4 importjava.awt.Font;5 importjava.awt.Graphics;6 importjava.awt.Graphics2D;7 importjava.awt.image.BufferedImage;8 importjava.io.IOException;9 importjava.util.Random;10

11 importjavax.imageio.ImageIO;12 importjavax.servlet.ServletException;13 importjavax.servlet.annotation.WebServlet;14 importjavax.servlet.http.HttpServlet;15 importjavax.servlet.http.HttpServletRequest;16 importjavax.servlet.http.HttpServletResponse;17

18

21 @WebServlet("/CheckImgServlet")22 public class CheckImgServlet extendsHttpServlet {23

24 public voiddoGet(HttpServletRequest request, HttpServletResponse response)25 throwsServletException, IOException {26

27 int width = 120;28 int height = 30;29

30 //步驟一 繪制一張記憶體中圖檔

31 BufferedImage bufferedImage = newBufferedImage(width, height,32 BufferedImage.TYPE_INT_RGB);33

34 //步驟二 圖檔繪制背景顔色 ---通過繪圖對象

35 Graphics graphics = bufferedImage.getGraphics();//得到畫圖對象 --- 畫筆36 //繪制任何圖形之前 都必須指定一個顔色

37 graphics.setColor(getRandColor(200, 250));38 graphics.fillRect(0, 0, width, height);39

40 //步驟三 繪制邊框

41 graphics.setColor(Color.WHITE);42 graphics.drawRect(0, 0, width - 1, height - 1);43

44 //步驟四 四個随機數字

45 Graphics2D graphics2d =(Graphics2D) graphics;46 //設定輸出字型

47 graphics2d.setFont(new Font("宋體", Font.BOLD, 18));48

49 String words =

50 "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";51 //String words = "\u7684\u4e00\u4e86\u662f\u6211\u4e0d\u5728\u4eba\u4eec\u6709\u6765\u4ed6\u8fd9\u4e0a\u7740\u4e2a\u5730\u5230\u5927\u91cc\u8bf4\u5c31\u53bb\u5b50\u5f97\u4e5f\u548c\u90a3\u8981\u4e0b\u770b\u5929\u65f6\u8fc7\u51fa\u5c0f\u4e48\u8d77\u4f60\u90fd\u628a\u597d\u8fd8\u591a\u6ca1\u4e3a\u53c8\u53ef\u5bb6\u5b66\u53ea\u4ee5\u4e3b\u4f1a\u6837\u5e74\u60f3\u751f\u540c\u8001\u4e2d\u5341\u4ece\u81ea\u9762\u524d\u5934\u9053\u5b83\u540e\u7136\u8d70\u5f88\u50cf\u89c1\u4e24\u7528\u5979\u56fd\u52a8\u8fdb\u6210\u56de\u4ec0\u8fb9\u4f5c\u5bf9\u5f00\u800c\u5df1\u4e9b\u73b0\u5c71\u6c11\u5019\u7ecf\u53d1\u5de5\u5411\u4e8b\u547d\u7ed9\u957f\u6c34\u51e0\u4e49\u4e09\u58f0\u4e8e\u9ad8\u624b\u77e5\u7406\u773c\u5fd7\u70b9\u5fc3\u6218\u4e8c\u95ee\u4f46\u8eab\u65b9\u5b9e\u5403\u505a\u53eb\u5f53\u4f4f\u542c\u9769\u6253\u5462\u771f\u5168\u624d\u56db\u5df2\u6240\u654c\u4e4b\u6700\u5149\u4ea7\u60c5\u8def\u5206\u603b\u6761\u767d\u8bdd\u4e1c\u5e2d\u6b21\u4eb2\u5982\u88ab\u82b1\u53e3\u653e\u513f\u5e38\u6c14\u4e94\u7b2c\u4f7f\u5199\u519b\u5427\u6587\u8fd0\u518d\u679c\u600e\u5b9a\u8bb8\u5feb\u660e\u884c\u56e0\u522b\u98de\u5916\u6811\u7269\u6d3b\u90e8\u95e8\u65e0\u5f80\u8239\u671b\u65b0\u5e26\u961f\u5148\u529b\u5b8c\u5374\u7ad9\u4ee3\u5458\u673a\u66f4\u4e5d\u60a8\u6bcf\u98ce\u7ea7\u8ddf\u7b11\u554a\u5b69\u4e07\u5c11\u76f4\u610f\u591c\u6bd4\u9636\u8fde\u8f66\u91cd\u4fbf\u6597\u9a6c\u54ea\u5316\u592a\u6307\u53d8\u793e\u4f3c\u58eb\u8005\u5e72\u77f3\u6ee1\u65e5\u51b3\u767e\u539f\u62ff\u7fa4\u7a76\u5404\u516d\u672c\u601d\u89e3\u7acb\u6cb3\u6751\u516b\u96be\u65e9\u8bba\u5417\u6839\u5171\u8ba9\u76f8\u7814\u4eca\u5176\u4e66\u5750\u63a5\u5e94\u5173\u4fe1\u89c9\u6b65\u53cd\u5904\u8bb0\u5c06\u5343\u627e\u4e89\u9886\u6216\u5e08\u7ed3\u5757\u8dd1\u8c01\u8349\u8d8a\u5b57\u52a0\u811a\u7d27\u7231\u7b49\u4e60\u9635\u6015\u6708\u9752\u534a\u706b\u6cd5\u9898\u5efa\u8d76\u4f4d\u5531\u6d77\u4e03\u5973\u4efb\u4ef6\u611f\u51c6\u5f20\u56e2\u5c4b\u79bb\u8272\u8138\u7247\u79d1\u5012\u775b\u5229\u4e16\u521a\u4e14\u7531\u9001\u5207\u661f\u5bfc\u665a\u8868\u591f\u6574\u8ba4\u54cd\u96ea\u6d41\u672a\u573a\u8be5\u5e76\u5e95\u6df1\u523b\u5e73\u4f1f\u5fd9\u63d0\u786e\u8fd1\u4eae\u8f7b\u8bb2\u519c\u53e4\u9ed1\u544a\u754c\u62c9\u540d\u5440\u571f\u6e05\u9633\u7167\u529e\u53f2\u6539\u5386\u8f6c\u753b\u9020\u5634\u6b64\u6cbb\u5317\u5fc5\u670d\u96e8\u7a7f\u5185\u8bc6\u9a8c\u4f20\u4e1a\u83dc\u722c\u7761\u5174\u5f62\u91cf\u54b1\u89c2\u82e6\u4f53\u4f17\u901a\u51b2\u5408\u7834\u53cb\u5ea6\u672f\u996d\u516c\u65c1\u623f\u6781\u5357\u67aa\u8bfb\u6c99\u5c81\u7ebf\u91ce\u575a\u7a7a\u6536\u7b97\u81f3\u653f\u57ce\u52b3\u843d\u94b1\u7279\u56f4\u5f1f\u80dc\u6559\u70ed\u5c55\u5305\u6b4c\u7c7b\u6e10\u5f3a\u6570\u4e61\u547c\u6027\u97f3\u7b54\u54e5\u9645\u65e7\u795e\u5ea7\u7ae0\u5e2e\u5566\u53d7\u7cfb\u4ee4\u8df3\u975e\u4f55\u725b\u53d6\u5165\u5cb8\u6562\u6389\u5ffd\u79cd\u88c5\u9876\u6025\u6797\u505c\u606f\u53e5\u533a\u8863\u822c\u62a5\u53f6\u538b\u6162\u53d4\u80cc\u7ec6";

52 Random random = new Random();//生成随機數53 //定義一個字元串,用于儲存随機産生的四個字母或數字

54 StringBuffer sb = newStringBuffer();55 //定義x坐标

56 int x = 10;57 for (int i = 0; i < 4; i++) {58 //随機顔色

59 graphics2d.setColor(new Color(20 + random.nextInt(110), 20 +random60 .nextInt(110), 20 + random.nextInt(110)));61 //旋轉 -30 --- 30度

62 int jiaodu = random.nextInt(60) - 30;63 //換算弧度

64 double theta = jiaodu * Math.PI / 180;65

66 //生成一個随機數字

67 int index = random.nextInt(words.length()); //生成随機數 0 到 length - 168 //獲得字母數字

69 char c =words.charAt(index);70 //将産生字元存入到StringBuffer中

71 sb.append(c);72 //将c 輸出到圖檔

73 graphics2d.rotate(theta, x, 20);74 graphics2d.drawString(String.valueOf(c), x, 20);75 graphics2d.rotate(-theta, x, 20);76 x += 30;77 }78 //将産生的字元串存入到session中:

79 request.getSession().setAttribute("checkCode", sb.toString());80

81 //步驟五 繪制幹擾線

82 graphics.setColor(getRandColor(160, 200));83 intx1;84 intx2;85 inty1;86 inty2;87 for (int i = 0; i < 30; i++) {88 x1 =random.nextInt(width);89 x2 = random.nextInt(12);90 y1 =random.nextInt(height);91 y2 = random.nextInt(12);92 graphics.drawLine(x1, y1, x1 + x2, x2 +y2);93 }94

95 //将上面圖檔輸出到浏覽器 ImageIO

96 graphics.dispose();//釋放資源

97 ImageIO.write(bufferedImage, "jpg", response.getOutputStream());98

99 }100

101

102 public voiddoPost(HttpServletRequest request, HttpServletResponse response)103 throwsServletException, IOException {104 doGet(request, response);105 }106

107

116 private Color getRandColor(int fc, intbc) {117 //取其随機顔色

118 Random random = newRandom();119 if (fc > 255) {120 fc = 255;121 }122 if (bc > 255) {123 bc = 255;124 }125 int r = fc + random.nextInt(bc -fc);126 int g = fc + random.nextInt(bc -fc);127 int b = fc + random.nextInt(bc -fc);128 return newColor(r, g, b);129 }130

131 }

View Code

loginServlet

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

1 packagecom.imooc.web.servlet;2

3 importjava.io.IOException;4 importjava.util.List;5

6 importjavax.servlet.ServletException;7 importjavax.servlet.annotation.WebServlet;8 importjavax.servlet.http.HttpServlet;9 importjavax.servlet.http.HttpServletRequest;10 importjavax.servlet.http.HttpServletResponse;11

12 importcom.imooc.domain.User;13 importcom.imooc.service.UserService;14 importcom.imooc.service.impl.UserServiceImpl;15

16 @WebServlet("/LoginServlet")17 public class LoginServlet extendsHttpServlet {18 private static final long serialVersionUID = 1L;19

20 protected void doGet(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {21 //完成驗證碼的校驗:22 //獲得session中儲存的驗證碼的資訊

23 String code1 = (String)request.getSession().getAttribute("checkCode");24 //接收前台表單送出的驗證碼的資訊

25 String code2 = request.getParameter("checkCode");26 if(code2==null || !code2.equalsIgnoreCase(code1)){27 request.setAttribute("msg", "驗證碼輸入不正确!");28 request.getRequestDispatcher("/login.jsp").forward(request, response);29 return;30 }31

32 //接收資料:

33 String username = request.getParameter("username");34 String password = request.getParameter("password");35 //封裝資料:

36 User user = newUser();37 user.setUsername(username);38 user.setPassword(password);39 //處理資料:完成登陸.

40 UserService userService = newUserServiceImpl();41 //獲得使用者清單的集合:

42 List userList = (List)getServletContext().getAttribute("userList");43 User existUser =userService.login(userList,user);44 //顯示結果:

45 if(existUser == null){46 //登入失敗

47 request.setAttribute("msg", "使用者名或密碼錯誤!");48 request.getRequestDispatcher("/login.jsp").forward(request, response);49 }else{50 //登入成功51 //将使用者資訊儲存:

52 request.getSession().setAttribute("existUser", existUser);53 response.sendRedirect(request.getContextPath()+"/index.jsp");54 }55 }56

57 protected void doPost(HttpServletRequest request, HttpServletResponse response) throwsServletException, IOException {58 doGet(request, response);59 }60

61 }

View Code

Kaptcha驗證碼的介紹及入門

上面我們自己編寫的驗證碼代碼有一定的局限性,當驗證碼的樣式,比如寬高等需要改變時,得更改相應的源代碼,不是很友善

這時我們可以用第三方的驗證碼工具,如Kaptcha

首先我們要将Kaptcha的jar包引入到工程中

然後在web.xml中進行相應的配置

java實作登入注冊案例_案例:使用者的注冊和登入功能
java實作登入注冊案例_案例:使用者的注冊和登入功能

1 <?xml version="1.0" encoding="UTF-8"?>

2

3

4

5 KaptchaServlet

6 com.google.code.kaptcha.servlet.KaptchaServlet

7

8

9

10 kaptcha.textproducer.char.length

11 4

12

13

14

15

16 kaptcha.textproducer.font.size

17 25

18

19

20 kaptcha.textproducer.char.space

21 10

22

23

24

25

26 kaptcha.image.width

27 120

28

29

30 kaptcha.image.height

31 30

32

33

34

35

36 KaptchaServlet

37 /KaptchaServlet

38

39

40

41

42 index.html

43 index.htm

44 index.jsp

45 default.html

46 default.htm

47 default.jsp

48

49

View Code

配置參數介紹

配置前

java實作登入注冊案例_案例:使用者的注冊和登入功能

配置後

java實作登入注冊案例_案例:使用者的注冊和登入功能

Kaptcha驗證碼的校驗

1 //獲得session中儲存的驗證碼的資訊

2 String code1 =(String)request.getSession().getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);3