struts2和hibernate整合的小Demo

jar包下載地址html

 


 

建立一個web項目。java


 

導入jar包mysql


配置web.xmlweb

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">

    <-- Struts的核心過濾器配置-->
    <filter>
        <filter-name>struts</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts</filter-name>
        <url-pattern>*.action</url-pattern>
    </filter-mapping>
    <filter-mapping>
        <filter-name>struts</filter-name>
        <url-pattern>*.jsp </url-pattern>
    </filter-mapping>
</web-app>

 

 在src 目錄下建立 hibernate.cfg.xml,指定數據庫「demo」sql


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
        <session-factory>
            <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="connection.url">jdbc:mysql://localhost:3306/demo</property>
            <property name="connection.username">root</property>
            <property name="connection.password">123</property>
            <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

            <property name="show_sql">true</property>
            <property name="format_sql">true</property>
            <property name="hbm2ddl.auto">update</property>
            <property name="current_session_context_class">thread</property>
        </session-factory>
</hibernate-configuration>

 

建立一個User實體類數據庫

 

package com.test.pojo;

/**
 * Created by Wdnnccey on 2016/10/24.
 */
public class User {
    private int uid;
    private String username;
    private String password;

    public User() {
    }

    public User(int uid, String username, String password) {
        this.uid = uid;
        this.username = username;
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    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;
    }
}

建立 :User.hbm.xml, 數據映射文件,對應的分別是數據字段。apache

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

<hibernate-mapping>
    <class name="com.test.pojo.User" table="user">
        <id name="uid" column="uid">
            <generator class="native"/>
        </id>
        <property name="username" column="username"  type="java.lang.String" length="20" />
        <property name="password" column="password"  type="java.lang.String" length="20"/>
 
    </class>
</hibernate-mapping>

 

建立一個包存放專門用來工具類,獲取session操做等等。tomcat

HibernateUtils.java安全

 

package com.test.utils;

import org.hibernate.Hibernate;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * Created by Wdnnccey on 2016/10/24.
 */
public class HibernateUtils {

    private static SessionFactory sessionFactory;

    //保證單例模式
    private HibernateUtils(){

    }

    //公有的靜態方法
    public static SessionFactory getSessionFactory(){

        if(sessionFactory ==null){
            Configuration configuration =new Configuration().configure();
            ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
            sessionFactory = configuration.buildSessionFactory(serviceRegistry);
            return sessionFactory;
        }else {
            return sessionFactory;
        }
    }

}

 

在建立一個源碼包,做爲測試類使用,來建立表。 TestDemo.javasession

package com.test;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.metamodel.relational.Schema;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;

/**
 * Created by Wdnnccey on 2016/10/24.
 */
public class TestDemo {

    @Test
    public void TestAll(){
        Configuration configuration = new Configuration().configure();
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
        SessionFactory sessionFactory =configuration.buildSessionFactory(serviceRegistry);
        Session session = sessionFactory.getCurrentSession();
        Transaction transaction = session.beginTransaction();
        SchemaExport export =new SchemaExport(configuration);
        export.create(true,true);
    }
}

成功建立user表。

 

在web目錄下建立users-->目錄存放-->login.jsp做爲登錄頁面。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>登錄頁面</title>
</head>
<body>
        <form action="" method="post">
                username:<input type="text" name="username"/><br>
                password:<input type="password" name="password"/><br>
            <input type="submit" value="tijiao"/>
        </form>
</body>
</html>

 

在web目錄下建立users-->目錄存放-->fails.jsp做爲登錄失敗後返回的頁面。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
你失敗了。
</body>
</html>

 

在web目錄下建立users-->目錄存放-->success.jsp做爲登錄成功後返回的頁面。 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
你成功了。
</body>
</html>

在src目錄下建立一個struts.xml配置文件。

<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <package name="default" extends="struts-default" namespace="/"> </package> <package name="users" namespace="/users" extends="default"> <!--http://www.cnblogs.com/wdnnccey/p/5982988.html有介紹--> <action name="*_*" class="com.test.action.{1}Action" method="{2}"> <!--若是登錄成功返回的頁面--> <result name="login_success">/users/success.jsp</result> <!--若是登錄失敗返回的頁面--> <result name="login_fails">/users/fails.jsp</result> </action> </package> </struts>

 

在src下建立一個dao層。 接口:userDao.java

import com.test.pojo.User;

/**
 * Created by Wdnnccey on 2016/10/24.
 */
public interface UserDao {

    //用戶登錄
    public boolean userLogin(User user);
}

在src下建立一個dao層的實現層。 userDaoImpl.java

;

import com.test.pojo.User;
import com.test.utils.HibernateUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import java.util.List;

/**
 * Created by Wdnnccey on 2016/10/24.
 */
public class UserDaoImpl  implements UserDao{
    @Override
    public boolean userLogin(User user) {
        //初始化事務
        Transaction transaction =null;
        //建立一個hql語句,先初始化。
        String hql ="";

        try {
            //用以前建立的utils工具來獲取session
            Session session = HibernateUtils.getSessionFactory().getCurrentSession();
            //建立事務並開啓事務
            transaction =session.beginTransaction();
            //編寫hql語句
            hql = "from User where username=? and password =?";
            //經過query去建立語句
            Query query = session.createQuery(hql);
            //爲hql語句中的?(問號),設置參數。(經過user實體類獲取來user用戶名和密碼的信息)
            query.setParameter(0,user.getUsername());
            query.setParameter(1,user.getPassword());
            //HQL語句返回的是一個QUery對象,將Query對象query轉換成集合,而且把該集合賦值給一個新的集合。
            List<User> list =query.list();
            //執行以前要提交事務
            transaction.commit();
            //判斷是否驗證到有用戶存在
            if(list.size()>0){
                return  true;
            }else {
                return  false;
            }
        }catch (Exception e){

        }finally {
            //將事務置爲空
            if(transaction!=null){
                transaction=null;
            }
        }
        return false;
    }
}

 

在src下建立一個action的包,用於存放action, 咱們先寫一個 SuperAction.java 

關於爲何繼承ActionSupport,請參考:http://www.cnblogs.com/wdnnccey/p/5994693.html

關於爲何要時間那些接口,請參考:http://www.cnblogs.com/wdnnccey/p/5994713.html

package com.test.action;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.util.ServletContextAware;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.spi.http.HttpContext;

/**
 * 全部action的父類
 * Created by Wdnnccey on 2016/10/24.
 */
public class SuperAction  extends ActionSupport implements ServletRequestAware,ServletResponseAware,ServletContextAware{

    protected HttpServletResponse response;
    protected HttpServletRequest request;
    protected ServletContext application;
    protected HttpSession session;

    @Override
    public void setServletRequest(HttpServletRequest request) {
        this.request = request;
        this.session = this.request.getSession();
    }

    @Override
    public void setServletResponse(HttpServletResponse response) {
        this.response =response;
    }

    @Override
    public void setServletContext(ServletContext application) {
        this.application=application;
    }
}

 

  在action包下建立 userAction.java 

package com.test.action;

import com.opensymphony.xwork2.ModelDriven;
import com.test.pojo.User;
import com.test.serivce.impl.UserDao;
import com.test.serivce.impl.UserDaoImpl;

/**
 * Created  by Wdnnccey on 2016/10/24.
 */
public class UserAction extends SuperAction implements ModelDriven<User> {

    //初始化一個user對象
    private User user = new User();

    //這裏使用模型驅動
    //所謂ModelDriven ,意思是直接把實體類當成頁面數據的收集對象。
    @Override
    public User getModel() {
        return this.user;
    }

    /**
     * 登錄方法
     * @return
     */
    public String login() {
        UserDao dao = new UserDaoImpl();
        //若是匹配的話
        if (dao.userLogin(user)) {
            //返回正確頁面,(session是通SuperAction獲得的!
 session.setAttribute("LoginUsername", user.getUsername());
      //若是正確跳轉到success頁面,在struts.xml中有體現配置
return "login_success"; } else { //返回錯頁面 return "login_fails"; } }
}

 

咱們在登錄以前要插入一條用戶數據,以便登錄的時候去驗證!

 

部署web項目,啓動tomcat :

 

在這輸入用戶名以及密碼 驗證。

我先輸入一個錯誤的信息,點擊提交按鈕:

 

此次咱們輸入一個正確的數據, 在數據庫中存在的!

寫到這裏,咱們完成了一個簡單的登錄的功能,以及頁面跳轉。


 

咱們想在登錄頁面知道這個用戶是誰:

在session域中取得,咱們在登錄時候setattribute的值(session.setAttribute("LoginUsername", user.getUsername());)

在success.jsp頁面添加以下:

歡迎你:(${sessionScope.LoginUsername})登錄!

 

再次登錄驗證:

http://localhost:8081/users/login.jsp


 

 

若是咱們想實現對這個用戶的退出呢? 也很簡單,把這個用戶在session中移除便可,代碼以下:

在userAction中編寫註銷方法:

    /**
     * 註銷方法
     */
    public String loginout() {
        //先去session中去獲取值,查看當前用戶是否爲空
        if (session.getAttribute("LoginUsername") != null) {
            //若是不等於空的話咱們將他移出session
            session.removeAttribute("LoginUsername");
        }
        //返回到登錄頁面(這個return的值是經過struts.xml文件配置的)
        return "loginout_success";
    }

在struts.xml的配置:(紅色標註)

<!DOCTYPE struts PUBLIC
        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
        "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="default" extends="struts-default" namespace="/">
    </package>
    
    <package name="users" namespace="/users" extends="default">
            <!--http://www.cnblogs.com/wdnnccey/p/5982988.html有介紹-->
        <action name="*_*" class="com.test.action.{1}Action" method="{2}">
            <!--若是登錄成功返回的頁面-->
            <result name="login_success">/users/success.jsp</result>
            <!--若是登錄失敗返回的頁面-->
            <result name="login_fails">/users/fails.jsp</result>
            <!--退出用戶的返回頁面-->
            <result name="loginout_success">/users/login.jsp</result>
        </action>
    </package>
   
</struts>

 

咱們須要在登錄成功的success.jsp寫上安全註銷的連接(紅色標註):

 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
你成功了。
<br><br><br> 歡迎你:(${sessionScope.LoginUsername})登錄! <br><br><br> <a href="/users/User_loginout.action">安全退出!</a> </body> </html>

 

 

測試註銷方法:

 

看地址欄,能看出來 咱們已經成功的退出當前用戶!

 

 

 不知道爲何 代碼的格式沒有複製上去,我就貼在這裏啦:

 struts.xml

 

<!DOCTYPE struts PUBLIC        "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"        "http://struts.apache.org/dtds/struts-2.0.dtd"><struts>    <package name="default" extends="struts-default" namespace="/">    </package>        <package name="users" namespace="/users" extends="default">            <!--http://www.cnblogs.com/wdnnccey/p/5982988.html有介紹-->        <action name="*_*" class="com.test.action.{1}Action" method="{2}">            <!--若是登錄成功返回的頁面-->            <result name="login_success">/users/success.jsp</result>            <!--若是登錄失敗返回的頁面-->            <result name="login_fails">/users/fails.jsp</result>            <!--退出用戶的返回頁面-->            <result name="loginout_success">/users/login.jsp</result>        </action>    </package></struts>
相關文章
相關標籤/搜索