Posted on 2008-09-04 22:28
H2O 阅读(1181)
评论(1) 编辑 收藏 所属分类:
Spring+Struts+Hibernate整合
项目结构图
包 com.yz.dao.impl
package com.yz.dao.impl;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Order;
import org.hibernate.type.DateType;
import org.hibernate.type.FloatType;
import org.hibernate.type.IntegerType;
import org.hibernate.type.StringType;
import org.hibernate.type.Type;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.yz.dao.intf.IBaseDao;
public class IBaseDaoImpl<T> extends HibernateDaoSupport implements IBaseDao<T> {
public T add(T ob) {
boolean add = false;
this.getHibernateTemplate().save(ob);
return ob;
}
public boolean update(T ob) {
this.getHibernateTemplate().update(ob);
return true;
}
public boolean delete(T ob) {
this.getHibernateTemplate().delete(ob);
return true;
}
public boolean deleteById(final Class cl,final Serializable id) {
Object obj =this.getHibernateTemplate().get(cl, id);
this.getHibernateTemplate().delete(obj);
return true;
}
public T getById(Class cl,Serializable id) {
return (T) this.getHibernateTemplate().get(cl, id);
}
public List getAllObject(final Class cl) {
List lst = this.getHibernateTemplate().executeFind(new HibernateCallback(){
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Criteria cr = session.createCriteria(cl);
return cr.list();
}
});
return lst;
}
public List<T> getObjectsByMap(final Class cl,final Map map) {
List lst = this.getHibernateTemplate().executeFind(new HibernateCallback(){
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Criteria cr = session.createCriteria(cl);
cr.add(Expression.allEq(map));
return cr.list();
}
});
return lst;
}
public T getUniqueObjectByMap(final Class cl,final Map map) {
Object obj = this.getHibernateTemplate().execute(new HibernateCallback(){
public Object doInHibernate(Session session) throws HibernateException, SQLException {
Criteria cr = session.createCriteria(cl);
cr.add(Expression.allEq(map));
return cr.uniqueResult();
}
});
return (T)obj;
}
public List<T> getOrderObjects(final Class cl,final Map map, final String orderstr,
final Integer beginpos, final Integer count) {
List lst =this.getHibernateTemplate().executeFind(new HibernateCallback(){
public Object doInHibernate(Session session){
Criteria cri = session.createCriteria(cl);
if (!(map == null)) {
Set keyset = map.keySet();
for (Object key : keyset) {
if (key == null || map.get(key) == null)
continue;
if (key.getClass() == String.class)
cri.add(Expression.like(key.toString(), map.get(key)));
else
cri.add(Expression.eq(key.toString(), map.get(key)));
}
}
if (orderstr != null)
cri.addOrder(Order.desc(orderstr));
if (beginpos != null)
cri.setFirstResult(beginpos);
else
cri.setFirstResult(0);
if (count != null)
cri.setMaxResults(count.intValue());
return cri.list();
}
});
return lst;
}
public List pageQuery(final String hql, final Integer currentPage,final Integer pageSize,final ObjectbindValue) {
List result = this.getHibernateTemplate().executeFind(
new HibernateCallback(){
public Object doInHibernate(Session session){
Query query = session.createQuery(hql);
if (bindValue != null && bindValue.length >= 1) {
//得到传入参数的对应到hibernate的类型
Type[] types = typesFactory(bindValue);
//设置query对象的参数
query.setParameters(bindValue, types);
}
if (currentPage != null && currentPage.intValue() >= 0) {
query.setFirstResult((currentPage-1)*pageSize);
if (pageSize != null && pageSize.intValue() >= 0)
query.setMaxResults(pageSize);
}
return query.list();
}
}
);
return result;
}
// 获取数组对象对应的类型。
private final Type[] typesFactory(ObjectbindValue) {
int count = bindValue.length;
Type[] types = new Type[count];
for (int i = 0; i < count; i++) {
if (bindValue[i].getClass().getName().endsWith("String")) {
types[i] = new StringType();
} else if (bindValue[i].getClass().getName().endsWith("Integer")) {
types[i] = new IntegerType();
} else if (bindValue[i].getClass().getName().endsWith("Float")) {
types[i] = new FloatType();
} else if (bindValue[i].getClass().getName().endsWith("Date")) {
types[i] = new DateType();
}
}
return types;
}
public Integer getPageCount(final Class c, final Integer pageSize) {
final String hql ="select count(*) from "+c.getName()+"";
Object count =this.getHibernateTemplate().execute(
new HibernateCallback(){
public Object doInHibernate(Session session){
return session.createQuery(hql).uniqueResult().toString();
}
}
);
Integer recordCount = Integer.parseInt(count.toString());
//表的总记录数
Integer pageCount = (recordCount+pageSize)/pageSize;
return pageCount;
}
}
package com.yz.dao.impl;
import java.util.List;
import com.yz.dao.intf.IDeptDao;
import com.yz.hbm.Dept;
public class IDeptDaoImpl extends IBaseDaoImpl<Dept> implements IDeptDao<Dept> {
public List<Dept> getAllDepts() {
List<Dept> lst = super.getAllObject(Dept.class);
return lst;
}
public Dept getDeptById(Integer id) {
return super.getById(Dept.class, id);
}
}
package com.yz.dao.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.yz.dao.intf.IUserDao;
import com.yz.hbm.Users;
public class IUserDaoImpl extends IBaseDaoImpl<Users> implements IUserDao<Users> {
public Users addUsers(Users u) {
return super.add(u);
}
public boolean checkLogin(Users u) {
Map<String,String> map = new HashMap<String,String>();
map.put("uname", u.getUname());
map.put("pwd",u.getPwd());
return super.getObjectsByMap(Users.class, map).size()>0;
}
public List<Users> getAllUsers(Integer currentPage,Integer pageSize) {
return super.pageQuery("from Users", currentPage, pageSize, null);
}
public Users getUsersById( int uid) {
return super.getById(Users.class,uid);
}
public boolean updateUsers(Users u) {
return super.update(u);
}
public List<Users> getAllUsers() {
return super.getAllObject(Users.class);
}
}
包 com.yz.dao.intf
package com.yz.dao.intf;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
public interface IBaseDao<T> {
/** *//**
* 添加POJO对象
*/
public T add(T ob);
/** *//**
* 更新POJO对象
*/
public abstract boolean update(T ob);
/** *//**
* 删除POJO对象
*/
public abstract boolean delete(T ob);
/** *//**
* 根据主键删除POJO对象
*/
public abstract boolean deleteById(Class cl, Serializable id);
/** *//**
* 根据主键查询POJO对象
*/
public abstract T getById(Class cl, Serializable id);
/** *//**
* 查询所有POJO对象
*/
public abstract List getAllObject(Class cl);
// 根据类型和查询条件(相等的条件)来得到响应对象
/** *//**
* map。put("属性名","属性值")
* map.put("username","1111");
* map.put("pwd","1111");
* Map map=new HashMap();
* map.put("key","");
*/
public abstract List<T> getObjectsByMap(Class cl, final Map map);
public abstract T getUniqueObjectByMap(Class cl, final Map map);
// 根据一个hql语句和一个map集合进行查询,并且可以培训和分页。
/** *//**根据一个hql语句和一个map集合进行查询,并且可以培训和分页。
* 例子:在子类中间 String hql="from Users as u where u.uname = ? and u.upwd = ?";
* Map map=new HashMap(); map.put("uname",users.getUname()); //注意键为类中间的属性名
* map.put("upwd",users.getUname()); List list =
* super.getOrderObjects(map,null, null, null);
*/
public abstract List<T> getOrderObjects(Class cl, final Map map,
final String orderstr, final Integer beginpos, final Integer count);
// 根据一个hql语句和一个对象进行分页的查询
/** *//**根据一个hql语句和一个对象进行分页的查询
* 例子:在子类中间 String hql="from Users as u where u.uname = ? and u.upwd = ?";
* Object[] params=new String[]{users.getUname(),users.getUpwd()}; List list =
* super.pageQuery(hql,params, null, null);
*/
public abstract List pageQuery(String hql,
Integer currentPage, Integer pageSize,ObjectbindValue);
/** *//**
* 根据类去找到表从而查询出总记录数,再根据页大小计算出总页数
* @param c
* @return
*/
public Integer getPageCount(Class c,Integer pageSize);
}
package com.yz.dao.intf;
import java.util.List;
import com.yz.hbm.Dept;
public interface IDeptDao<T> extends IBaseDao<T> {
public List<Dept> getAllDepts();
public T getDeptById(Integer id);
}
package com.yz.dao.intf;
import java.util.List;
import com.yz.hbm.Users;
public interface IUserDao<T> extends IBaseDao<T> {
public abstract Users addUsers(Users u);
public abstract boolean checkLogin(Users u);
public abstract List<T> getAllUsers();
public abstract T getUsersById(int uid);
public abstract boolean updateUsers(Users u);
public abstract List<T> getAllUsers(Integer currentPage,Integer pageSize);
}
包com.yz.hbm
package com.yz.hbm;
import java.util.HashSet;
import java.util.Set;
public class Dept implements java.io.Serializable {
private Integer deptId;
private String deptName;
private Set userses = new HashSet(0);
public Dept() {
}
public Dept(String deptName) {
this.deptName = deptName;
}
public Dept(String deptName, Set userses) {
this.deptName = deptName;
this.userses = userses;
}
public Integer getDeptId() {
return this.deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
public String getDeptName() {
return this.deptName;
}
public void setDeptName(String deptName) {
this.deptName = deptName;
}
public Set getUserses() {
return this.userses;
}
public void setUserses(Set userses) {
this.userses = userses;
}
}
package com.yz.hbm;
import java.util.Date;
public class Users implements java.io.Serializable {
private Integer uid;
private Dept dept;
private String uname;
private String pwd;
private Date birth;
private String aihao;
public Users() {
}
public Users(Dept dept, String uname, String pwd, Date birth) {
this.dept = dept;
this.uname = uname;
this.pwd = pwd;
this.birth = birth;
}
public Users(Dept dept, String uname, String pwd, Date birth, String aihao) {
this.dept = dept;
this.uname = uname;
this.pwd = pwd;
this.birth = birth;
this.aihao = aihao;
}
public Integer getUid() {
return this.uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public Dept getDept() {
return this.dept;
}
public void setDept(Dept dept) {
this.dept = dept;
}
public String getUname() {
return this.uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPwd() {
return this.pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public Date getBirth() {
return this.birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public String getAihao() {
return this.aihao;
}
public void setAihao(String aihao) {
this.aihao = aihao;
}
}
<?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.yz.hbm.Dept" table="dept" catalog="ssh">
<id name="deptId" type="java.lang.Integer">
<column name="deptId" />
<generator class="native" />
</id>
<property name="deptName" type="java.lang.String">
<column name="deptName" length="32" not-null="true">
<comment>部门名称</comment>
</column>
</property>
<set name="userses" inverse="true">
<key>
<column name="deptId" not-null="true">
<comment>属于该部门用户</comment>
</column>
</key>
<one-to-many class="com.yz.hbm.Users" />
</set>
</class>
</hibernate-mapping>
<?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.yz.hbm.Users" table="users">
<id name="uid" type="java.lang.Integer">
<column name="uid" />
<generator class="native" />
</id>
<many-to-one name="dept" class="com.yz.hbm.Dept" fetch="select">
<column name="deptId" not-null="true">
<comment>部门编号</comment>
</column>
</many-to-one>
<property name="uname" type="java.lang.String">
<column name="uname" length="32" not-null="true">
<comment>用户名</comment>
</column>
</property>
<property name="pwd" type="java.lang.String">
<column name="pwd" length="16" not-null="true">
<comment>密码</comment>
</column>
</property>
<property name="birth" type="java.util.Date">
<column name="birth" length="10" not-null="true">
<comment>生日</comment>
</column>
</property>
<property name="aihao" type="java.lang.String">
<column name="aihao" length="50">
<comment>爱好</comment>
</column>
</property>
</class>
</hibernate-mapping>
包com.yz.services.intf
package com.yz.serveces.intf;
import java.util.List;
import com.yz.hbm.Dept;
public interface IDeptService {
public abstract List<Dept> getAllDept();
public abstract Dept getDeptById(Integer id);
}
package com.yz.serveces.intf;
import java.util.List;
import com.yz.hbm.Users;
public interface IUserService {
public abstract Users addUsers(Users u);
public abstract boolean checkLogin(Users u);
public abstract List<Users> getAllUsers();
public abstract List<Users> getAllUsers(int currentPage, int pageSize);
public abstract boolean delUsersById(int uid);
public abstract Users getUsersById(int uid);
public abstract boolean updateUsers(Users u);
public abstract Integer getPageCount(int pageSize);
}
包com.yz.services.impl
package com.yz.services.impl;
import java.util.List;
import com.yz.dao.impl.IDeptDaoImpl;
import com.yz.dao.intf.IDeptDao;
import com.yz.hbm.Dept;
import com.yz.serveces.intf.IDeptService;
public class DeptServices implements IDeptService {
IDeptDao<Dept> dept;
public IDeptDao<Dept> getDept() {
return dept;
}
public void setDept(IDeptDao<Dept> dept) {
this.dept = dept;
}
public List<Dept> getAllDept(){
return dept.getAllDepts();
}
public Dept getDeptById(Integer id){
return dept.getDeptById(id);
}
}
package com.yz.services.impl;
import java.util.HashMap;
import java.util.List;
import com.yz.dao.impl.IUserDaoImpl;
import com.yz.dao.intf.IUserDao;
import com.yz.hbm.Users;
import com.yz.serveces.intf.IUserService;
public class UserServices implements IUserService {
IUserDao<Users> ud;
public IUserDao<Users> getUd() {
return ud;
}
public void setUd(IUserDao<Users> ud) {
this.ud = ud;
}
public Users addUsers(Users u) {
return (Users) ud.add(u);
}
public boolean checkLogin(Users u) {
return ud.checkLogin(u);
}
public List<Users> getAllUsers(){
return ud.getAllUsers();
}
public List<Users> getAllUsers(int currentPage,int pageSize){
return ud.getAllUsers(currentPage, pageSize);
}
public boolean delUsersById(int uid) {
return ud.deleteById(Users.class,uid );
}
public Users getUsersById(int uid) {
return (Users) ud.getUsersById(uid);
}
public boolean updateUsers(Users u) {
return ud.updateUsers(u);
}
public Integer getPageCount(int pageSize){
return ud.getPageCount(Users.class, pageSize);
}
}
包com.yz.sturts 放struts的资源文件ApplicationResources.properties 不要也没关系,本例子没用到属性文件
包com.yz.actions
package com.yz.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
public class DeptAction extends DispatchAction {
public ActionForward getAllDept(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
return mapping.findForward("");
}
}
package com.yz.struts.action;
import java.text.SimpleDateFormat;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import com.yz.hbm.Users;
import com.yz.serveces.intf.IDeptService;
import com.yz.serveces.intf.IUserService;
import com.yz.services.impl.DeptServices;
import com.yz.services.impl.UserServices;
import com.yz.struts.form.UserForm;
public class UserAction extends DispatchAction {
IUserService us ;
IDeptService ds ;
public IDeptService getDs() {
return ds;
}
public void setDs(IDeptService ds) {
this.ds = ds;
}
public IUserService getUs() {
return us;
}
public void setUs(IUserService us) {
this.us = us;
}
public ActionForward regist(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
UserForm uf = (UserForm) form;
Users u = new Users();
u.setUname(uf.getUname());
u.setBirth(new SimpleDateFormat("yyyy-MM-dd").parse(uf.getBirth()));
u.setPwd(uf.getPwd());
String aihao ="";
for (int i = 0; i < uf.getAihaos().length; i++) {
if(i<uf.getAihaos().length-1){
aihao+=uf.getAihaos()[i]+",";
}else{
aihao+=uf.getAihaos()[i];
}
}
u.setAihao(aihao);
u.setDept(ds.getDeptById(uf.getDeptId()));
//添加用户
Users add =us.addUsers(u);
if(add!=null){
//添加成功
request.setAttribute("msg","恭喜你,用户添加成功!");
request.setAttribute("go","login.jsp");
request.setAttribute("goinfo", " 登 录 ");
}else{
//添加失败
request.setAttribute("msg","对不起,添加失败");
}
return mapping.findForward("tips");
}
public ActionForward checkLogin(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
UserForm uf = (UserForm) form;
Users u = new Users();
u.setUname(uf.getUname());
u.setPwd(uf.getPwd());
boolean login=us.checkLogin(u);
if(login){
request.setAttribute("msg", "恭喜你,登录成功!");
request.setAttribute("go","/yz-ssh/users.do?actions=queryAll");
request.setAttribute("goinfo", "进入管理页面。o O");
}else{
request.setAttribute("msg", "对不起,登录失败!");
}
return mapping.findForward("tips");
}
public ActionForward queryAll(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
//页大小--->每页显示的记录条数
int pageSize = 5;
//总页数
int pageCount = us.getPageCount(pageSize);
//当前页
String cpage =request.getParameter("currentPage")==null?"":request.getParameter("currentPage").toString();
int currentPage = request.getParameter("currentPage")==null?1:Integer.parseInt(cpage);
List<Users> lst = us.getAllUsers(currentPage, pageSize);
request.setAttribute("allUsers", lst);
request.setAttribute("pageCount",pageCount);
request.setAttribute("currentPage", currentPage);
return mapping.findForward("admin");
}
public ActionForward modify(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
Users u = us.getUsersById(Integer.parseInt(request.getParameter("uid")));
UserForm uf = (UserForm) form;
uf.setUid(u.getUid());
uf.setUname(u.getUname());
uf.setPwd(u.getPwd());
uf.setBirth(new SimpleDateFormat("yyyy-MM-dd").format(u.getBirth()));
uf.setAihaos(u.getAihao().split(","));
uf.setDeptId(u.getDept().getDeptId());
return mapping.findForward("modify");
}
public ActionForward del(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
String uid = request.getParameter("uid");
boolean del =us.delUsersById(Integer.parseInt(uid));
if(del){
request.setAttribute("msg", "恭喜您,删除成功!");
}else{
request.setAttribute("msg", "对不起,删除失败!");
}
return mapping.findForward("tips");
}
public ActionForward finishModify(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
UserForm uf = (UserForm) form;
Users u = new Users();
u.setUname(uf.getUname());
u.setBirth(new SimpleDateFormat("yyyy-MM-dd").parse(uf.getBirth()));
u.setPwd(uf.getPwd());
u.setUid(uf.getUid());
String aihao ="";
for (int i = 0; i < uf.getAihaos().length; i++) {
if(i<uf.getAihaos().length-1){
aihao+=uf.getAihaos()[i]+",";
}else{
aihao+=uf.getAihaos()[i];
}
}
u.setAihao(aihao);
u.setDept(ds.getDeptById(uf.getDeptId()));
//修改用户
boolean update =us.updateUsers(u);
if(update){
request.setAttribute("msg", "恭喜您,修改成功!");
request.setAttribute("go","/yz-ssh/users.do?actions=queryAll");
request.setAttribute("goinfo", "进入管理页面。o O");
}else{
request.setAttribute("msg", "对不起,修改失败!");
}
return mapping.findForward("tips");
}
}
包com.yz.struts.forms
package com.yz.struts.form;
import java.text.ParseException;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import com.yz.hbm.Dept;
import com.yz.serveces.intf.IDeptService;
import com.yz.services.impl.DeptServices;
public class UserForm extends ActionForm{
private Integer uid;
private Integer deptId;
private String uname;
private String pwd;
private String birth;
private String[] aihaos;
private Integer currentPage;
private Integer pageSize;
private Integer pageCount;
public Integer getPageCount() {
return pageCount;
}
public void setPageCount(Integer pageCount) {
this.pageCount = pageCount;
}
public Integer getCurrentPage() {
return currentPage;
}
public void setCurrentPage(Integer currentPage) {
this.currentPage = currentPage;
}
public Integer getPageSize() {
return pageSize;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public String[] getAihaos() {
return aihaos;
}
@Override
public void reset(ActionMapping mapping, HttpServletRequest request) {
if(request.getSession().getAttribute("allDept")==null){
//查询处所有部门
String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
ApplicationContext appctx =(ApplicationContext) servlet.getServletContext().getAttribute(key);
IDeptService ds = (IDeptService) appctx.getBean("deptService");
List<Dept> depts = ds.getAllDept();
System.out.println(depts.get(0).getDeptId());
//保存到session范围
request.getSession().setAttribute("allDept",depts );
}
}
public void setAihaos(String[] aihaos) {
this.aihaos = aihaos;
}
public String getBirth() {
return birth;
}
public void setBirth(String birth) {
this.birth = birth;
}
public Integer getDeptId() {
return deptId;
}
public void setDeptId(Integer deptId) {
this.deptId = deptId;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
}
log4j.properties配置
#to console#
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %m%n
#to file#
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=ssh.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %l %m%n
#error/warn/info/debug#
log4j.rootLogger=info, stdout, file
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
<!-- 数据源,保存数据库连接信息 -->
<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/ssh"></property>
<property name="username" value="root"></property>
<property name="password" value="admin"></property>
</bean>
<!--session工厂,用session工厂获得session会话连接-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="ds"></ref>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
</props>
</property>
<!-- 指定 POJO类的映射文件路径
还有一种写法
<property name="mappingDirectoryLocations">
<list>
<value>classpath:/com/yz/hbm</value>
</list>
</property>
-->
<property name="mappingResources">
<list>
<value>com/yz/hbm/Users.hbm.xml</value>
<value>com/yz/hbm/Dept.hbm.xml</value>
</list>
</property>
</bean>
<!-- spring容器创建了一个hibernateTemplate对象 -->
<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 事务管理器 apring2.0中间事务的配置和处理-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- 事务属性:通知/处理/横切关注点
<tx:method name="add*" propagation="REQUIRED" isolation="DEFAULT" />
以add开头 事务传播属性(没有事务就创建) 事务隔离级别(数据库默认)
-->
<tx:advice id="mytx">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" isolation="DEFAULT"/>
<tx:method name="*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 织入 -->
<aop:config>
<aop:advisor advice-ref="mytx" pointcut="execution(* com.yz.services.impl.*.*(..))"/>
</aop:config>
</beans>
actionbean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<!-- 具体的action对象 -->
<bean name="/users" class="com.yz.struts.action.UserAction">
<property name="us" ref="userService"></property>
<property name="ds" ref="deptService"></property>
</bean>
</beans>
bean.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<!-- 具体的dao对象 -->
<bean id="userDao" class="com.yz.dao.impl.IUserDaoImpl">
<property name="hibernateTemplate" ref="hibernateTemplate">
</property>
</bean>
<bean id="deptDao" class="com.yz.dao.impl.IDeptDaoImpl">
<property name="hibernateTemplate" ref="hibernateTemplate">
</property>
</bean>
<!-- 具体的service对象 -->
<bean id="userService" class="com.yz.services.impl.UserServices">
<property name="ud" ref="userDao"></property>
</bean>
<bean id="deptService" class="com.yz.services.impl.DeptServices">
<property name="dept" ref="deptDao"></property>
</bean>
</beans>
struts.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.2//EN" "http://struts.apache.org/dtds/struts-config_1_2.dtd">
<struts-config>
<data-sources />
<form-beans>
<form-bean name="userForm" type="com.yz.struts.form.UserForm"></form-bean>
</form-beans>
<global-exceptions />
<global-forwards>
<forward name="tips" path="/msg.jsp"></forward>
<forward name="admin" path="/manage.jsp"></forward>
<forward name="modify" path="/modify.jsp"></forward>
</global-forwards>
<action-mappings>
<action
path="/users"
name="userForm"
attribute="userForm"
type="com.yz.struts.actions.UserAction"
scope="request"
parameter="actions">
</action>
</action-mappings>
<!-- 替换掉struts中的请求处理器 -->
<controller processorClass="org.springframework.web.struts.DelegatingRequestProcessor"></controller>
<message-resources parameter="com.yz.struts.ApplicationResources" />
</struts-config>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>action</servlet-name>
<servlet-class>
org.apache.struts.action.ActionServlet
</servlet-class>
<init-param>
<param-name>config</param-name>
<param-value>/WEB-INF/struts-config.xml</param-value>
</init-param>
<init-param>
<param-name>debug</param-name>
<param-value>3</param-value>
</init-param>
<init-param>
<param-name>detail</param-name>
<param-value>3</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>action</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- 使用监听器来加载spring容器: 支持多配置文件-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml,/WEB-INF/bean.xml,/WEB-INF/actionbean.xml
</param-value>
</context-param>
<!-- 改监听器用来读取spring配置文件,启动spring容器 -->
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<!-- 加载spring过滤器处理中文 -->
<filter>
<filter-name>ChineseFilter</filter-name>
<filter-class>
org.springframework.web.filter.CharacterEncodingFilter
</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>ChineseFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 何时关闭session -->
<filter>
<filter-name>sessionFilter</filter-name>
<filter-class>
org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>sessionFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<jsp:directive.page import="com.yz.hbm.Dept"/>
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>用户注册</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<center>
<table>
<caption><h1>用户注册</h1></caption>
<html:form action="/users?actions=regist">
<tr>
<td>用户名:</td>
<td><html:text property="uname" ></html:text></td>
</tr>
<tr>
<td>密码:</td>
<td><html:password property="pwd" ></html:password></td>
</tr>
<tr>
<td>生日::</td>
<td><html:text property="birth" ></html:text></td>
</tr>
<tr>
<td>爱好:</td>
<td>
<html:multibox property="aihaos" value="电影"></html:multibox>电影
<html:multibox property="aihaos" value="游戏"></html:multibox>游戏
<html:multibox property="aihaos" value="音乐"></html:multibox>音乐
<html:multibox property="aihaos" value="泡妞"></html:multibox>泡妞
<html:multibox property="aihaos" value="美女"></html:multibox>美女
<html:multibox property="aihaos" value="帅哥"></html:multibox>帅哥
<html:multibox property="aihaos" value="旅行"></html:multibox>旅行
<html:multibox property="aihaos" value="无聊"></html:multibox>无聊
<html:multibox property="aihaos" value="感伤"></html:multibox>感伤
<html:multibox property="aihaos" value="做白日梦"></html:multibox>做白日梦
</td>
</tr>
<tr>
<td>部门:</td>
<td><html:select property="deptId">
<html:optionsCollection name="allDept" label="deptName" value="deptId"/>
</html:select>
</td>
</tr>
<tr>
<td><html:submit value=" 注 册 "></html:submit></td>
<td><html:reset value=" 重 置 "></html:reset></td>
</tr>
</html:form>
</table>
</center>
<body>
</body>
</html>
login.jsp
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
<head>
<html:base />
<title>用户登录</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<center>
<html:form method="post" action="/users?actions=checkLogin" focus="uname">
<table>
<caption style="font-weight:bold;"> 用 户 登 录</caption>
<tr>
<td>用户名:</td>
<td><html:text property="uname"></html:text> </td>
</tr>
<tr>
<td>密 码:</td>
<td><html:password property="pwd"></html:password></td>
</tr>
<tr>
<td><html:submit value=" 登 录 "></html:submit></td>
<td><html:reset value=" 重 置 "></html:reset></td>
</tr>
</table>
</html:form>
</center>
</body>
</html:html>
manage.jsp
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
<head>
<html:base />
<title>用户管理</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<%
Integer currentPage=request.getAttribute("currentPage")==null?1:Integer.parseInt(request.getAttribute("currentPage").toString());
Integer pageCount=request.getAttribute("pageCount")==null?1:Integer.parseInt(request.getAttribute("pageCount").toString());
%>
<script type="text/javascript">
</script>
</head>
<body>
<center>
<table>
<caption style="font-weight:bold;font-size:30px;">用户管理</caption>
<th>序号</th><th>用户编号</th><th>用户名</th><th>密码</th><th>生日</th><th>爱好</th><th>部门</th>
<logic:iterate id="u" name="allUsers" indexId="i">
<tr>
<td>${i+1}<br><br></td>
<td><bean:write name="u" property="uid"/></td>
<td><bean:write name="u" property="uname"/></td>
<td><bean:write name="u" property="pwd"/></td>
<td><bean:write name="u" property="birth"/></td>
<td><bean:write name="u" property="aihao"></bean:write></td>
<td>${u.dept.deptName}</td>
<td><html:link style="color:red;font-weight:bold;" action="/users?actions=modify" paramId="uid" paramName="u" paramProperty="uid" >修改</html:link></td>
<td><html:link style="color:red;font-weight:bold;" action="/users?actions=del" paramId="uid" paramName="u" paramProperty="uid" onclick="return(confirm('你确定要删除吗?'))">删除</html:link></td>
</tr>
</logic:iterate>
</table>
<div style="color:red;fontsize:20px;">
<a href="/yz-ssh/users.do?actions=queryAll¤tPage=1">首页</a>
<a href="/yz-ssh/users.do?actions=queryAll¤tPage=<%=currentPage-1 %>" onclick="return <%=currentPage>1%>"<%=currentPage==1?"disabled":"" %> >上一页</a>
<a href="/yz-ssh/users.do?actions=queryAll¤tPage=<%=currentPage+1 %>" onclick="return <%=currentPage<pageCount%>" <%=currentPage==pageCount?"disabled":"" %>>下一页</a>
<a href="/yz-ssh/users.do?actions=queryAll¤tPage=<%=pageCount%>">尾页</a>
当前页${currentPage==null?1:currentPage}
<b style="color:blue;font-weight:bold;font-size:50px;">/
</b>总页数:${pageCount}
</div>
</center>
</body>
</html:html>
modify.jsp
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
<head>
<html:base />
<title>用户修改</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
</head>
<body>
<center>
<table>
<caption><h1>用户注册</h1></caption>
<html:form action="/users?actions=finishModify">
<tr>
<html:hidden property="uid"/>
<td>用户名:</td>
<td><html:text property="uname" ></html:text></td>
</tr>
<tr>
<td>密码:</td>
<td><html:password property="pwd" ></html:password></td>
</tr>
<tr>
<td>生日::</td>
<td><html:text property="birth" ></html:text></td>
</tr>
<tr>
<td>爱好:</td>
<td>
<html:multibox property="aihaos" value="电影"></html:multibox>电影
<html:multibox property="aihaos" value="游戏"></html:multibox>游戏
<html:multibox property="aihaos" value="音乐"></html:multibox>音乐
<html:multibox property="aihaos" value="泡妞"></html:multibox>泡妞
<html:multibox property="aihaos" value="美女"></html:multibox>美女
<html:multibox property="aihaos" value="帅哥"></html:multibox>帅哥
<html:multibox property="aihaos" value="旅行"></html:multibox>旅行
<html:multibox property="aihaos" value="无聊"></html:multibox>无聊
<html:multibox property="aihaos" value="感伤"></html:multibox>感伤
<html:multibox property="aihaos" value="做白日梦"></html:multibox>做白日梦
</td>
</tr>
<tr>
<td>部门:</td>
<td><html:select property="deptId">
<html:optionsCollection name="allDept" label="deptName" value="deptId"/>
</html:select>
</td>
</tr>
<tr>
<td><html:submit value=" 注 册 "></html:submit></td>
<td><html:reset value=" 重 置 "></html:reset></td>
</tr>
</html:form>
</table>
</center>
</body>
</html:html>
msg.jsp
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://struts.apache.org/tags-bean" prefix="bean" %>
<%@ taglib uri="http://struts.apache.org/tags-html" prefix="html" %>
<%@ taglib uri="http://struts.apache.org/tags-logic" prefix="logic" %>
<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html:html lang="true">
<head>
<html:base />
<title>小毅温馨提示您o(∩_∩)o</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<h1 style="color:red;">${msg}</h1><br>
<h3 style="color:blue;"><a href="javascript:history.back();"> 返 回 </a></h3><br>
<h3 style="color:red;"><a href="${go}"> ${goinfo} </a></h3>
</body>
</html:html>
数据库创建脚本.sql
drop database if exists ssh;
create database ssh;
use ssh;
-- 用户表
drop table if exists users;
create table users(
uid int PRIMARY key auto_increment comment '用户编号',
uname varchar(32) not NULL comment '用户名',
pwd char(16) not null comment '密码',
birth date not null comment '出生日期',
aihao varchar(50) comment '爱好',
deptId int not null comment'所在部门编号'
);
-- 部门表
drop table if exists dept;
create table dept(
deptId int primary key auto_increment comment '部门编号',
deptName varchar(32) not NULL comment '部门名称'
);
-- 添加约束
alter table users add constraint fk_users_deptId foreign key(deptId) references dept(deptId);
-- 插入测试数据
insert into dept values(default,'技术部');
insert into dept values(default,'无聊部');
insert into dept values(default,'美女部');
insert into dept values(default,'帅哥部');
insert into users values(default,'小毅','yizhi','1989-01-25 01:01:01','无聊,游戏',1);