- 浏览: 415087 次
- 性别:
- 来自: 深圳
文章分类
最新评论
-
skying007:
...
Mysql coalesce() 函数认识和用法 -
kchiu:
关于这个心跳的发送和接收 晚上全是the fuccking s ...
socket心跳检测 -
bjsq618:
你的想法在大的物流公司已经实现了,只不过他们使用是GPS定位
ddd -
jiaguwen123:
2,AuthenticationHandler类的写法
pa ...
xfire客户端 -
sornor:
总结的不错哟!
Java中的函数yield(),sleep()和wait()的区别
项目结构图
地址:http://www.blogjava.net/xiaoyi/articles/xiaoyi_ssh.html
包 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);
地址:http://www.blogjava.net/xiaoyi/articles/xiaoyi_ssh.html
包 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);
发表评论
-
cxf需要的jar包
2012-12-09 21:55 3822cxf-2.3.3.jar geronimo-annotati ... -
eclipse下安装tomcat插件方法
2010-10-17 11:01 1736在Eclipse下安装Tomcat插件使开发,编译,发布变的相 ... -
SVN的约定俗成的目录结构
2010-10-10 22:32 1548对于SVN约定俗成的目录结构的一点资料:(另外,由本官方出的书 ... -
Windows下svn权限配置说明
2010-09-18 22:23 11291、 本文档适用于对Subvesion的自带服务 ... -
svn的服务器及客户端安装和配置
2010-09-18 11:28 1278一、svn服务器安装 1、 ... -
j2se----Timer和TimerTask
2010-09-16 20:11 1034Timer是一个定时器对象,本来可以用Thread.sleep ... -
java实现AOP日志记录功能
2010-09-08 09:08 1231目前整个开发社区对AOP(Aspect ... -
ECLIPSE快捷键大全
2010-09-03 09:13 820Ctrl+1 快速修复(最经典的快捷键,就不用多说了) Ctr ... -
Rose Rational安装及破解方法
2010-08-25 13:06 11131、安装Rational Rose2003时,在需选择安装项的 ... -
常用正则表达式
2010-08-03 16:57 830下面给出一些常用正则表达式: 1、 非负整数:”^d+$” ... -
绝妙的权限控制算法
2010-07-16 11:34 720这里笔者介绍一种很常用,也比较专业的权限控制思路。这里用jav ... -
JSP使用FCKeditor详解
2010-07-14 11:01 924在向大家详细介绍JSP使用FCKeditor之前,首先让大家了 ... -
错误: Undeployment Failure XXX could not be redeploy
2010-07-05 08:59 1548关键字: undeployment failure 错误: ...
相关推荐
这个整合例子旨在展示如何将这三个框架协同工作,以构建一个完整的Java Web应用程序。 Struts1是Apache基金会的一个开源项目,主要用于处理Web应用程序的用户界面和业务逻辑。它遵循MVC(Model-View-Controller)...
在Struts和Hibernate的整合中,Spring主要作为容器管理它们,包括Action对象和数据访问对象(DAO)。Spring的IoC容器可以轻松地管理和配置其他框架的组件,使得整个应用的耦合度降低。 **Hibernate框架**是一个强大...
一个简单的struts+spring+hibernate整合实现用户注册的例子,我花了一个下午整出来的,希望对想学习的同志有所帮助。 mysql sql文: DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `password` varchar(32) ...
SSH(Struts+Spring+Hibernate)是Java Web开发中一种常见的技术栈,它将MVC设计模式、依赖注入和持久层框架集成为一个整体,大大提高了开发效率和代码的可维护性。下面我们将深入探讨SSH框架的各个组成部分及其结合...
在`stm-ssh`和`SSHdemo`中,可能包含的是Struts2+Spring+Hibernate的整合示例。开发者通常会创建Action类来处理请求,定义Service层来封装业务逻辑,并使用Hibernate来操作数据库。Spring会管理这些对象的生命周期和...
SSH整合,全称为Struts、Spring和Hibernate的集成,是一种常见的Java Web开发框架组合,用于构建高效、可维护的企业级应用程序。在这个例子中,我们看到的是一个基于SSH的用户注册功能的实现,使用的开发工具是...
### Struts+Spring+Hibernate...综上所述,通过合理配置和整合Struts、Spring和Hibernate这三个框架,可以构建出一个结构清晰、易于维护的Web应用系统。这种方式不仅提高了开发效率,也确保了系统的稳定性和可扩展性。
自己总结了一下,终于做出的Struts+Spring+Hibernate整合的小例子,也是最基础的SSH实例,虽然是小例子,但什么程序都是从基础的做起。如果你弄明白了这个小实例,相信你的SSH整合框架技术也会提高很多。 在做本例...
环境:jdk5.0 eclipse3.2 struts1.1 spring1.2 hibernate3.1 mysql5.0 1. 新建一个starssh的web工程 2. 添加struts框架包。 3. 添加spring框架包。注意spring的配置文件要放到WEB-INF下。 4. 添加hibernate框架...
java(1) 整合入门(spring,struts,hibernate的整合)资料(1) 中大软件工厂项目前培训资料(1) 完整笔记+源码(1) ssh(1) C#查询参数化例子(1) 学习笔记+完整源码(1) 介绍与深入(1) 学习笔记(不含整合)(1) C#(1) .CHM格式...
Struts、Spring、Hibernate(SSH)是Java Web开发中三个非常重要的开源框架,它们分别用于MVC模式的实现、依赖注入和持久化管理。SSH整合是将这三个框架结合在一起,以构建更高效、可维护性更强的企业级应用。本文...
下面将详细讨论Spring的核心特性,特别是其在控制反转(IOC)和依赖注入(DI)中的作用,以及如何与Struts和Hibernate整合。 Spring框架的核心是控制反转(IOC),这是一种设计模式,它将对象的创建和管理从应用...
Struts2、Spring和Hibernate是Java Web开发中的三大框架,它们的组合被称为SSH2。SSH2框架集成可以实现MVC(Model-View-Controller)架构,提供强大的数据持久化、业务逻辑管理和用户界面控制能力。下面我们将详细...
Struts、Spring和Hibernate是Java开发中非常著名的三大框架,它们各自解决了一部分软件开发中的问题,而将它们集成在一起可以构建出强大的企业级应用。这个压缩包文件提供了一个使用这三个框架加上Ajax技术的详细...
SSH整合是Java Web开发中的一个经典组合,由Struts、Spring和Hibernate三个开源框架组成,它们各自负责Web应用的不同层面,协同工作以提高开发效率和应用的可维护性。Struts处理请求和视图,Spring提供依赖注入和...
最简单的Spring+Struts2+Hibernate整合例子,MySql数据库,IDE是JavaEE版的Eclipse,tomcat7.0 ,实现功能:登录+注册+增删改查+一键清空数据库表的数据。所有jar文件都在里面了。
Struts1.2+Spring1.2+HIbernate3.1整合一个用户登录的例子,原以为这个很简单没有必要上传上去,但问我的人太多了,所以就发布上来了,我随后会在博客里做详细的介绍,请大家继续关注我的博客.
### Struts1+Spring+Hibernate整合示例解析 在Java Web开发领域,Struts1、Spring与Hibernate三者的结合(通常简称为SSH)是构建复杂应用的一种常见模式。本篇文章将详细解读“struts1+spring+hibernate整合示例”...
标题 "Eclipse + MyEclipse整合Struts+Spring+Hibernate简单例子开发" 指向的是一个关于如何在集成开发环境Eclipse与MyEclipse中搭建Struts、Spring和Hibernate(SSH)框架的教程。SSH是Java Web开发中常用的一个...
《Struts+Spring+Hibernate整合教程》:深入解析与实践指南 **一、SSH整合理念** 在《Struts+Spring+Hibernate整合教程》中,作者陈文光详细阐述了Struts、Spring和Hibernate三大框架的整合策略,旨在构建一个结构...