zoukankan      html  css  js  c++  java
  • 实战3--设计管理模块,整合!!!

    1. 所有dao和daoimpl模块都不用, 加上 @Deprecated

    2. 建立DaoSupport类和DaoSupportImpl类

        DaoSupport.java     

    package cn.itcast.oa.base;
    import java.util.List;
    public interface DaoSupport<T> {
    	void save(T entity);
    	void delete(Long id);
    	void update(T entity);
    	T getById(Long id);
    	List<T> getByIds(Long[] ids);
    	List<T> findAll();
    }
    

       DaoSupportImpl.java     

    package cn.itcast.oa.base;
    import java.lang.reflect.ParameterizedType;
    import java.util.List;
    import javax.annotation.Resource;
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    @SuppressWarnings("unchecked") public class DaoSupportImpl<T> implements DaoSupport<T> { @Resource private SessionFactory sessionFactory; private Class<T> clazz = null; public DaoSupportImpl(){ //使用反射技术得到T的真实类型 ParameterizedType pt = (ParameterizedType)this.getClass().getGenericSuperclass();//获取当前new的对象的泛型的父类类型 this.clazz = (Class<T>)pt.getActualTypeArguments()[0]; System.out.println("clazz===>"+clazz.getName()); System.out.println("clazz===>"+clazz.getSimpleName()); } protected Session getSession() { return sessionFactory.getCurrentSession(); } public void save(T entity) { getSession().save(entity); } public void update(T entity) { getSession().update(entity); } public void delete(Long id) { Object obj = getById(id); if (obj != null) { getSession().delete(obj); } } public T getById(Long id) { if(id == null) return null; else return (T) getSession().get(clazz, id); } public List<T> getByIds(Long[] ids) { 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(); } }

     3. 抽取BaseAction, 这样每个action都可以专注写自己的方法   

    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>{	
    	protected T model ;	
    	public BaseAction(){		
    		try {
    			//通过反射活的model的真实类型
    			ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
    			Class<T> clazz = (Class<T>)pt.getActualTypeArguments()[0];
    			//通过反射创建model的实例
    			model = clazz.newInstance();
    		} catch (Exception e) {
    			 throw new RuntimeException();
    		} 
    	}
    	public T getModel() {		
    		return model;
    	}
    	
    	//******************service实例的声明******************
    	@Resource
    	protected RoleService roleService;
    	@Resource
    	protected DepartmentService departmentService;
    	@Resource
    	protected UserService userService;
    }
    

    整合完毕!!!

    增加新模块的步骤: 

    一. 创建Action的准备

    1. 写新的action, UserAction.java,

        1) extends BaseAction

        2) @Controller  @Scope("prototype")

    2. 定义出Action的方法, 写出方法名, 作用, 返回值    

    /** 列表 */
    	public String list() throws Exception {
    		return "list";
    	}
    
    	/** 删除 */
    	public String delete() throws Exception {
    		return "toList";
    	}
    
    	/** 添加页面 */
    	public String addUI() throws Exception {
    		return "saveUI";
    	}
    
    	/** 添加 */
    	public String add() throws Exception {
    		return "toList";
    	}
    
    	/** 修改页面 */
    	public String editUI() throws Exception {
    		return "saveUI";
    	}
    
    	/** 修改 */
    	public String edit() throws Exception {
    		return "toList";
    	}
            /** 初始化密码1234 **/
    	public String initPassword() throws Exception {
    		return "toList";
    	}    
    

    3. 创建所用到的jsp页面(list.jsp, saveUI.jsp)

    4. struts.xml配置    

    <!-- 用户管理 -->
    <action name="user_*" 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">user_list?parentId=${parentId}</result>
    </action>
    

      

    二. 准备service

    1. 创建接口UserService.java,    extends DaoSupport<User>   

    package cn.itcast.oa.service;
    import cn.itcast.oa.base.DaoSupport;
    import cn.itcast.oa.domain.User;
    public interface UserService  extends DaoSupport<User>{
    }
    

    2. 创建实现类 UserServiceImpl.java  ,  extends DaoSupportImpl<User> implements UserService

    3. 配置: 在UserServiceImpl上写注解 @Service  @Transactional

    package cn.itcast.oa.service.impl;
    
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import cn.itcast.oa.base.DaoSupportImpl;
    import cn.itcast.oa.domain.User;
    import cn.itcast.oa.service.UserService;
    
    @Service
    @Transactional
    public class UserServiceImpl extends DaoSupportImpl<User> implements UserService{
    
    }
    

    4. BaseAction里写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>{	
    	protected T model ;	
    	public BaseAction(){		
    		try {
    			//通过反射活的model的真实类型
    			ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
    			Class<T> clazz = (Class<T>)pt.getActualTypeArguments()[0];
    			//通过反射创建model的实例
    			model = clazz.newInstance();
    		} catch (Exception e) {
    			 throw new RuntimeException();
    		} 
    	}
    	public T getModel() {		
    		return model;
    	}
    	
    	//******************service实例的声明******************
    	@Resource
    	protected RoleService roleService;
    	@Resource
    	protected DepartmentService departmentService;
    	@Resource
    	protected UserService userService;
    }
    

      

    三. 填空

    1. 写Action方法

       UserAction.java

       

    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);
    
    		// 准备岗位
    		List<Role> roleList = roleService.findAll();
    		ActionContext.getContext().put("roleList", roleList);
    		return "saveUI";
    	}
    
    	/** 添加 */
    	public String add() throws Exception {
    		// 封装到对象中 (model是实体类型时, 可以使用model, 但要设置未封装的属性)
    		model.setDepartment(departmentService.getById(departmentId));
    		List<Role> roleList = roleService.getByIds(roleIds);
    		model.setRoles(new HashSet<Role>(roleList));
    
    		// 设置密码为1234, 要使用MD5摘要()
    		String md5Digest = DigestUtils.md5Hex("1234");
    		model.setPassword(md5Digest);
    		
    		// 保存到数据库
    		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);
    
    		// 准备岗位
    		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() != null) {
    			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 {
    		// 从数据库中取出原对象
    		User user = userService.getById(model.getId());
    
    		// 设置要修改的属性
    		user.setLoginName(model.getLoginName());
    		user.setName(model.getName());
    		user.setGender(model.getGender());
    		user.setPhoneNumber(model.getPhoneNumber());
    		user.setEmail(model.getEmail());
    		user.setDescription(model.getDescription());
    		user.setDepartment(departmentService.getById(departmentId));
    		List<Role> roleList = roleService.getByIds(roleIds);
    		user.setRoles(new HashSet<Role>(roleList));
    		// 更新到数据库
    		userService.update(user);
    		return "toList";
    	}
    
    	/** 初始化密码1234 **/
    	public String initPassword() throws Exception {
    		// 从数据库中取出原对象
    		User user = userService.getById(model.getId());
    		// 设置要修改的属性
    		String md5Digest = DigestUtils.md5Hex("1234");
    		user.setPassword(md5Digest);
    		// 更新到数据库,使用MD5摘要
    		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;
    	}
    }
    

      

    2. 新增service方法

    3. jsp页面内容

        list.jsp

        

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
    <%String path = request.getContextPath();%>
    <html>
    <head>
        <title>用户列表</title>
         <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
         <script language="javascript" type="text/javascript" src=<%=path%>/script/jquery.js"></script>
         <script language="javascript" type="text/javascript" src=<%=path%>/script/pageCommon.js"></script>
         <script language="javascript" type="text/javascript" src=<%=path%>/script/PageUtils.js"></script>
          <link type="text/css" rel="stylesheet" href="<%=path%>/style/blue/pageCommon.css"/>
        <script type="text/javascript">
        </script>
    </head>
    <body>
    
    <div id="Title_bar">
        <div id="Title_bar_Head"> 
            <div id="Title_Head"></div>
            <div id="Title"><!--页面标题-->
                <img border="0" width="13" height="13" src="${pageContext.request.contextPath}/style/images/title_arrow.gif"/> 用户管理
            </div>
            <div id="Title_End"></div>
        </div>
    </div>
    
    <div id="MainArea">
        <table cellspacing="0" cellpadding="0" class="TableStyle">
           
            <!-- 表头-->
            <thead>
                <tr align=center valign=middle id=TableTitle>
                    <td width="100">登录名</td>
                    <td width="100">姓名</td>
                    <td width="100">所属部门</td>
                    <td width="200">岗位</td>
                    <td>备注</td>
                    <td>相关操作</td>
                </tr>
            </thead>
            
            <!--显示数据列表-->
            <tbody id="TableData" class="dataContainer" datakey="userList">
            
            <s:iterator value="#userList">
                <tr class="TableDetail1 template">
                    <td>${loginName} </td>
                    <td>${name} </td>
                    <td>${department.name} </td>
                    <td>
                    	<s:iterator value="roles">
                    		${name}
                    	</s:iterator>
                    </td>
                    <td>${description} </td>
                    <td>
                    	<s:a action="user_delete?id=%{id}" onclick="return delConfirm()">删除</s:a>
                        <s:a action="user_editUI?id=%{id}">修改</s:a>
    					<s:a action="user_initPassword?id=%{id}" onclick="return window.confirm('您确定要初始化密码为1234吗?')">初始化密码</s:a>
                    </td>
                </tr>
            </s:iterator> 
                
            </tbody>
        </table>
        
        <!-- 其他功能超链接 -->
        <div id="TableTail">
            <div id="TableTail_inside">
                <s:a action="user_addUI"><img src="${pageContext.request.contextPath}/style/images/createNew.png" /></s:a>
            </div>
        </div>
    </div>
    
    </body>
    </html>
    

      saveUI.jsp

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%@ taglib prefix="s" uri="/struts-tags" %>
    <%String path = request.getContextPath();%>
    <html>
    <head>
    	<title>用户信息</title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
           <script language="javascript" type="text/javascript" src=<%=path%>/script/jquery.js"></script>
        <script language="javascript" type="text/javascript" src=<%=path%>/script/pageCommon.js"></script>
        <script language="javascript" type="text/javascript" src=<%=path%>/script/PageUtils.js"></script>
       
        <link type="text/css" rel="stylesheet" href="<%=path%>/style/blue/pageCommon.css"/>
        <script type="text/javascript">
        </script>
    </head>
    <body>
    
    <!-- 标题显示 -->
    <div id="Title_bar">
        <div id="Title_bar_Head">
            <div id="Title_Head"></div>
            <div id="Title"><!--页面标题-->
                <img border="0" width="13" height="13" src="<%=path%>/style/images/title_arrow.gif"/> 用户信息
            </div>
            <div id="Title_End"></div>
        </div>
    </div>
    
    <!--显示表单内容-->
    <div id=MainArea>
    
        <s:form action="user_%{id == null ? 'add' : 'edit'}">
        	<s:hidden name="id"></s:hidden>
            
            <div class="ItemBlock_Title1"><!-- 信息说明 --><div class="ItemBlock_Title1">
            	<img border="0" width="4" height="7" src="<%=path%>/style/blue/images/item_point.gif" /> 用户信息 </div> 
            </div>
            
            <!-- 表单内容显示 -->
            <div class="ItemBlockBorder">
                <div class="ItemBlock">
                    <table cellpadding="0" cellspacing="0" class="mainForm">
                        <tr><td width="100">所属部门</td>
                            <td>
                            	<s:select name="departmentId" cssClass="SelectStyle"
                            		list="#departmentList" listKey="id" listValue="name"
                            		headerKey="" headerValue="==请选择部门=="
                            	/>
                            </td>
                        </tr>
                        <tr><td>登录名</td>
                            <td><s:textfield name="loginName" cssClass="InputStyle"/> *
    							(登录名要唯一)
    						</td>
                        </tr>
                        <tr><td>姓名</td>
                            <td><s:textfield name="name" cssClass="InputStyle"/> *</td>
                        </tr>
    					<tr><td>性别</td>
                            <td>
                            	<%--
    							<s:radio name="gender" list="%{ #{'男':'男', '女':'女'} }"></s:radio>
    							<s:radio name="gender" list="#{'男':'男', '女':'女'}"></s:radio>
                            	 --%>
    							<s:radio name="gender" list="{'男', '女'}"></s:radio>
    
    						</td>
                        </tr>
    					<tr><td>联系电话</td>
                            <td><s:textfield name="phoneNumber" cssClass="InputStyle"/></td>
                        </tr>
                        <tr><td>E-mail</td>
                            <td><s:textfield name="email" cssClass="InputStyle"/></td>
                        </tr>
                        <tr><td>备注</td>
                            <td><s:textarea name="description" cssClass="TextareaStyle"></s:textarea></td>
                        </tr>
                    </table>
                </div>
            </div>
            
    		<div class="ItemBlock_Title1"><!-- 信息说明 --><div class="ItemBlock_Title1">
            	<img border="0" width="4" height="7" src="<%=path%>/style/blue/images/item_point.gif" /> 岗位设置 </div> 
            </div>
            
            <!-- 表单内容显示 -->
            <div class="ItemBlockBorder">
                <div class="ItemBlock">
                    <table cellpadding="0" cellspacing="0" class="mainForm">
                        <tr>
    						<td width="100">岗位</td>
                            <td>
                            	<s:select name="roleIds" cssClass="SelectStyle"
                            		multiple="true" size="10" 
                            		list="#roleList" listKey="id" listValue="name"
                            	/>
    							按住Ctrl键可以多选或取消选择
                            </td>
                        </tr>
                    </table>
                </div>
            </div>		
    		
            <!-- 表单操作 -->
            <div id="InputDetailBar">
                <input type="image" src="<%=path%>/style/images/save.png"/>
                <a href="javascript:history.go(-1);"><img src="<%=path%>/style/images/goBack.png"/></a>
            </div>
        </s:form>
    </div>
    
    <div class="Description">
    	说明:<br />
    	1,用户的登录名要唯一,在填写时要同时检测是否可用。<br />
    	2,新建用户后,密码被初始化为"1234"。<br />
    	3,密码在数据库中存储的是MD5摘要(不是存储明文密码)。<br />
    	4,用户登录系统后可以使用“个人设置→修改密码”功能修改密码。<br />
    	5,新建用户后,会自动指定默认的头像。用户可以使用“个人设置→个人信息”功能修改自已的头像<br />
    	6,修改用户信息时,登录名不可修改。
    </div>
    
    </body>
    </html>
    

      

      

      

  • 相关阅读:
    iot 表索引dump《2》
    heap表和iot表排序规则不同
    Cannot complete the install because one or more required items could not be found.
    iot表输出按主键列排序,heap表不是
    iot 表主键存放所有数据,且按数据插入顺序排序
    iot表和heap表排序规则不同
    org.eclipse.graphiti.ui.editor.DiagramEditorInput.
    Oracle 排序规则
    perl 异步超时 打印错误
    14.6.3 Grouping DML Operations with Transactions 组DML操作
  • 原文地址:https://www.cnblogs.com/wujixing/p/5511045.html
Copyright © 2011-2022 走看看