实现增删该查的步骤:
一、做ACTION相关的准备:ACTION,jsp,配置.
- 创建MYaction extends BaseAction
- 定义出Action中的方法,要写出方法名,作用、返回值。
- 创建所用到的JSP页面
- 配置Action:1.在myAction上写注解@Controller与@Scope("prototype") 2.在strtus.xml中配置这个Action与所用的result。
@Transactional
// @Transactional注解可以被继承,即对子类也有效
子类有此注解,父类无效!
@Controller
@Scope("prototype")
子类不能继承父类,每次子类都要注解。
二、做Service相关准备
- 创建接口myService extends BaseDao;
- 创建实现类MyService extends BaseDaoImpl
- 配置 在MyServiceIMPLE 上添加@service注解
package cn.itcast.oa.base; import java.lang.reflect.ParameterizedType; import javax.annotation.Resource; import cn.itcast.oa.service.DepartmentService; import cn.itcast.oa.service.RoleService; import cn.itcast.oa.service.UserService; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T>{ @Resource protected RoleService roleService; @Resource protected DepartmentService departmentService; @Resource protected UserService userService; protected T model; public BaseAction() { try { // 得到model的类型信息 getClass得到子类,<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">getGenericSuperclass()得到该子类的父类,也就是该方法</span> <span style="white-space:pre"> </span>//得到真实的参数类型<span style="font-family: Arial, Helvetica, sans-serif; font-size: 12px;">ParameterizedType </span> <span style="white-space:pre"> </span>//得到第一个参数的真实参数类型 ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); Class clazz = (Class) pt.getActualTypeArguments()[0]; // 通过反射生成model的实例 model = (T) clazz.newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } public T getModel() { return model; } }
package cn.itcast.oa.base; import java.util.List; public interface BaseDao<T> { /** * 保存实体 * * @param entity */ void save(T entity); /** * 删除实体 * * @param id */ void delete(Long id); /** * 更新实体 * * @param entity */ void update(T entity); /** * 查询实体,如果id为null,则返回null,并不会抛异常。 * * @param id * @return */ T getById(Long id); /** * 查询实体 * * @param ids * @return */ List<T> getByIds(Long[] ids); /** * 查询所有 * * @return */ List<T> findAll(); }
package cn.itcast.oa.base; import java.lang.reflect.ParameterizedType; import java.util.Collections; import java.util.List; import javax.annotation.Resource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.transaction.annotation.Transactional; // @Transactional注解可以被继承,即对子类也有效 @Transactional @SuppressWarnings("unchecked") public abstract class BaseDaoImpl<T> implements BaseDao<T> { @Resource private SessionFactory sessionFactory; protected Class<T> clazz; // 这是一个问题! public BaseDaoImpl() { // 通过反射得到T的真实类型 ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); this.clazz = (Class) pt.getActualTypeArguments()[0]; System.out.println("clazz = " + clazz.getName()); } public void save(T entity) { getSession().save(entity); } public void update(T entity) { getSession().update(entity); } public void delete(Long id) { Object obj = getSession().get(clazz, id); getSession().delete(obj); } public T getById(Long id) { if (id == null) { return null; } return (T) getSession().get(clazz, id); } public List<T> getByIds(Long[] ids) { if (ids == null || ids.length == 0) { return Collections.EMPTY_LIST; } return getSession().createQuery(// "FROM " + clazz.getSimpleName() + " WHERE id IN(:ids)")// .setParameterList("ids", ids)// .list(); } public List<T> findAll() { return getSession().createQuery(// "FROM " + clazz.getSimpleName())// .list(); } /** * 获取当前可用的Session * * @return */ protected Session getSession() { return sessionFactory.getCurrentSession(); } }
三、填空
- ACTION方法
- 新增的Service方法
- JSP页面的内容
- 拷贝静态页面中的源代码到JSP中
- 包含进来的公共资源
- <%@ include file ="../public/common.jspf" %>
- 把../ 替换成 ${pageContext.request.contextPath}/
- 修改页面
1. 创建实体
bean方法,并且添加get,set方法
package cn.itcast.oa.domain; import java.util.HashSet; import java.util.Set; /** * 用户 * @author tyg * */ public class User { <span style="white-space:pre"> </span>private Long id; <span style="white-space:pre"> </span>private Department department; <span style="white-space:pre"> </span>private Set<Role> roles = new HashSet<Role>(); <span style="white-space:pre"> </span>private String loginName; // 登录名 <span style="white-space:pre"> </span>private String password; // 密码 <span style="white-space:pre"> </span>private String name; // 真实姓名 <span style="white-space:pre"> </span>private String gender; // 性别 <span style="white-space:pre"> </span>private String phoneNumber; // 电话号码 <span style="white-space:pre"> </span>private String email; // 电子邮件 <span style="white-space:pre"> </span>private String description; // 说明 <span style="white-space:pre"> </span>public Long getId() { <span style="white-space:pre"> </span>return id; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public void setId(Long id) { <span style="white-space:pre"> </span>this.id = id; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public Department getDepartment() { <span style="white-space:pre"> </span>return department; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public void setDepartment(Department department) { <span style="white-space:pre"> </span>this.department = department; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public Set<Role> getRoles() { <span style="white-space:pre"> </span>return roles; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public void setRoles(Set<Role> roles) { <span style="white-space:pre"> </span>this.roles = roles; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public String getLoginName() { <span style="white-space:pre"> </span>return loginName; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public void setLoginName(String loginName) { <span style="white-space:pre"> </span>this.loginName = loginName; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public String getPassword() { <span style="white-space:pre"> </span>return password; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public void setPassword(String password) { <span style="white-space:pre"> </span>this.password = password; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public String getName() { <span style="white-space:pre"> </span>return name; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public void setName(String name) { <span style="white-space:pre"> </span>this.name = name; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public String getGender() { <span style="white-space:pre"> </span>return gender; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public void setGender(String gender) { <span style="white-space:pre"> </span>this.gender = gender; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public String getPhoneNumber() { <span style="white-space:pre"> </span>return phoneNumber; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public void setPhoneNumber(String phoneNumber) { <span style="white-space:pre"> </span>this.phoneNumber = phoneNumber; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public String getEmail() { <span style="white-space:pre"> </span>return email; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public void setEmail(String email) { <span style="white-space:pre"> </span>this.email = email; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public String getDescription() { <span style="white-space:pre"> </span>return description; <span style="white-space:pre"> </span>} <span style="white-space:pre"> </span>public void setDescription(String description) { <span style="white-space:pre"> </span>this.description = description; <span style="white-space:pre"> </span>} }
Hbm的方法确定
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.itcast.oa.domain"> <span style="white-space:pre"> </span><class name="User" table="itcast_user"> <span style="white-space:pre"> </span><id name="id"> <generator class="native"/> <span style="white-space:pre"> </span></id> <span style="white-space:pre"> </span><property name="loginName"/> <span style="white-space:pre"> </span><property name="password"/> <span style="white-space:pre"> </span><property name="name"/> <span style="white-space:pre"> </span><property name="gender" /> <span style="white-space:pre"> </span><property name="phoneNumber"/> <span style="white-space:pre"> </span><property name="email"/> <span style="white-space:pre"> </span><property name="description"/> <span style="white-space:pre"> </span> <span style="white-space:pre"> </span><!-- department属性,本类与Department的多对一 --> <span style="white-space:pre"> </span><many-to-one name="department" class="Department" column="departmentId"></many-to-one> <span style="white-space:pre"> </span><!-- roles属性,本类与Role的多对多 --> <span style="white-space:pre"> </span><set name="roles" table="itcast_user_role"> <span style="white-space:pre"> </span><key column="userId"></key> <span style="white-space:pre"> </span><many-to-many class="Role" column="roleId"></many-to-many> <span style="white-space:pre"> </span></set> <span style="white-space:pre"> </span> <span style="white-space:pre"> </span></class> <span style="white-space:pre"> </span> </hibernate-mapping>
二、ACTION方法,相应的方法
package cn.itcast.oa.view.action; import java.util.HashSet; import java.util.List; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import cn.itcast.oa.base.BaseAction; import cn.itcast.oa.domain.Department; import cn.itcast.oa.domain.Role; import cn.itcast.oa.domain.User; import cn.itcast.oa.util.DepartmentUtils; import com.opensymphony.xwork2.ActionContext; @Controller @Scope("prototype") public class UserAction extends BaseAction<User> { private Long departmentId; private Long[] roleIds; /** 列表 */ public String list() throws Exception { List<User> userList = userService.findAll(); ActionContext.getContext().put("userList", userList); return "list"; } /** 删除 */ public String delete() throws Exception { userService.delete(model.getId()); return "toList"; } /** 添加页面 */ public String addUI() throws Exception { // 准备数据:departmentList,显示为树状结构 List<Department> topList = departmentService.findTopList(); List<Department> departmentList = DepartmentUtils.getAllDepartments(topList); ActionContext.getContext().put("departmentList", departmentList); // 准备数据:roleList List<Role> roleList = roleService.findAll(); ActionContext.getContext().put("roleList", roleList); return "saveUI"; } /** 添加 */ public String add() throws Exception { // 1,新建对象并设置属性(也可以使用model) Department department = departmentService.getById(departmentId); model.setDepartment(department); List<Role> roleList = roleService.getByIds(roleIds); model.setRoles(new HashSet<Role>(roleList)); String passwdMD5 = DigestUtils.md5Hex("1234"); model.setPassword(passwdMD5); // 默认密码为1234,应使用MD5摘要 // 2,保存到数据库 userService.save(model); return "toList"; } /** 修改页面 */ public String editUI() throws Exception { // 准备数据:departmentList,显示为树状结构 List<Department> topList = departmentService.findTopList(); List<Department> departmentList = DepartmentUtils.getAllDepartments(topList); ActionContext.getContext().put("departmentList", departmentList); // 准备数据:roleList List<Role> roleList = roleService.findAll(); ActionContext.getContext().put("roleList", roleList); // 准备回显的数据 User user = userService.getById(model.getId()); ActionContext.getContext().getValueStack().push(user); if (user.getDepartment() != null) { departmentId = user.getDepartment().getId(); } if (user.getRoles().size() > 0) { roleIds = new Long[user.getRoles().size()]; int index = 0; for (Role role : user.getRoles()) { roleIds[index++] = role.getId(); } } return "saveUI"; } /** 修改 */ public String edit() throws Exception { // 1,从数据库中取出原对象 User user = userService.getById(model.getId()); // 2,设置要修改的属性 // >> 普通属性 user.setLoginName(model.getLoginName()); user.setName(model.getName()); user.setGender(model.getGender()); user.setPhoneNumber(model.getPhoneNumber()); user.setEmail(model.getEmail()); user.setDescription(model.getDescription()); // >> 所属部门 Department department = departmentService.getById(departmentId); user.setDepartment(department); // >> 关联的岗位 List<Role> roleList = roleService.getByIds(roleIds); user.setRoles(new HashSet<Role>(roleList)); // 3,更新到数据库 userService.update(user); return "toList"; } /** 初始化密码为“1234” */ public String initPassword() throws Exception { // 1,从数据库中取出原对象 User user = userService.getById(model.getId()); // 2,设置要修改的属性(要使用MD5摘要) String passwdMD5 = DigestUtils.md5Hex("1234"); user.setPassword(passwdMD5); // 3,更新到数据库 userService.update(user); return "toList"; } // ------- public Long getDepartmentId() { return departmentId; } public void setDepartmentId(Long departmentId) { this.departmentId = departmentId; } public Long[] getRoleIds() { return roleIds; } public void setRoleIds(Long[] roleIds) { this.roleIds = roleIds; } }
三、JSP页面,根据ACIOTN添加相应的实体,配置相应的structs.xml配置相应的内容
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" "http://struts.apache.org/dtds/struts-2.0.dtd"> <struts> <!-- 配置为开发模式 --> <constant name="struts.devMode" value="true" /> <!-- 配置扩展名为action --> <constant name="struts.action.extension" value="action" /> <!-- 配置主题 --> <constant name="struts.ui.theme" value="simple" /> <package name="default" namespace="/" extends="struts-default"> <!-- 测试用的action,当与Spring整合后,class属性写的就是Spring中bean的名称 --> <action name="test" class="testAction"> <result name="success">/test.jsp</result> </action> <!-- 岗位管理 --> <action name="roleAction_*" class="roleAction" method="{1}"> <result name="list">/WEB-INF/jsp/roleAction/list.jsp</result> <result name="addUI">/WEB-INF/jsp/roleAction/addUI.jsp</result> <result name="editUI">/WEB-INF/jsp/roleAction/editUI.jsp</result> <result name="toList" type="redirectAction">roleAction_list</result> </action> <!-- 部门管理 --> <action name="departmentAction_*" class="departmentAction" method="{1}"> <result name="list">/WEB-INF/jsp/departmentAction/list.jsp</result> <result name="saveUI">/WEB-INF/jsp/departmentAction/saveUI.jsp</result> <result name="toList" type="redirectAction">departmentAction_list?parentId=${parentId}</result> </action> <strong><!-- 用户管理 --> <action name="userAction_*" class="userAction" method="{1}"> <result name="list">/WEB-INF/jsp/userAction/list.jsp</result> <result name="saveUI">/WEB-INF/jsp/userAction/saveUI.jsp</result> <result name="toList" type="redirectAction">userAction_list</result> </action></strong> </package> </struts>
四、创建接口,创建实现类
package cn.itcast.oa.service; import cn.itcast.oa.base.BaseDao; import cn.itcast.oa.domain.User; public interface UserService extends BaseDao<User> { }
package cn.itcast.oa.service.impl; import org.springframework.stereotype.Service; import cn.itcast.oa.base.BaseDaoImpl; import cn.itcast.oa.domain.User; import cn.itcast.oa.service.UserService; @Service public class UserServiceImpl extends BaseDaoImpl<User> implements UserService{ }
package cn.itcast.oa.base; import java.lang.reflect.ParameterizedType; import java.util.Collections; import java.util.List; import javax.annotation.Resource; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.transaction.annotation.Transactional; // @Transactional注解可以被继承,即对子类也有效 @Transactional @SuppressWarnings("unchecked") public abstract class BaseDaoImpl<T> implements BaseDao<T> { @Resource private SessionFactory sessionFactory; protected Class<T> clazz; // 这是一个问题! public BaseDaoImpl() { // 通过反射得到T的真实类型 ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass(); this.clazz = (Class) pt.getActualTypeArguments()[0]; System.out.println("clazz = " + clazz.getName()); } public void save(T entity) { getSession().save(entity); } public void update(T entity) { getSession().update(entity); } public void delete(Long id) { Object obj = getSession().get(clazz, id); getSession().delete(obj); } public T getById(Long id) { if (id == null) { return null; } return (T) getSession().get(clazz, id); } public List<T> getByIds(Long[] ids) { if (ids == null || ids.length == 0) { return Collections.EMPTY_LIST; } return getSession().createQuery(// "FROM " + clazz.getSimpleName() + " WHERE id IN(:ids)")// .setParameterList("ids", ids)// .list(); } public List<T> findAll() { return getSession().createQuery(// "FROM " + clazz.getSimpleName())// .list(); } /** * 获取当前可用的Session * * @return */ protected Session getSession() { return sessionFactory.getCurrentSession(); } }
五、添加ACTION,添加事务
package cn.itcast.oa.view.action; import java.util.HashSet; import java.util.List; import org.apache.commons.codec.digest.DigestUtils; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import cn.itcast.oa.base.BaseAction; import cn.itcast.oa.domain.Department; import cn.itcast.oa.domain.Role; import cn.itcast.oa.domain.User; import cn.itcast.oa.util.DepartmentUtils; import com.opensymphony.xwork2.ActionContext; @Controller @Scope("prototype") public class UserAction extends BaseAction<User> { private Long departmentId; private Long[] roleIds; /** 列表 */ public String list() throws Exception { List<User> userList = userService.findAll(); ActionContext.getContext().put("userList", userList); return "list"; } /** 删除 */ public String delete() throws Exception { userService.delete(model.getId()); return "toList"; } /** 添加页面 */ public String addUI() throws Exception { // 准备数据:departmentList,显示为树状结构 List<Department> topList = departmentService.findTopList(); List<Department> departmentList = DepartmentUtils.getAllDepartments(topList); ActionContext.getContext().put("departmentList", departmentList); // 准备数据:roleList List<Role> roleList = roleService.findAll(); ActionContext.getContext().put("roleList", roleList); return "saveUI"; } /** 添加 */ public String add() throws Exception { // 1,新建对象并设置属性(也可以使用model) Department department = departmentService.getById(departmentId); model.setDepartment(department); List<Role> roleList = roleService.getByIds(roleIds); model.setRoles(new HashSet<Role>(roleList)); String passwdMD5 = DigestUtils.md5Hex("1234"); model.setPassword(passwdMD5); // 默认密码为1234,应使用MD5摘要 // 2,保存到数据库 userService.save(model); return "toList"; } /** 修改页面 */ public String editUI() throws Exception { // 准备数据:departmentList,显示为树状结构 List<Department> topList = departmentService.findTopList(); List<Department> departmentList = DepartmentUtils.getAllDepartments(topList); ActionContext.getContext().put("departmentList", departmentList); // 准备数据:roleList List<Role> roleList = roleService.findAll(); ActionContext.getContext().put("roleList", roleList); // 准备回显的数据 User user = userService.getById(model.getId()); ActionContext.getContext().getValueStack().push(user); if (user.getDepartment() != null) { departmentId = user.getDepartment().getId(); } if (user.getRoles().size() > 0) { roleIds = new Long[user.getRoles().size()]; int index = 0; for (Role role : user.getRoles()) { roleIds[index++] = role.getId(); } } return "saveUI"; } /** 修改 */ public String edit() throws Exception { // 1,从数据库中取出原对象 User user = userService.getById(model.getId()); // 2,设置要修改的属性 // >> 普通属性 user.setLoginName(model.getLoginName()); user.setName(model.getName()); user.setGender(model.getGender()); user.setPhoneNumber(model.getPhoneNumber()); user.setEmail(model.getEmail()); user.setDescription(model.getDescription()); // >> 所属部门 Department department = departmentService.getById(departmentId); user.setDepartment(department); // >> 关联的岗位 List<Role> roleList = roleService.getByIds(roleIds); user.setRoles(new HashSet<Role>(roleList)); // 3,更新到数据库 userService.update(user); return "toList"; } /** 初始化密码为“1234” */ public String initPassword() throws Exception { // 1,从数据库中取出原对象 User user = userService.getById(model.getId()); // 2,设置要修改的属性(要使用MD5摘要) String passwdMD5 = DigestUtils.md5Hex("1234"); user.setPassword(passwdMD5); // 3,更新到数据库 userService.update(user); return "toList"; } // ------- public Long getDepartmentId() { return departmentId; } public void setDepartmentId(Long departmentId) { this.departmentId = departmentId; } public Long[] getRoleIds() { return roleIds; } public void setRoleIds(Long[] roleIds) { this.roleIds = roleIds; } }
七、填空
添加ACTION方法,新增Service业务的方法,添加JSP方法,添加DAO方法。
时间: 2024-10-10 15:46:17