SSH-BOS项目:用户管理模块(完善)

UserAction:

package com.xushuai.bos.web.action;

import java.io.IOException;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.opensymphony.xwork2.ActionContext;
import com.xushuai.bos.entity.User;
import com.xushuai.bos.service.UserService;
import com.xushuai.bos.utils.BOSUtils;
import com.xushuai.bos.utils.MD5Utils;

import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;

@Controller("userAction")
@Scope("prototype")
public class UserAction extends BaseAction<User> {

	//属性驱动 接收验证码参数
	private String checkcode;
	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
	
	//接收角色ID
	private String[] roleIds;
	public String[] getRoleIds() {
		return roleIds;
	}
	public void setRoleIds(String[] roleIds) {
		this.roleIds = roleIds;
	}
	
	//接收要删除的用户ID
	private String ids;
	public String getIds() {
		return ids;
	}
	public void setIds(String ids) {
		this.ids = ids;
	}

	@Autowired
	@Qualifier("userService")
	private UserService userService;
	public void setUserService(UserService userService) {
		this.userService = userService;
	}


	/**
	 * 登录(Shiro认证)
	 * @return
	 */
	public String login(){
		//从session中获取生成的验证码
		String vcode = (String) ActionContext.getContext().getSession().get("key");
		//校验验证码
		if(StringUtils.isNotBlank(checkcode) && vcode.equals(checkcode)){//验证码正确
			Subject subject = SecurityUtils.getSubject();
			AuthenticationToken token = new UsernamePasswordToken(model.getUsername(), MD5Utils.md5(model.getPassword()));
			try {
				subject.login(token);
				User user = (User) subject.getPrincipal();
				ActionContext.getContext().getSession().put("user", user);
			} catch (UnknownAccountException e1) {
				e1.printStackTrace();
				this.addActionError("用户名不存在!");
				return LOGIN;
			} catch (IncorrectCredentialsException e2) {
				e2.printStackTrace();
				this.addActionError("密码错误!");
				return LOGIN;
			}
			return HOME;
		}else{//验证码错误
			this.addActionError("验证码错误");
			return LOGIN;
		}
	}
	
	
	/**
	 * 退出
	 * @return
	 */
	public String logout(){
		ServletActionContext.getRequest().getSession().invalidate();
		return LOGIN;
	}
	
	/**
	 * 修改密码 
	 * @return
	 * @throws IOException 
	 */
	public String editPassword() throws IOException{
		//修改密码情况的标志,成功:1
		String f = "1";
		User user = BOSUtils.getLoginUser();
		user.setPassword(model.getPassword());
		try {
			userService.editPassword(user);
		} catch (Exception e) {//修改失败
			f = "0";
			e.printStackTrace();
		}
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("text/html;charset=UTF-8");
		//返回修改密码的标志
		response.getWriter().print(f);
		
		return NONE;
	}
	
	/**
	 * 添加用户
	 * @return
	 */
	public String add(){
		userService.save(model, roleIds);
		
		return LIST;
	}
	
	/**
	 * 分页查询用户信息
	 * @return
	 */
	public String pageQuery(){
		userService.pageQuery(pageBean);
		BOSUtils.writerJson(pageBean, new String[]{"currentPage","pageSize","criteria","users","functions","noticebills"});
		
		return NONE;
	}
	
	/**
	 * 删除指定用户(可以为多个)
	 * @return
	 */
	public String delete(){
		userService.delete(ids);
		
		return LIST;
	}
	
	/**
	 * 加载指定用户
	 * @return
	 * @throws IOException 
	 */
	public String load() throws IOException{
		User user = userService.load(model.getId());
		Set roles = user.getRoles();
		HttpServletResponse response = BOSUtils.getResponse();
		response.setContentType("text/json;charset=UTF-8");
		JsonConfig jsonConfig = new JsonConfig();
		//去除不需要返回的值
		jsonConfig.setExcludes(new String[]{"noticebills","functions","users"});
		//将查询结果转换为json串
		String json = JSONArray.fromObject(roles, jsonConfig).toString();
		response.getWriter().print(json);
		
		return NONE;
	}
	
	/**
	 * 修改用户信息
	 * @return
	 */
	public String edit(){
		userService.edit(model, roleIds);
		
		return LIST;
	}
	
	/**
	 * 重置用户密码(可以为多个)
	 * @return
	 */
	public String resetPassword(){
		userService.resetPassword(ids);
		
		return LIST;
	}
	
}

UserService、UserServiceImpl:

package com.xushuai.bos.service;

import com.xushuai.bos.entity.User;
import com.xushuai.bos.utils.PageBean;

public interface UserService {

	/**
	 * 登录
	 * @param model
	 * @return
	 */
	User login(User model);

	/**
	 * 修改密码
	 * @param user
	 */
	void editPassword(User user);

	/**
	 * 新增用户
	 * @param model
	 */
	void save(User model, String[] roleIds);

	/**
	 * 分页查询用户信息
	 * @param pageBean
	 */
	void pageQuery(PageBean pageBean);

	/**
	 * 删除指定用户(可以为多个)
	 * @param ids
	 */
	void delete(String ids);

	/**
	 * 加载指定用户
	 * @param id
	 * @return
	 */
	User load(String id);

	/**
	 * 修改用户信息
	 * @param model
	 */
	void edit(User model, String[] roleIds);

	/**
	 * 重置用户密码(可以为多个)
	 * @param ids
	 */
	void resetPassword(String ids);

}
package com.xushuai.bos.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xushuai.bos.dao.UserDao;
import com.xushuai.bos.entity.Role;
import com.xushuai.bos.entity.User;
import com.xushuai.bos.service.UserService;
import com.xushuai.bos.utils.MD5Utils;
import com.xushuai.bos.utils.PageBean;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {
	
	//依赖注入
	@Autowired
	@Qualifier("userDao")
	private UserDao userDao;
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}


	@Override
	public User login(User user) {		
		//使用MD5加密 密码
		String password = MD5Utils.md5(user.getPassword());
		return userDao.findByUsernameAndPassword(user.getUsername(), password);
	}


	@Override
	public void editPassword(User user) {
		//使用MD5加密 密码,并调用dao#update(user)修改数据
		user.setPassword(MD5Utils.md5(user.getPassword()));
		userDao.update(user);
	}


	@Override
	public void save(User model, String[] roleIds) {
		model.setPassword(MD5Utils.md5(model.getPassword()));
		userDao.save(model);
		Role role = null;
		if(roleIds != null && roleIds.length != 0){
			for (String id : roleIds) {
				role = new Role(id);
				model.getRoles().add(role);
			}
		}
	}


	@Override
	public void pageQuery(PageBean pageBean) {
		userDao.findByPage(pageBean);
	}


	@Override
	public void delete(String ids) {
		if(StringUtils.isNotBlank(ids)){
			String[] strings = ids.split(",");
			for (String id : strings) {
				User user = userDao.findById(id);
				userDao.delete(user);
			}
		}
		
	}


	@Override
	public User load(String id) {
		return userDao.findById(id);
	}


	@Override
	public void edit(User model, String[] roleIds) {
		//查询出数据库中的User对象
		User _user = userDao.findById(model.getId());
		_user.setBirthday(model.getBirthday());
		_user.setGender(model.getGender());
		_user.setSalary(model.getSalary());
		_user.setStation(model.getStation());
		_user.setTelephone(model.getTelephone());
		//清空角色信息
		_user.getRoles().clear();
		if(roleIds != null && roleIds.length != 0){
			Role role = null;
			for (String id : roleIds) {
				role = new Role(id);
				_user.getRoles().add(role);
			}
		}
		userDao.update(_user);
	}


	@Override
	public void resetPassword(String ids) {
		if(StringUtils.isNotBlank(ids)){
			String[] strings = ids.split(",");
			User _user = null;
			for (String id : strings) {
				_user = userDao.findById(id);
				if(_user != null){
					_user.setPassword(MD5Utils.md5("123456"));
				}
			}
			userDao.update(_user);
		}
	}

}

struts.xml(更改UserAction):

		<!-- 用户模块 -->
		<action name="UserAction_*" class="userAction" method="{1}">
			<result name="login">/login.jsp</result>
			<result name="home">/index.jsp</result>
			<result name="list">/WEB-INF/pages/admin/userlist.jsp</result>
		</action>

页面(userlist.jsp、userinfo.jsp):

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<!-- 导入jquery核心类库 -->
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/jquery-1.8.3.js"></script>
<!-- 导入easyui类库 -->
<link rel="stylesheet" type="text/css"
	href="${pageContext.request.contextPath }/js/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css"
	href="${pageContext.request.contextPath }/js/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css"
	href="${pageContext.request.contextPath }/js/easyui/ext/portal.css">
<link rel="stylesheet" type="text/css"
	href="${pageContext.request.contextPath }/css/default.css">	
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/easyui/jquery.easyui.min.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/easyui/ext/jquery.portal.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/easyui/ext/jquery.cookie.js"></script>
<script
	src="${pageContext.request.contextPath }/js/easyui/locale/easyui-lang-zh_CN.js"
	type="text/javascript"></script>
<script type="text/javascript">
	// 工具栏
	var toolbar = [ {
		id : 'button-add',
		text : '新增',
		iconCls : 'icon-add',
		handler : doAdd
	}, {
		id : 'button-delete',
		text : '删除',
		iconCls : 'icon-cancel',
		handler : doDelete
	}, {
		id : 'button-reset',
		text : '重置密码',
		iconCls : 'icon-save',
		handler : function(){
			var rows = $("#grid").datagrid('getSelections');
			if(rows.length == 0){
				$.messager.alert('提示信息','请选择您要重置密码的用户','warning');
			}else{
				$.messager.confirm('提示信息','确定要重置这些用户的密码?',function(r){
					if(r){
						//定义一个数组,存放要删除功能的ID值
						Array :arr = new Array();
						for(var i = 0; i < rows.length; i++){
							//将需要删除的权限ID添加到数组中
							arr.push(rows[i].id);
						}
						//将数组格式化成一个字符串,用逗号分隔每个ID值
						var ids = arr.join(",");
						$.post('UserAction_resetPassword.action',{'ids':ids},function(data){
							if(data == '0'){
								$.messager.alert('提示信息','重置密码失败!','error');
							}
						});
					}
				});
			}
		}
	}, {
		id : 'button-clear',
		text : '取消选中',
		handler : doClear
	}];
	//定义冻结列
	var frozenColumns = [ [ {
		field : 'id',
		checkbox : true,
		rowspan : 2
	}, {
		field : 'username',
		title : '名称',
		width : 80,
		rowspan : 2
	} ] ];


	// 定义标题栏
	var columns = [ [ {
		field : 'gender',
		title : '性别',
		width : 60,
		rowspan : 2,
		align : 'center'
	}, {
		field : 'birthday',
		title : '生日',
		width : 180,
		rowspan : 2,
		align : 'center'
	}, {
		title : '其他信息',
		colspan : 2
	}, {
		field : 'telephone',
		title : '电话',
		width : 240,
		rowspan : 2
	} ], [ {
		field : 'station',
		title : '单位',
		width : 180,
		align : 'center'
	}, {
		field : 'salary',
		title : '工资',
		width : 80,
		align : 'right'
	} ] ];
	$(function(){
		// 初始化 datagrid
		// 创建grid
		$('#grid').datagrid( {
			iconCls : 'icon-forward',
			fit : true,
			border : false,
			rownumbers : true,
			striped : true,
			toolbar : toolbar,
			url : "UserAction_pageQuery.action",
			pageList: [15,20,28],
			pageSize: 28,
			pagination : true,
			fit:true,
			idField : 'id', 
			frozenColumns : frozenColumns,
			columns : columns,
			onDblClickRow : doDblClickRow
		});
		
		$("body").css({visibility:"visible"});
		
		// 修改用户窗口
		$('#editUserWindow').window({
	        title: '编辑权限',
	        width: 800,
	        modal: true,
	        shadow: true,
	        closed: true,
	        height: 600,
	        resizable:false
	    });
		//绑定修改按钮单击事件
		$("#edit").click(function(){
			if($("#form").form('validate')){
				$("#form").submit();
			}
		});
		
	});
	// 双击
	function doDblClickRow(rowIndex, rowData) {
		$('#editUserWindow').window('open');
		$('#editUserWindow').form('load',rowData);
		
		$.post('UserAction_load.action',{'id':rowData.id},function(data){
			var checkboxs = $("input[name=roleIds]");
			for(var i=0;i<data.length;i++){
				$("#check"+data[i].id).attr('checked','true');
			}
		});
	}
	
	function doAdd() {
		location.href="${pageContext.request.contextPath}/page_admin_userinfo.action";
	}

	
	function doClear(){
		$('#grid').datagrid('clearSelections');
	}

	function doDelete() {
		var rows = $("#grid").datagrid('getSelections');
		if(rows.length == 0){
			$.messager.alert('提示信息','请选择您要删除的用户','warning');
		}else{
			$.messager.confirm('提示信息','确定要执行删除操作吗?',function(r){
				if(r){
					//定义一个数组,存放要删除功能的ID值
					Array :arr = new Array();
					for(var i = 0; i < rows.length; i++){
						//将需要删除的权限ID添加到数组中
						arr.push(rows[i].id);
					}
					//将数组格式化成一个字符串,用逗号分隔每个ID值
					var ids = arr.join(",");
					location.href = "UserAction_delete.action?ids=" + ids;
				}
			});
		}
	}
	
</script>		
</head>
<body class="easyui-layout" style="visibility:hidden;">
    <div region="center" border="false">
    	<table id="grid"></table>
	</div>
	<div class="easyui-window" title="对用户信息进行修改" id="editUserWindow" 
			collapsible="false" minimizable="false" maximizable="false" style="top:20px;left:200px">
		<div region="north" style="height:31px;overflow:hidden;" split="false" border="false" >
		<div class="datagrid-toolbar">
			<a id="edit" icon="icon-save" href="#" class="easyui-linkbutton" plain="true" >修改</a>
		</div>
	</div>
    <div region="center" style="overflow:auto;padding:5px;" border="false">
       <form id="form" method="post" action="UserAction_edit.action" >
       		<input type="hidden" name="id">
           <table class="table-edit"  width="95%" align="center">
           		
				<tr class="title"><td colspan="4">其他信息</td></tr>
	           	<tr><td>工资:</td><td><input type="text" name="salary" id="salary" class="easyui-numberbox" /></td>
					<td>生日:</td><td><input type="text" name="birthday" id="birthday" class="easyui-datebox" /></td></tr>
	           	<tr><td>性别:</td><td>
	           		<select name="gender" id="gender" editable="false" class="easyui-combobox" style="width: 150px;">
	           			<option value="">请选择</option>
	           			<option value="男">男</option>
	           			<option value="女">女</option>
	           		</select>
	           	</td>
					<td>单位:</td><td>
					<select name="station" id="station" class="easyui-combobox" style="width: 150px;">
	           			<option value="">请选择</option>
	           			<option value="总公司">总公司</option>
	           			<option value="分公司">分公司</option>
	           			<option value="厅点">厅点</option>
	           			<option value="基地运转中心">基地运转中心</option>
	           			<option value="营业所">营业所</option>
	           		</select>
				</td></tr>
				<tr>
					<td>联系电话</td>
					<td colspan="3">
						<input type="text" name="telephone" id="telephone" class="easyui-validatebox" required="true" />
					</td>
				</tr>
				<tr>
	           		<td>选择角色:</td>
	           		<td colspan="3" id="roleItem">
	           		
	           			<script type="text/javascript">
	           				$(function(){
	           					$.post('RoleAction_ajaxList.action',function(data){
	           						//遍历json数组
									for(var i=0;i<data.length;i++){
										var id = data[i].id;
										var name = data[i].name;
										//构造checkbox
										$("#roleItem").append('<input id="check'+id+'" type="checkbox" name="roleIds" '+
												' value="'+id+'"><label for="check'+id+'">'+name+'</label>        ');
									}
	           					});
	           				});
	           			</script>
	           		</td>
	           	</tr>
	           	<tr>
	           		<td>备注:</td>
	           		<td colspan="3">
	           			<textarea style="width:80%"></textarea>
	           		</td>
	           	</tr>
           </table>
       </form>
	</div>
	</div>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<!-- 导入jquery核心类库 -->
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/jquery-1.8.3.js"></script>
<!-- 导入easyui类库 -->
<link rel="stylesheet" type="text/css"
	href="${pageContext.request.contextPath }/js/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css"
	href="${pageContext.request.contextPath }/js/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css"
	href="${pageContext.request.contextPath }/js/easyui/ext/portal.css">
<link rel="stylesheet" type="text/css"
	href="${pageContext.request.contextPath }/css/default.css">	
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/easyui/jquery.easyui.min.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/easyui/ext/jquery.portal.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath }/js/easyui/ext/jquery.cookie.js"></script>
<script
	src="${pageContext.request.contextPath }/js/easyui/locale/easyui-lang-zh_CN.js"
	type="text/javascript"></script>
<script type="text/javascript">
	$(function(){
		$("body").css({visibility:"visible"});
		$('#save').click(function(){
			if($('#form').form('validate')){
				$('#form').submit();
			}
		});
	});
</script>	
</head>
<body class="easyui-layout" style="visibility:hidden;">
	<div region="north" style="height:31px;overflow:hidden;" split="false" border="false" >
		<div class="datagrid-toolbar">
			<a id="save" icon="icon-save" href="#" class="easyui-linkbutton" plain="true" >保存</a>
		</div>
	</div>
    <div region="center" style="overflow:auto;padding:5px;" border="false">
       <form id="form" method="post" action="UserAction_add.action" >
           <table class="table-edit"  width="95%" align="center">
           		<tr class="title"><td colspan="4">基本信息</td></tr>
	           	<tr><td>用户名:</td><td><input type="text" name="username" id="username" class="easyui-validatebox" required="true" /></td>
					<td>口令:</td><td><input type="password" name="password" id="password" class="easyui-validatebox" required="true" validType="minLength[5]" /></td></tr>
				<tr class="title"><td colspan="4">其他信息</td></tr>
	           	<tr><td>工资:</td><td><input type="text" name="salary" id="salary" class="easyui-numberbox" /></td>
					<td>生日:</td><td><input type="text" name="birthday" id="birthday" class="easyui-datebox" /></td></tr>
	           	<tr><td>性别:</td><td>
	           		<select name="gender" id="gender" editable="false" class="easyui-combobox" style="width: 150px;">
	           			<option value="">请选择</option>
	           			<option value="男">男</option>
	           			<option value="女">女</option>
	           		</select>
	           	</td>
					<td>单位:</td><td>
					<select name="station" id="station" class="easyui-combobox" style="width: 150px;">
	           			<option value="">请选择</option>
	           			<option value="总公司">总公司</option>
	           			<option value="分公司">分公司</option>
	           			<option value="厅点">厅点</option>
	           			<option value="基地运转中心">基地运转中心</option>
	           			<option value="营业所">营业所</option>
	           		</select>
				</td></tr>
				<tr>
					<td>联系电话</td>
					<td colspan="3">
						<input type="text" name="telephone" id="telephone" class="easyui-validatebox" required="true" />
					</td>
				</tr>
				<tr>
	           		<td>选择角色:</td>
	           		<td colspan="3" id="roleItem">
	           		
	           			<script type="text/javascript">
	           				$(function(){
	           					$.post('RoleAction_ajaxList.action',function(data){
	           						//遍历json数组
									for(var i=0;i<data.length;i++){
										var id = data[i].id;
										var name = data[i].name;
										//构造checkbox
										$("#roleItem").append('<input id="check'+id+'" type="checkbox" name="roleIds" '+
												' value="'+id+'"><label for="check'+id+'">'+name+'</label>        ');
									}
	           					});
	           				});
	           			</script>
	           		</td>
	           	</tr>
	           	<tr>
	           		<td>备注:</td>
	           		<td colspan="3">
	           			<textarea style="width:80%"></textarea>
	           		</td>
	           	</tr>
           </table>
       </form>
	</div>
</body>
</html>




猜你喜欢

转载自blog.csdn.net/qq1031893936/article/details/80010918