1. 程式人生 > >Struts 2 + Hibernate 使用者的登入與登出

Struts 2 + Hibernate 使用者的登入與登出

 1.反向工程生成使用者實體類

User.java

package com.sunline.entity;
/**
 * User entity. @author MyEclipse Persistence Tools
 */

public class User  implements java.io.Serializable {


    // Fields    

     private Integer userId;
     private String userName;
     private String userPassword;
     private String userStatus;


    // Constructors

    /** default constructor */
    public User() {
    }

    
    /** full constructor */
    public User(String userName, String userPassword, String userStatus) {
        this.userName = userName;
        this.userPassword = userPassword;
        this.userStatus = userStatus;
    }

   
    // Property accessors

    public Integer getUserId() {
        return this.userId;
    }
    
    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    public String getUserName() {
        return this.userName;
    }
    
    public void setUserName(String userName) {
        this.userName = userName;
    }

    public String getUserPassword() {
        return this.userPassword;
    }
    
    public void setUserPassword(String userPassword) {
        this.userPassword = userPassword;
    }

    public String getUserStatus() {
        return this.userStatus;
    }
    
    public void setUserStatus(String userStatus) {
        this.userStatus = userStatus;
    }

}

User.hbm.xml

<?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">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="com.sunline.entity.User" table="user" catalog="hengfeng">
        <id name="userId" type="java.lang.Integer">
            <column name="user_id" />
            <generator class="native"></generator>
        </id>
        <property name="userName" type="java.lang.String">
            <column name="user_name" length="40" not-null="true" />
        </property>
        <property name="userPassword" type="java.lang.String">
            <column name="user_password" length="30" not-null="true" />
        </property>
        <property name="userStatus" type="java.lang.String">
            <column name="user_status" length="30" not-null="true" />
        </property>
    </class>
</hibernate-mapping>

Hibernate配置檔案

Hibernate.cfg.xml

<?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">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
	<property name="dialect">
		org.hibernate.dialect.MySQLDialect
	</property>
	<property name="connection.url">
		jdbc:mysql://localhost:3306/hengfeng?characterEncoding=UTF-8
	</property>
	<property name="connection.username">root</property>
	<property name="connection.password">******</property>
	<property name="connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<property name="myeclipse.connection.profile">
		com.mysql.jdbc.Driver
	</property>
	<property name="show_sql">true</property>
	<property name="format_sql">true</property>
	<property name="hbm2ddl.auto">update</property>
	<mapping resource="com/sunline/entity/Basedata.hbm.xml" />
	<mapping resource="com/sunline/entity/Targetdimension.hbm.xml" />
	<mapping resource="com/sunline/entity/User.hbm.xml" />

</session-factory>

</hibernate-configuration>

Struts 2 配置檔案

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>
	<package name="SunlineShow" extends="struts-default">
	   <!-- 登入 -->
	   <action name="Main" class="com.sunline.action.LoginAction">
			<result name="success">/jsp/Main.jsp</result>
			<result name="error">/error.jsp</result>
		</action>
	   
	   <!-- 登出登入 -->
	   <action name="LogOut" class="com.sunline.action.LogoutAction">
			<result name="success">/index.jsp</result>
		</action>
	</package>
</struts>    

Hibernate配置檔案解析類

HibernateSessionFactory.java

package com.sunline.dao;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory {
    private SessionFactory sessionFactory;
    public HibernateSessionFactory(){
        
    }
    
    public SessionFactory config(){
        try{
            Configuration configuration= new Configuration();
            Configuration configure=configuration.configure("hibernate.cfg.xml");
            return configure.buildSessionFactory();
        }catch(Exception e){
        e.getMessage();
        return null;
        }
    }
    
    public Session getSession(){
        sessionFactory=config();
        return sessionFactory.openSession();
    }
}

資料訪問層Dao類

UserDao.java

package com.sunline.dao;

import java.util.List;

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

import com.sunline.entity.User;

public class UserDao {
	private Session session;
	private Transaction transaction;
	private Query query;
	HibernateSessionFactory getSession;
    public List<User> Login(String user_name,String user_password){
    	getSession = new HibernateSessionFactory();
    	session = getSession.getSession();
        try{
            String hqlsql="from User as u where u.userName=? and u.userPassword=?";
            query=session.createQuery(hqlsql);
            query.setParameter(0, user_name);
            query.setParameter(1, user_password);
            List<User> list=query.list();
            transaction=session.beginTransaction();
            System.out.println("查詢成功!");
            transaction.commit();
            return list;
        }catch(Exception e){
            System.out.println("查詢錯誤!");
            e.printStackTrace();
            return null;
        }
    }
}

Action控制類

登入控制類:

LoginAction.java

package com.sunline.action;

import java.util.List;
import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.sunline.dao.UserDao;
import com.sunline.entity.User;

public class LoginAction extends ActionSupport {
	private static final long serialVersionUID = 1889710968497585080L;
	private String user_name ;
	private String user_password;
	public String getUser_name() {
		return user_name;
	}
	public void setUser_name(String user_name) {
		this.user_name = user_name;
	}
	public String getUser_password() {
		return user_password;
	}
	public void setUser_password(String user_password) {
		this.user_password = user_password;
	}
	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
		UserDao dao = new UserDao();
		List<User> list = dao.Login(this.user_name, this.user_password);
		if(list.size()>=1){
			ActionContext context = ActionContext.getContext();
			Map<String, Object> session = context.getSession();
		//	session.put("user",list);
			session.put("user",this.user_name);
			return SUCCESS;
		}
		else{
			return ERROR;
		}
	}
	
}

登出控制類:

LogoutAction.java

package com.sunline.action;

import java.util.Map;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class LogoutAction extends ActionSupport {
	private static final long serialVersionUID = 1L;

	@Override
	public String execute() throws Exception {
		// TODO Auto-generated method stub
        Map session = ActionContext.getContext().getSession(); 
        session.remove("user"); 
		return SUCCESS;
	}
    
}

登入前端頁面:

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登入驗證</title>
<link rel="stylesheet" href="bootstrap-3.3.7/css/bootstrap.min.css">    
<script src="js/jquery-3.2.1.min.js"></script>    
<script src="js/bootstrap.min.js"></script>  
<script type="text/javascript">
function check(){
	var uname = document.getElementById("uname").value;
	var upassword = document.getElementById("upassword").value;
	if(uname==""){
		alert("使用者名稱為空!");
		return false;
	}
	if(upassword==""){
		alert("密碼為空!");
		return false;
	}
}
</script>
<style type="text/css">
  .input-group{  
        margin:10px 0px;//輸入框上下外邊距為10px,左右為0px  
    }  
    h3{  
        padding:5px;  
        border-bottom:1px solid #ddd;//h3字型下邊框  
    }  
    em{//強調的樣式  
        color:#c7254e;  
        font-style: inherit;  
        background-color: #f9f2f4;  
    }  
    .center{
       margin-left: auto;
       margin-right: auto;
       vertical-align:middle;
       text-align: center;
    }
</style>
</head>
<body style="background-image: url(image/3.jpg)">
 <center>
<nav class="navbar navbar-default" role="navigation" style="text-align: center;">
 <div class="container-fluid">
	<div class="navbar-header">
		<a class="navbar-brand" href="#"><span class="glyphicon glyphicon-flag" aria-hidden="true">
		</span>財務資料集市系統</a>
	</div> 
 </div>
</nav>

<div class="row center" style="margin-top:100px;">  
  <div class="col-md-5 col-sm-offset-4">  
    <div class="well col-md-10">  
       <h3>使用者登入</h3>  
       <div>
          <span style="font-size: 16px;"><font color="red">${message}</font></span><br/>
          <span style="font-size: 16px;"><font color="red">${verify}</font></span>
       </div>
       <form action="Main" method="post" onsubmit="return check()">
		    <div class="input-group input-group-md">  
		          <span class="input-group-addon" id="sizing-addon1"><i class="glyphicon glyphicon-user" aria-hidden="true"></i></span>  
		          <input type="text" class="form-control" id="uname" name="user_name" placeholder="使用者名稱" aria-describedby="sizing-addon1">
		    </div>  
		    <div class="input-group input-group-md">  
		          <span class="input-group-addon" id="sizing-addon1"><i class="glyphicon glyphicon-lock"></i></span>  
		          <input type="password" class="form-control" id="upassword" name="user_password" placeholder="密碼" aria-describedby="sizing-addon1">  
		    </div>  
		    <div style="float: right">
		             <a href="#">忘記密碼?</a>
		    </div>
		    <input type="submit" name="sub" class="btn btn-success btn-block" value="登入"/>
	    </form>
    </div>  
  </div>  
</div>  
</center>
</body>
</html>

截圖: