天天看點

Struts2和hibernate3的簡單應用-登入驗證

先附上整體的結構吧

Struts2和hibernate3的簡單應用-登入驗證

Struts版本是hibernate-distribution-3.6.10.Final

hibernate版本是struts-2.3.24.1-all

一首先是導入jar包

Struts2和hibernate3的簡單應用-登入驗證

這裡要說明的是我使用Struts和hibernate的包貌似有沖突,是以把cg-lib.jar換成了cglib-nodep-2.13.jar.

二然後是Struts配置

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    xmlns="http://java.sun.com/xml/ns/javaee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
  <display-name></display-name> 
  //第一個顯示的頁面
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  //struts2的過濾器
  //struts2可以為任何自定義字元串,單要和過濾映射器同名
  <!-- 定義Filter -->
  <filter>
    <!-- Filter的名字 -->
    <filter-name>struts2</filter-name>
    <!-- Filter的實作類 -->
    <filter-class>
        org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
    </filter-class>
  </filter>
  //過濾映射器
  <filter-mapping>
    <!-- Filter的名字 -->
    <filter-name>struts2</filter-name>
    <!-- Filter負責攔截的URL中*.action的請求,如果<url-pattern>/* </>,全部以/的請求-->
    <url-pattern>*.action</url-pattern>
  </filter-mapping></web-app>
           

Struts.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
    //包名:user,繼承自struts-default;需要通路http://localhost:8080/ForTest/User/Login.action
    <package name="user" namespace="/User" extends="struts-default">
        <action name="Login">
            <result>/login.jsp</result>
        </action>
        //action name是**Welcome**,class是該action對應的類
        <action name="Welcome" class="com.bit.edu.cn.WelcomeUserAction">
            <result name="SUCCESS">/welcome_user.jsp</result>
            <result name="ERROR">/error.jsp</result>
        </action>
    </package>
</struts> 
           

WelcomeUserAction.java:

package com.bit.edu.cn;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.opensymphony.xwork2.ActionSupport;

public class WelcomeUserAction extends ActionSupport{
    private String username;
    private String password;

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    //Action Welcome會執行execute()方法
    public String execute() {
//      WelcomeUserAction action = new WelcomeUserAction();
        List<User> sList = queryResult(username, password);

        System.out.println(username+"  "+password);

        if(sList.size()>){
            return "SUCCESS";
        }
        return "ERROR";

    }


    public List<User> queryResult(String name, String pass){

        Session session = HibernateUtil.currentSession();
        Transaction ts = session.beginTransaction();

        List<User> result = session.createQuery("from User where username='"+name+"' and password="+pass).list();

        return result;
    }

}
           

四個JSP頁面

index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
  </head>

  <body>
    This is my JSP page. <br>
    //登入頁面連結
    <a href="http://localhost:8080/ForTest/User/Login.action">Login</a> <br>
  </body>
</html>
           

login.jsp:

<%@ page contentType="text/html; charset=UTF-8"%>
//導入Struts标簽
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head></head>
<body>
    <h1>Login Page</h1>
    //struts-form 标簽
    <s:form action="Welcome">
        <s:textfield name="username" label="Username" />
        <s:password name="password" label="Password" />
        <s:submit />
    </s:form>

</body>
</html>
           

welcome_user.jsp:

<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head></head>
<body>
    <h1>Login Success Page</h1>

    <h2>
        Hello
        <s:property value="username" />
    </h2>

</body>
</html>
           

error.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">


    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css" target="_blank" rel="external nofollow" >
    -->

  </head>

  <body>
    Error Page <br>
  </body>
</html>
           

三hibernate配置

先把資料庫貼上來吧:

資料庫用的是MySQL,database的名字是hibernate。

Struts2和hibernate3的簡單應用-登入驗證

建立資料庫:

/*
Navicat MySQL Data Transfer
Source Host     : localhost:3306
Source Database : hibernate
Target Host     : localhost:3306
Target Database : hibernate
Date: 2016-01-03 20:11:37
*/

SET FOREIGN_KEY_CHECKS=;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int() NOT NULL AUTO_INCREMENT,
  `username` varchar() DEFAULT NULL,
  `password` varchar() DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT= DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('1', 'heheda', '123');
INSERT INTO `user` VALUES ('2', 'dacaibi', '1234');
INSERT INTO `user` VALUES ('3', 'xyd', '1234');
           

hibernate.cfg.xml(hibernate配置檔案):

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost/hibernate</property>
    <property name="connection.username">root</property>
    <property name="connection.password">2334145</property>
    <!-- JDBC connection pool (use the built-in) -->
    <!-- <property name="connection.pool_size">1</property> -->
    <!-- SQL dialect -->
    //方言設定
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <!-- Echo all executed SQL to stdout -->
    //顯示sql語句
    <property name="show_sql">true</property>
    <!-- Enable Hibernate's automatic session context management -->
    <!--<property name="current_session_context_class">thread</property>-->
    <!-- Drop and re-create the database schema on startup -->
    <!-- <property name="hbm2ddl.auto">create</property> -->
    <!-- Disable the second-level cache -->
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    //映射配置檔案
    <mapping resource="com/bit/edu/cn/User.hbm.xml"/>
    </session-factory>
</hibernate-configuration>
           

User.hbm.xml(映射配置檔案):

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.bit.edu.cn">
    <class name="User">
        <id name="id">
        //Native主鍵生成方式會根據不同的底層資料庫自動選擇Identity、Sequence、Hilo主鍵生成方式  
            <generator class="native"></generator>
        </id>
        <property name="username"></property>
        <property name="password"></property>
    </class>
</hibernate-mapping>
           

User.java:

package com.bit.edu.cn;

public class User {

    private int id;
    private String username;
    private String password;

    public int getId() {
        return id;
    }

    public String getPassword() {
        return password;
    }

    public String getUsername() {
        return username;
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setUsername(String username) {
        this.username = username;
    }

}
           

HibernateUtil.java:

package com.bit.edu.cn;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.hql.ast.SqlASTFactory;

public class HibernateUtil {

    public static SessionFactory sessionFactory ;

    static{
        try {
            //hibernate初始化
            sessionFactory = new Configuration().configure().buildSessionFactory();
        } catch (Exception e) {
            System.err.print("Create SessionFactory Failed!");
            e.printStackTrace();
        }
    }

    public static ThreadLocal session = new ThreadLocal();

    public static Session currentSession()throws HibernateException {

        Session s = (Session) session.get();
        if(s==null){
            s = sessionFactory.openSession();
            session.set(s);
        }
        return s;
    }

    public static void  closeSession()throws HibernateException{
        Session s = (Session) session.get();
        if(s!=null){
            s.close();
        }
        session.set(null);
    }
}
           

ReadInfoUser.java(測試連接配接):

package com.bit.edu.cn;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class ReadInfoUser {
    public static void main(String[] args){

        ReadInfoUser rUser = new ReadInfoUser();

        List<User> list = rUser.getList();

        for(int i=;i<list.size();i++){
            System.out.println(list.get(i).getId());
        }

    }

    private List<User> getList(){

        Session session = HibernateUtil.currentSession();
        Transaction transaction = session.getTransaction();

        List<User> list = session.createQuery("from User").list();

        return list;
    }
}
           

至此,所有的代碼都貼完了,我也是剛接觸這些東西,有什麼不對的地方,請指出,萬分感謝!

下載下傳位址:https://github.com/DevilHeS/LoginProject

繼續閱讀