Structs版本 2.3.31
Hibernate版本 4.3.11
Tomcat 8.0
JDK 1.8
Eclipse版本 Neon.1a Release (4.6.1)
Eclipse插件JBoss Tools 4.4.1
数据库 MySQL
综合Structs 和 Hibernate,Structs 做页面跳转,Hibernate代替JDBC执行数据库的操作,登录就是条件查询,注册就是添加数据
Jar包,我会发源码
必不可缺的文件,直接给出源代码,下面就写这些文件了
数据库,root ,root,要先建立数据库,我建的数据库名为 sh
web.xml
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>StructsAndHibernateTestdisplay-name>
<filter>
<filter-name>struts2filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilterfilter-class>
filter>
<filter-mapping>
<filter-name>struts2filter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
web-app>
struts.xml
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="user_login" method="login" class="jxust.action.UserAction">
<result>/success.jspresult>
<result name="input">/index.jspresult>
<result name="registersuccess">/index.jspresult>
action>
<action name="user_register" method="register" class="jxust.action.UserAction">
<result>/index.jspresult>
<result name="input">/register.jspresult>
action>
package>
struts>
Hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="connection.username">rootproperty>
<property name="connection.password">rootproperty>
<property name="connection.driver_class">com.mysql.jdbc.Driverproperty>
<property name="connection.url">jdbc:mysql://127.0.0.1:3306/sh?useUnicod=true&characterEncoding=utf8property>
<property name="dialect">org.hibernate.dialect.MySQLDialectproperty>
<property name="show_sql">trueproperty>
<property name="format_sql">trueproperty>
<property name="hbm2ddl.auto">updateproperty>
<mapping resource="jxust/model/User.hbm.xml"/>
session-factory>
hibernate-configuration>
User.hbm.xml
<hibernate-mapping>
<class name="jxust.model.User" table="USER">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="increment" />
id>
<property name="username" type="java.lang.String">
<column name="USERNAME" />
property>
<property name="password" type="java.lang.String">
<column name="PASSWORD" />
property>
class>
hibernate-mapping>
源代码顺序是按包从上到下
源代码下载:http://download.csdn.net/detail/peng_hong_fu/9686886
jxust.action
包UserAction.java
package jxust.action;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.opensymphony.xwork2.ActionSupport;
import jxust.dao.impl.UserDaoImpl;
import jxust.model.User;
@SuppressWarnings("serial")
public class UserAction extends ActionSupport implements SessionAware {
private String username;
private String password;
UserDaoImpl dao = new UserDaoImpl();
private Map session;
public String login(){
System.out.println(username +","+ password);
User user = dao.isvalidateAdmin(username, password);
if (user != null) {
session.put("loginusername", user.getUsername());
return SUCCESS;
} else {
addFieldError("loginerror", "用户名或密码错误!");
return INPUT;
}
}
public String register(){
User user = new User(username,password);
dao.saveUser(user);
return "success";
}
//validate验证
public void validate() {
if(username==null||"".equals(username)){
this.addFieldError("username", "用户名不能为空");
}
if(password==null||"".equals(password)){
this.addFieldError("password", "密码不能为空");
}
}
@Override
public void setSession(Map session) {
this.session = session;
}
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;
}
}
jxust.dao
包HBSessionDao.java
package jxust.dao;
import java.util.List;
import org.hibernate.Session;
public interface HBSessionDao {
public Session getSession();
public void closeSession();
public List search(String hql);
}
UserDao.java
package jxust.dao;
import java.util.List;
import jxust.model.User;
public interface UserDao {
public void saveUser(User user);
public List getAll();
public User isvalidateAdmin(String username,String password);
}
jxust.dao.impl
包HBSessionDaoImpl.java
package jxust.dao.impl;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import jxust.dao.HBSessionDao;
public class HBSessionDaoImpl implements HBSessionDao {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
private void init() {
//创建配置对象
Configuration cfg = new Configuration().configure();
//创建服务注册对象
StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build();
//创建会话工厂对象
sessionFactory = cfg.buildSessionFactory(serviceRegistry);
//会话对象
session =sessionFactory.openSession();
//开启事务
transaction = session.beginTransaction();
}
@Override
public Session getSession() {
init();
return session;
}
@Override
public void closeSession() {
transaction.commit();//提交事务
session.close();// 关闭对话
sessionFactory.close();// 关闭会话工厂
}
@Override
public List search(String hql) {
//查询不用事务管理
Session session = null;
session = getSession();
List alist = null;
alist = session.createQuery(hql).list();
session.close();
return alist;
}
}
UserDaoImpl.java
package jxust.dao.impl;
import java.util.List;
import org.hibernate.Session;
import jxust.dao.HBSessionDao;
import jxust.dao.UserDao;
import jxust.model.User;
public class UserDaoImpl implements UserDao {
@Override
public void saveUser(User user) {
System.out.println("添加数据...");
HBSessionDao hbsessionDao = new HBSessionDaoImpl();
Session session = hbsessionDao.getSession();
session.save(user);
hbsessionDao.closeSession();
System.out.println("添加数据成功...");
}
@SuppressWarnings("unchecked")
@Override
public List getAll() {
List listuser = null;
HBSessionDao hbsessionDao = new HBSessionDaoImpl();
Session session = hbsessionDao.getSession();
listuser = session.createQuery("from User").list();
hbsessionDao.closeSession();//需要关闭
return listuser;
}
@Override
public User isvalidateAdmin(String username, String password) {
HBSessionDaoImpl hbsessionDao= new HBSessionDaoImpl();
User user = null;
System.out.println("查询数据库匹配数据...");
@SuppressWarnings("unchecked")
List list = hbsessionDao.search(
"FROM User where username = '" + username + "' and password = '" + password + "'");
if (list != null && list.size() > 0) {
user = list.get(0);
System.out.println("查询到的数据:"+user.toString());
}
return user;
}
//测试UserDaoImpl
/* public static void main(String[] args) {
*//**
* 插入数据,id为自增长
* UserDaoImpl dao = new UserDaoImpl();
User user1 =new User("秦天明2","12345");
dao.saveUser(user1);
*//*
*//**
*查询数据
*UserDaoImpl dao = new UserDaoImpl();
User user = dao.isvalidateAdmin("秦天明2","12345");
System.out.println(user.toString());
*//*
//查询user表所有数据
UserDaoImpl dao = new UserDaoImpl();
List list = dao.getAll();
System.out.println("共查询到"+list.size()+"条数据");
for(User s:list){
System.out.println(s.toString());
}
}*/
}
jxust.model
包User.java
package jxust.model;
/**
* 用户个人信息实体类
* @author Peng
*
*/
public class User {
private Integer id;//id
private String username;//用户名
private String password;//密码
public User() {
super();
}
public User( String username, String password) {
super();
this.username = username;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
}
}
User 类对应关系映射文件,在配置Hibernate环境时已给出
添加数据:
Hibernate:
select
max(ID)
from
USER
Hibernate:
insert
into
USER
(USERNAME, PASSWORD, ID)
values
(?, ?, ?)
查询数据:
Hibernate:
select
user0_.ID as ID1_0_,
user0_.USERNAME as USERNAME2_0_,
user0_.PASSWORD as PASSWORD3_0_
from
USER user0_
where
user0_.USERNAME='秦天明2'
and user0_.PASSWORD='12345'
查询所有:
Hibernate:
select
user0_.ID as ID1_0_,
user0_.USERNAME as USERNAME2_0_,
user0_.PASSWORD as PASSWORD3_0_
from
USER user0_
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>index.jsp起始页title>
head>
<body>
<h1>登录h1>
<%-- "loginerror" > --%>
<s:fielderror>s:fielderror>
<form action="user_login.action" method="post">
用户名:<input type="text" name="username"/><br/>
密 码:<input type="password" name="password"/><br/>
<input type="submit" value="登录"/> <a href="register.jsp"><input type="button" value="注册"/>a>
form>
body>
html>
register.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>register.jsp起始页title>
head>
<body>
<h1>注册h1>
<s:fielderror fieldName="registererror">s:fielderror>
<form action="user_register.action" method="post">
用户名:<input type="text" name="username"/><br/>
密 码:<input type="password" name="password"/><br/>
<input type="submit" value="注册"/><input type="reset" value="重置">
form>
body>
html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>登录成功title>
head>
<body>
<h1>欢迎${loginusername},登录成功!h1>
body>
html>
1.没有添加数据库连接驱动名
"connection.driver_class">com.mysql.jdbc.Driver
2.解决了一个Action中,多个方法验证失败返回同一个视图的问题
我配置两个action来解决
name="user_login" method="login" class="jxust.action.UserAction">
<result>/success.jspresult>
<result name="input">/index.jspresult>
<result name="registersuccess">/index.jspresult>
name="user_register" method="register" class="jxust.action.UserAction">
<result>/index.jspresult>
<result name="input">/register.jspresult>
http://download.csdn.net/detail/peng_hong_fu/9686886