歡迎您光臨本站 註冊首頁

Struts 2.0整合Hibernate 3.2開發註冊登錄系統

←手機掃碼閱讀     火星人 @ 2014-03-10 , reply:0

開發工具:MyEclipse 6.0 ,Tomcat 5.5 ,JDK 1.5 ,MySQL 5.0 ;開發準備:下載Struts 2.0和Hibernate 3.2,大家可Struts和Hibernate的官方網站下載這兩個框架.我們先來總覽一下開發完成後的包—類圖:

NEW一個Web Project ,名為"LoginSystem" ,在 lib 目錄下加入Struts 2.0的Jar包和Hibernate 3.2的Jar包,然後按下面的步驟來:

1、在 src 目錄下建 "hibernate.cfg.xml" 全部代碼如下:

1<?xml version='1.0' encoding='UTF-8'?>
2<!DOCTYPE hibernate-configuration PUBLIC
3 "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
4 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
5
6<!-- Generated by MyEclipse Hibernate Tools. -->

7<hibernate-configuration>
8 <session-factory>
9 <property name="connection.username">root</property>
10 <property name="connection.url">
11 jdbc:mysql://localhost:3306/LoginSystem
12 </property>

13 <property name="dialect">
14 org.hibernate.dialect.MySQLDialect
15 </property>
16 <property name="myeclipse.connection.profile">
17 LoginSystem
18 </property>
19 <property name="connection.password">root</property>

20 <property name="connection.driver_class">
21 com.mysql.jdbc.Driver
22 </property>
23 <property name="show_sql">true</property>
24 <!-- POJO類映射配置 -->
25 <mapping resource="com/rong/ORM/User.hbm.xml" />

26 </session-factory>
27</hibernate-configuration>

2、建立實體類 "User.java" 及其映射文件 "User.hbm.xml" 兩者都放在 "com.rong.ORM" 包下.其中"User.java"的代碼如下:

1package com.rong.ORM;
2
3public class User {

4
5 private int id; //主鍵ID
6 private String name; //用戶名
7 private String pwd; //密碼
8
9 /*

10 * Getter方法與Setter方法
11 */

12 public String getName() {
13 return name;
14 }

15 public void setName(String name) {

16 this.name = name;
17 }

18 public String getPwd() {
19 return pwd;
20 }

21 public void setPwd(String pwd) {

22 this.pwd = pwd;
23 }

24 public int getId() {
25 return id;
26 }

27 public void setId(int id) {

28 this.id = id;
29 }

30}

User.hbm.xml的代碼如下:

1<?xml version="1.0" encoding="utf-8"?>
2<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
3"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
4
5<hibernate-mapping>

6 <class name="com.rong.ORM.User" table="tb_user">
7 <id name="id">
8 <generator class="native"/>
9 </id>
10 <property name="name" type="java.lang.String" length="20"/>

11 <property name="pwd" type="java.lang.String" length="20"/>
12 </class>
13</hibernate-mapping>

3、建立"ExportDB.java"工具類,我們執行如下代碼,就能輕鬆將User類導入資料庫轉變成資料庫中的表.不過,前提是我們已經在MySQL中建立了一個名為"LoginSystem"的資料庫.

1package tool;
2
3import org.hibernate.cfg.Configuration;

4import org.hibernate.tool.hbm2ddl.SchemaExport;
5
6public class ExportDB {
7
8 /*

9 * 運行此類,通過POJO類和配置文件,生成資料庫的表
10 */

11 public static void main(String[] args){
12 Configuration cfg = new Configuration().configure();
13 SchemaExport export = new SchemaExport(cfg);

14 export.create(true, true);
15 }

16}

17

4、建立獲取SessionFactory和管理Session的HibernateUtil.java類:

1package com.rong.hibernate;
2
3import org.hibernate.HibernateException;
4import org.hibernate.Session;
5import org.hibernate.SessionFactory;

6import org.hibernate.cfg.Configuration;
7
8public class HibernateUtil {
9
10 //聲明Hibernate配置文件所在的路徑
11 private static String configFile = "/hibernate.cfg.xml";

12 //建Configuration對象
13 private static Configuration configuration = new Configuration();
14 //建Session工廠對象
15 private static SessionFactory sessionFactory = null;
16
17 /**

18 * 單例模式,只初始化一次,只產生一個SessionFactory對象(線程安全)
19 */

20 static {
21 try{

22 //通過hibernate.cfg.xml配置資料庫連接
23 configuration.configure(configFile);
24 //建立一個Session工廠
25 sessionFactory = configuration.buildSessionFactory();
26 System.out.println("[標記]初始化SessionFactory");
27 }
catch(Exception e){

28 System.out.println("[異常]創建SessionFactory時發生異常,異常原因如下:");
29 e.printStackTrace();
30 }

31 }

32
33 /**
34 * getSession()方法
35 * @return Session對象

36 * @throws HibernateException
37 */

38 public Session getSession(){
39 Session session = null;
40 try{

41 session = sessionFactory.openSession();
42 }
catch(Exception e){
43 System.out.println("[異常]開啟Session時發生異常,異常原因如下:");
44 e.printStackTrace();
45 }

46 return session;

47 }

48
49 /**
50 * closeSession()方法
51 * @param session 要關閉的Session對象
52 */

53 public void closeSession(Session session){

54 try{
55 if(null != session)
56 session.close();
57 }
catch(Exception e){

58 System.out.println("[異常]關閉Session時發生異常,異常原因如下:");
59 e.printStackTrace();
60 }

61 }

62
63
64
66}

67

5、DAO層設計:在"com.rong.DAO" 包下建立兩個類,一個是介面,一個是實現類,其中UserDao.java代碼如下:

1package com.rong.DAO;

2
3import java.util.List;
4import com.rong.ORM.User;
5
6public interface UserDao {
7
8 /**

9 * 增加用戶
10 * @param user 要增加的用戶
11 */

12 public void add(User user);
13
14 /**
15 * 登錄驗證
16 * @param name

17 * @param password
18 * @return -1:不存在用戶名 ; -2:密碼不正確 ; >0:登錄成功(即返回該記錄ID)
19 */

20 public int isExist(String name,String password);
21}

UserDaoImpl.java的代碼如下

1package com.rong.DAO;
2
3import java.util.Iterator;

4import java.util.List;
5import org.hibernate.Query;
6import org.hibernate.Session;
7import org.hibernate.Transaction;
8import com.rong.ORM.User;
9import com.rong.hibernate.HibernateUtil;
10
11public class UserDaoImpl implements UserDao {

12
13 HibernateUtil util = new HibernateUtil();
14
15 /**
16 * 增加用戶
17 * @param user 要增加的用戶
18 */

19 public void add(User user){

20 Session session = util.getSession();
21 Transaction ts = null;
22 try{
23 ts = session.beginTransaction();
24 session.save(user);
25 ts.commit();
26 }
catch(Exception e){

27 System.out.println("UserDaoImpl.add()方法發生異常:");
28 e.printStackTrace();
29 }
finally{
30 util.closeSession(session);
31 }

32 }

33

34 /**
35 * 登錄驗證
36 * @param name
37 * @param password
38 * @return -1:不存在用戶名 ; -2:密碼不正確 ; >0:登錄成功(即返回該記錄ID)
39 */

40 public int isExist(String name,String password){

41 //int state = 0 ; //初始化狀態變數
42 Session session = util.getSession();
43 try{
44 Query query = session.createQuery("from User u where u.name = ?");
45 query.setString(0, name);

46 List list = query.list();
47 if(null == list || 0 == list.size()){
48 return -1 ; //用戶名不存在

49 }

50 Query query2 = session.createQuery("from User u where u.name = ? and u.pwd = ?");
51 query2.setString(0, name);
52 query2.setString(1, password);
53 List list2 = query.list();
54 if(null == list2){

55 return -2 ; //密碼不正確
56 }

57 Iterator it = list.iterator();
58 User user = (User)it.next();
59 return user.getId(); //驗證成功,取ID值
60
61 }
catch(Exception e){

62 System.out.println("UserDaoImpl.isExist()方法發生異常:");
63 e.printStackTrace();
64 return 0; //異常時返回0
65 }
finally{
66 util.closeSession(session);

67 }

68 }

69}

70

6、在web.xml中配置Struts 2.0支持:

1<?xml version="1.0" encoding="UTF-8"?>
2<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
6
7 <!-- 用過濾器配置Struts2支持 -->
8 <filter>
9 <filter-name>struts2</filter-name>
10 <filter-class>
11 org.apache.struts2.dispatcher.FilterDispatcher
12 </filter-class>

13 </filter>
14 <filter-mapping>
15 <filter-name>struts2</filter-name>
16 <url-pattern>/*</url-pattern>
17 </filter-mapping>
18
19 <welcome-file-list>

20 <welcome-file>login.jsp</welcome-file>
21 </welcome-file-list>
22</web-app>

7、登錄頁面login.jsp代碼如下:

1<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>

2<%@ taglib prefix="s" uri="/struts-tags" %>
3<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4<html>

5 <head>
6
7 <title>Login Page</title>
8 </head>
9
10 <body>
11 <p><a href="register.jsp">用戶註冊</a>|用戶登錄</p>

12 <s:form action="loginAction" theme="simple">
13 <table>
14 <tr>
15 <td style="text-align:right">
16 賬號
17 </td>
18 <td>

19 <s:textfield name="name" label="賬號" />
20
21 </td>
22 </tr>
23 <tr>
24 <td style="text-align:right">
25 密碼

26 </td>
27 <td>
28 <s:password name="pwd" label="密碼" />
29 </td>
30 </tr>
31 <tr>

32 <td style="text-align:right">
33 驗證碼
34 </td>
35 <td>
36 <s:textfield name="inputCertCode" label="驗證碼" cssStyle="width:100px"/>
37 <img src="other/makeCertPic.jsp">

38 </td>
39 </tr>
40 <tr>
41 <td style="text-align:right">
42 <s:submit value="登錄" />
43 </td>

44 <td style="text-align:left">
45 <s:reset value="取消"/>
46 </td>
47 </tr>
48 </table>
49 </s:form>

50 <s:fielderror cssStyle="color:red"/>
51 </body>
52</html>
53

註冊頁register.jsp代碼如下

1<%@ page language="java" import="java.util.*" pageEncoding="gbk"%>

2<%@ taglib prefix="s" uri="/struts-tags"%>
3<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
4<html>

5 <head>
6
7 <title>Register Page</title>
8 </head>
9
10 <body>
11 <p><a href="login.jsp">用戶登錄</a>|用戶註冊</p>

12 <s:form action="registerAction" theme="simple">
13 <table>
14 <tr>
15 <td style="text-align:right">
16 請輸入賬號
17 </td>
18 <td>

19 <s:textfield name="user.name" label="賬號" />
20
21 </td>
22 </tr>
23 <tr>
24 <td style="text-align:right">
25 請輸入密碼

26 </td>
27 <td>
28 <s:password name="user.pwd" label="密碼" />
29 </td>
30 </tr>
31 <tr>

32 <td style="text-align:right">
33 請再次輸入密碼
34 </td>
35 <td>
36 <s:password name="repwd" label="重複密碼" />
37 </td>

38 </tr>
39 <tr>
40 <td style="text-align:right">
41 請輸入驗證碼
42 </td>
43 <td>
44 <s:textfield name="inputCertCode" label="驗證碼" cssStyle="width:100px"/>

45 <img src="other/makeCertPic.jsp">
46 </td>
47 </tr>
48 <tr>
49 <td style="text-align:right">
50 <s:submit value="註冊" />

51 </td>
52 <td style="text-align:left">
53 <s:reset value="取消"/>
54 </td>
55 </tr>
56 </table>

57 </s:form>
58 <s:fielderror cssStyle="color:red"/>
59 </body>
60</html>
61

8、在JSP頁中所用到的驗證碼的生成頁面makeCertPic.jsp(我們把它放在WebRoot的other目錄下):

1<%@page contentType="image/jpeg" pageEncoding="gbk"%>

2<jsp:useBean id="image" scope="page" class="com.rong.other.makeCertPic" />
3<%
4 String str = image.getCertPic(0,0,response.getOutputStream());

5 // 將驗證碼保存到Session中
6 session.setAttribute("certCode", str);
7
%>

其中,它調用了名為makeCertPic的Bean ,這個類主要用來生成彩色的驗證圖片,其代碼如下:

1package com.rong.other;
2import java.awt.Color;
3import java.awt.Font;
4import java.awt.Graphics;

5import java.awt.image.BufferedImage;
6import java.io.IOException;
7import java.io.OutputStream;
8import java.util.Random;
9import javax.imageio.ImageIO;
10/**
11 * 生成驗證碼圖片

12 */

13public class makeCertPic {
14 //驗證碼圖片中可以出現的字符集,可根據需要修改
15 private char mapTable[]={

16 'a','b','c','d','e','f',
17 'g','h','i','j','k','l',

18 'm','n','o','p','q','r',
19 's','t','u','v','w','x',

20 'y','z','0','1','2','3',
21 '4','5','6','7','8','9'}
;

22 /**
23 * 功能:生成彩色驗證碼圖片
24 * 參數width為生成的圖片的寬度,參數height為生成的圖片的高度,參數os為頁面的輸出流
25 */

26 public String getCertPic(int width, int height, OutputStream os) {

27 if(width<=0)width=60;
28 if(height<=0)height=20;
29 BufferedImage image = new BufferedImage(width, height,
30 BufferedImage.TYPE_INT_RGB);
31 // 獲取圖形上下文
32 Graphics g = image.getGraphics();
33 // 設定背景色

34 g.setColor(new Color(0xDCDCDC));
35 g.fillRect(0, 0, width, height);
36 //畫邊框
37 g.setColor(Color.black);
38 g.drawRect(0,0,width-1,height-1);
39 // 取隨機產生的認證碼
40 String strEnsure = "";

41 // 4代表4位驗證碼,如果要生成更多位的認證碼,則加大數值
42 for(int i=0; i<4; i) {
43 strEnsure = mapTable[(int)(mapTable.length*Math.random())];

44 }

45 // 將認證碼顯示到圖象中,如果要生成更多位的認證碼,增加drawString語句
46 g.setColor(Color.black);
47 g.setFont(new Font("Atlantic Inline",Font.PLAIN,18));
48 String str = strEnsure.substring(0,1);
49 g.drawString(str,8,17);
50 str = strEnsure.substring(1,2);

51 g.drawString(str,20,15);
52 str = strEnsure.substring(2,3);
53 g.drawString(str,35,18);
54 str = strEnsure.substring(3,4);
55 g.drawString(str,45,15);
56 // 隨機產生10個干擾點
57 Random rand = new Random();

58 for (int i=0;i<10;i ) {
59 int x = rand.nextInt(width);
60 int y = rand.nextInt(height);
61 g.drawOval(x,y,1,1);

62 }

63 // 釋放圖形上下文
64 g.dispose();
65 try {
66 // 輸出圖象到頁面
67 ImageIO.write(image, "JPEG", os);

68 }
catch (IOException e) {
69 return "";
70 }

71 return strEnsure;
72 }

73}

74

9、此時,我們很有必要來配置一下struts.xml其全部代碼如下

1<?xml version="1.0" encoding="UTF-8" ?>
2<!DOCTYPE struts PUBLIC
3 "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
4 "http://struts.apache.org/dtds/struts-2.0.dtd">
5
6<struts>
7

8 <package name="com.rong.action" extends="struts-default">
9 <!-- 用戶登錄 -->
10 <action name="loginAction" class="com.rong.action.LoginAction">
11 <result name="success" type="redirect">/back/index.jsp</result>
12 <result name="input">/login.jsp</result>

13 </action>
14 <!-- 用戶註冊 -->
15 <action name="registerAction" class="com.rong.action.RegisterAction">
16 <result name="success" type="redirect">/login.jsp</result>
17 <result name="input">/register.jsp</result>

18 </action>
19 </package>
20</struts>

10、Action層設計:兩個非常關鍵的類,其中LoginAction.java的代碼如下:

1package com.rong.action;
2
3import java.util.Map;
4import com.opensymphony.xwork2.ActionContext;
5import com.opensymphony.xwork2.ActionSupport;

6import com.rong.DAO.UserDao;
7import com.rong.DAO.UserDaoImpl;
8import com.rong.ORM.User;
9
10public class LoginAction extends ActionSupport {
11

12
13 private UserDao userDao = new UserDaoImpl(); //操縱資料庫DAO類(Hibernate實現),通過Struts.xml注入值
14
15 private int id;
16 private String name; //用戶名(值由struts注入)
17 private String pwd; //密碼(值由struts注入)
18

19 private String inputCertCode; //驗證碼
20
21 public int getId() {
22 return id;
23 }

24 public void setId(int id) {

25 this.id = id;
26 }

27 public String getName() {
28 return name;
29 }

30 public void setName(String name) {

31 this.name = name;
32 }

33 public String getPwd() {
34 return pwd;
35 }

36 public void setPwd(String pwd) {

37 this.pwd = pwd;
38 }

39
40 public String getInputCertCode() {
41 return inputCertCode;
42 }

43 public void setInputCertCode(String inputCertCode) {

44 this.inputCertCode = inputCertCode;
45 }

46 @Override
47 public String execute() throws Exception {
48 int state = userDao.isExist(name,pwd);
49 System.out.println("state=" state);

50 if(state == -1){
51 this.addFieldError("name", "用戶名不正確,請先註冊!");
52 return INPUT;
53 }
else if(state == -2){

54 this.addFieldError("pwd", "密碼不正確,請重新輸入密碼!");
55 return INPUT;
56 }
else if(state > 0){
57 System.out.println("[測試]登錄成功!用戶ID=" state);

58 this.setId(state);
59 return SUCCESS;
60 }
else{
61 this.addFieldError("name", "登錄失敗,請與管理員聯繫!");
62 return INPUT;

63 }

64 }

65
66 public void validate() {
67 //驗證碼驗證
68 if(null == inputCertCode || "".equals(inputCertCode)){

69 this.addFieldError("inputCertCode", "驗證碼不能為空!");
70 }
else{
71 Map session = ActionContext.getContext().getSession();
72 String certCode = session.get("certCode").toString();

73 if( ! certCode.equals(this.inputCertCode)){
74 this.addFieldError("inputCertCode", "驗證碼不正確!");
75 }

76 }

77
78 }

79
80
81
82
83}

84

RegisterAction.java的代碼如下:

1package com.rong.action;
2
3import java.util.Map;

4
5import com.opensymphony.xwork2.ActionContext;
6import com.opensymphony.xwork2.ActionSupport;
7import com.rong.DAO.UserDao;
8import com.rong.DAO.UserDaoImpl;
9import com.rong.ORM.User;
10
11public class RegisterAction extends ActionSupport {

12
13 private UserDao userDao = new UserDaoImpl();
14
15 private User user; //註冊提交的用戶對象
16
17 private String repwd; //重複密碼
18
19 private String inputCertCode; //驗證碼

20
21 public User getUser() {
22 return user;
23 }

24
25 public void setUser(User user) {

26 this.user = user;
27 }

28
29 public String getRepwd() {
30 return repwd;
31 }

32

33 public void setRepwd(String repwd) {
34 this.repwd = repwd;
35 }

36
37 public String getInputCertCode() {

38 return inputCertCode;
39 }

40
41 public void setInputCertCode(String inputCertCode) {
42 this.inputCertCode = inputCertCode;
43 }

44
45 @Override
46 public String execute() throws Exception {
47 User user = new User();
48 userDao.add(user); //保存註冊的user對象
49 return SUCCESS;

50 }

51
52 @Override
53 public void validate() {
54 //驗證碼驗證
55 if(null == inputCertCode || "".equals(inputCertCode)){

56 this.addFieldError("inputCertCode", "驗證碼不能為空!");
57 }
else{
58 Map session = ActionContext.getContext().getSession();
59 String certCode = session.get("certCode").toString();

60 if( ! certCode.equals(this.inputCertCode)){
61 this.addFieldError("inputCertCode", "驗證碼不正確!");
62 }

63 }

64
65 }

66
67}

68

11、不要忘記配置校驗框架,與上面兩個Action同一個目錄下.LoginAction-validation.xml代碼如下:

1<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
2 "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
3
4<validators>

5 <!-- 用戶名驗證 -->
6 <field name="name">
7 <field-validator type="requiredstring">
8 <param name="trim">true</param>
9 <message>用戶名不能為空!</message>

10 </field-validator>
11 <field-validator type="regex">
12 <param name="expression"><![CDATA[(w{4,8})]]></param>
13 <message>賬號必須是長度為4-8的數字或字母!</message>
14 </field-validator>

15 </field>
16 <!-- 密碼驗證 -->
17 <field name="pwd">
18 <field-validator type="requiredstring">
19 <param name="trim">true</param>
20 <message>密碼不能為空!</message>

21 </field-validator>
22 <field-validator type="regex">
23 <param name="expression"><![CDATA[(w{4,8})]]></param>
24 <message>密碼必須長度為4-8的數字或字母!</message>
25 </field-validator>

26 </field>
27
28</validators>

RegisterAction-validation.xml代碼如下:

1<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN"
2 "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
3
4<validators>
5

6 <!-- 用戶名驗證 -->
7 <field name="user.name">
8 <field-validator type="requiredstring">
9 <param name="trim">true</param>
10 <message>用戶名不能為空!</message>

11 </field-validator>
12 <field-validator type="regex">
13 <param name="expression"><![CDATA[(w{4,8})]]></param>
14 <message>賬號必須是長度為4-8的數字或字母!</message>
15 </field-validator>

16 </field>
17
18 <!-- 密碼驗證 -->
19 <field name="user.pwd">
20 <field-validator type="requiredstring">
21 <param name="trim">true</param>

22 <message>密碼不能為空!</message>
23 </field-validator>
24 <field-validator type="regex">
25 <param name="expression"><![CDATA[(w{4,8})]]></param>
26 <message>密碼必須長度為4-8的數字或字母!</message>

27 </field-validator>
28 </field>
29
30 <field name="repwd">
31 <field-validator type="requiredstring" short-circuit="true">
32 <param name="trim">true</param>

33 <message>重複密碼不能為空!</message>
34 </field-validator>
35 <field-validator type="fieldexpression">
36 <param name="expression"><![CDATA[(repwd==user.pwd)]]></param>
37 <message>兩次輸入的密碼要一致!</message>

38 </field-validator>
39 </field>
40
41</validators>

到這裡,我們的項目也差不多完成了,大家自己也嘗試一下,開發出自己的J2EE系統.


[火星人 ] Struts 2.0整合Hibernate 3.2開發註冊登錄系統已經有627次圍觀

http://coctec.com/docs/java/show-post-61830.html