創建一個web項目。

導入jar包

配置web.xml
<?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”
<?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, 數據映射文件,對應的分別是數據字段。
<?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操作等等。
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.java
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>
