文件目录结构如下:
数据库test的表info如下:
详细步骤如下:
1.新建一个web project,命名为ch14,然后右击ch14,选择倒数第二项 myeclipse,依次添加Struts2核心组件和Hibernate核心组件;然后把mysql的驱动文件包拷贝进/ch14/WebRoot/WEB-INF/lib 下
2.登录界面的jsp文件代码(login.jsp)
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
注册
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
登录
<%@ page language="java" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
欢迎${userName },登录成功!
5.addHibernateFile下的HibernateSessionFactory.java代码:
package addHibernateFile;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
* Configures and provides access to Hibernate sessions, tied to the
* current thread of execution. Follows the Thread Local Session
* pattern, see {@link http://hibernate.org/42.html }.
*/
public class HibernateSessionFactory {
/**
* Location of hibernate.cfg.xml file.
* Location should be on the classpath as Hibernate uses
* #resourceAsStream style lookup for its configuration file.
* The default classpath location of the hibernate config file is
* in the default package. Use #setConfigFile() to update
* the location of the configuration file for the current session.
*/
private static final ThreadLocal threadLocal = new ThreadLocal();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static ServiceRegistry serviceRegistry;
static {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public HibernateSessionFactory() {
}
public SessionFactory config(){
try{
Configuration configuration = new Configuration();
Configuration configure = configuration.configure("hibewnate.cfg.xml");
return configure.buildSessionFactory();
}catch(Exception e){
e.getMessage();
return null;
}
}
/**
* Returns the ThreadLocal Session instance. Lazy initialize
* the SessionFactory
if needed.
*
* @return Session
* @throws HibernateException
*/
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
/**
* Rebuild hibernate session factory
*
*/
public static void rebuildSessionFactory() {
try {
configuration.configure();
serviceRegistry = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
/**
* Close the single hibernate session instance.
*
* @throws HibernateException
*/
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
/**
* return session factory
*
*/
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
/**
* return hibernate configuration
*
*/
public static Configuration getConfiguration() {
return configuration;
}
}
(1)LoginAction.java
package loginRegisterAction;
import java.util.List;
import loginRegisterDao.*;
import PO.UserInfoPO;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private String userName;
private String password;
private String message="error";
private List list;
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;
}
public void validate(){
if(this.getUserName()==null || this.getUserName().length()==0){
addFieldError("userName", "用户名不能为空!");
}else{
LoginRegisterInfo info = new LoginRegisterInfo();
list = info.queryInfo("userName",this.getUserName());
if(list.size()==0){
addFieldError("userName", "该用户尚未注册!");
}else{
UserInfoPO ui = new UserInfoPO();
int count = 0;
for(int i=0; i
package loginRegisterAction;
import java.util.List;
import loginRegisterDao.LoginRegisterInfo;
import PO.UserInfoPO;
import com.opensymphony.xwork2.ActionSupport;
public class RegisterAction extends ActionSupport {
private String userName;
private String password1;
private String password2;
private String mess=ERROR;
private List list;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword1() {
return password1;
}
public void setPassword1(String password1) {
this.password1 = password1;
}
public String getPassword2() {
return password2;
}
public void setPassword2(String password2) {
this.password2 = password2;
}
public void validate(){
if(this.getUserName()==null || this.getUserName().length()==0){
addFieldError("userName", "用户名不能为空!");
}else{
LoginRegisterInfo info = new LoginRegisterInfo();
list = info.queryInfo("userName",this.getUserName());
UserInfoPO ui = new UserInfoPO();
for(int i=0; i
package loginRegisterDao;
import java.util.List;
import javax.swing.JOptionPane;
import PO.UserInfoPO;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import addHibernateFile.HibernateSessionFactory;
public class LoginRegisterInfo {
private Session session;
private Transaction transaction;
private Query query;
HibernateSessionFactory getSession;
public LoginRegisterInfo() {
}
public String saveInfo(UserInfoPO info) {
String mess = "error";
getSession = new HibernateSessionFactory();
session = getSession.getSession();
try {
transaction = session.beginTransaction();
session.save(info);
transaction.commit();
mess = "success";
return mess;
} catch (Exception e) {
message("RegisterInfo.error:" + e);
e.printStackTrace();
return null;
}
}
public List queryInfo(String type, Object value) {
getSession = new HibernateSessionFactory();
session = getSession.getSession();
transaction = session.beginTransaction(); /
try {
String hqlsql = "from UserInfoPO as u where u.userName='" + value
+ "'";
query = session.createQuery(hqlsql);
// query.setParameter(0, value);
List list = query.list();
transaction.commit();
return list;
} catch (Exception e) {
message("LoginRegisterInfo类中有异常,异常为:" + e);
e.printStackTrace();
return null;
}
}
public void message(String mess) {
int type = JOptionPane.YES_NO_OPTION;
String title = "提示信息";
JOptionPane.showMessageDialog(null, mess, title, type);
}
}
(1)UserInfoPO.java
package PO;
public class UserInfoPO {
private int id;
private String userName;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
}
jdbc:mysql://localhost:3306/test
root
1234
com.mysql.jdbc.Driver
org.hibernate.dialect.MySQLInnoDBDialect
/login.jsp
/register.jsp
/register.jsp
/success.jsp
/login.jsp
/login.jsp
login.jsp
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*
OK,全部代码贴完毕,接下来是运行流程:
首先进去的是注册页面:register.jsp,填写注册信息:用户名和密码,有一个validate验证,如下第一个图:
如果验证通过,就会跳转到登录界面,如上第二个图:
如果用户名和密码都正确,则登录成功,如上第三个图:
好了,上面是大概的流程,以下就是稍微详细一点的流程(本人菜鸟,正在学习中,大牛勿喷呀):
首先进入register.jsp,提交之后会向tomcat服务器发送请求,服务器接收到请求之后,会查看web.xml配置文件,发现所有请求都交给struts2这个过滤器来处理;struts.xml就会根据发来的请求,找到与请求相应的action,发现是register这个action,就会去执行loginRegisterAction包里面的RegisterAction.java类,先执行validate()这个验证方法,然后根据类里面的execute返回的信息执行下一步;如果信息是success,则表示成功了,跳转到login.jsp这个页面;如果是error或者input,则表示失败了,重新回到register.jsp页面;成功跳转到login.jsp之后,填写用户名密码,提交,又会发送请求到tomcat服务器,紧接着服务器会查看web.xml文件,发现被拦截到了struts.xml中,继续查找struts.xml中的action,发现login这个action与之匹配,执行loginRegisterAction包里面的LoginAction.java类,先执行validate()这个验证方法,再执行execute()方法,根据返回的信息,如果成功success则跳转到success.jsp页面,登录成功,如果失败error则返回登录界面login.jsp