人员管理系统(使用struts)--逻辑代码

功能模块:

登录:

 

保存用户:

 

查看用户:

 

用户列表:

 

 

UserDao:

 

package cn.hcx.user.dao;

import java.util.List;

import cn.hcx.user.domain.User;

public interface UserDao {
	//根据登录名称获得用户对象
	User  getUserByLoginName(String loginName);
	// 根据查询条件获得用户列表
	List<User> getUserByCondition(User u);
	//保存用户对象
	void  saveUser(User u);
	//根据userid 获得user对象
	User getUserByUid(String id);
	
}


UserDaoImpl:

 

 

package cn.hcx.user.dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import cn.hcx.user.domain.User;

public class UserDaoImpl implements UserDao {
	private static QueryRunner qr = new QueryRunner(new ComboPooledDataSource());
	
	public User getUserByLoginName(String loginName) {
		//1 书写sql语句
		String sql = " select * from tab_user where loginname = ? ";
		//2 调用runner的 query方法
		try {
			User u  = qr.query(sql, new  BeanHandler<User>(User.class), loginName);
			//3 返回
			return u;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("查询用户失败!");
		}
	}

	public List<User> getUserByCondition(User u) {
		String sql = " select * from tab_user  where 1=1";
		//准备放置参数的集合
		List<Object> params = new ArrayList<Object>();
		//判断 拼装查询语句,和添加参数
		//用户名
		if(u.getUsername() != null && !"".equals(u.getUsername().trim())){
			sql = sql + " and  username=? ";
			params.add(u.getUsername());
		}
		//根据学历
		if(u.getEducation() != null && !"".equals(u.getEducation().trim())){
			sql = sql + " and  education=? ";
			params.add(u.getEducation());
		}
		//根据性别
		if(u.getGender() != null && !"".equals(u.getGender().trim())){
			sql = sql + " and  gender=? ";
			params.add(u.getGender());
		}
		//根据是否上传简历
		if(u.getUpload() != null && !"".equals(u.getUpload().trim())){
				if(u.getUpload().equals("1")){//用户要找有简历的
					sql = sql + " and  filepath is not null ";
				}
				if(u.getUpload().equals("2")){//用户要找没有简历的
					sql = sql + " and  filepath is  null ";
				}
		}
		
		try {
			System.out.println(sql);
			System.out.println(params);
			List<User> list = qr.query(sql, new BeanListHandler<User>(User.class), params.toArray());
			return list;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("查询用户列表失败!");
		}
		
		
	}

	public void saveUser(User u) {
		String sql =	
				" INSERT INTO `tab_user`                 "+
				" VALUES                                 "+
				"   (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ";
		
		try {
			int result = qr.update(sql, u.getUid(),u.getUsername(),
					u.getLoginname(),u.getLoginpass(),
					u.getGender(),u.getBirthday(),u.getEducation(),
					u.getCellphone(),u.getHobby(),u.getFilepath(),
					u.getFilename(),u.getRemark());
			if(result!=1){
				throw new RuntimeException("保存用户失败!");
			}
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("保存用户失败!");
		}
		 
	}

	public User getUserByUid(String id) {
		//1 书写sql语句
		String sql = " select * from tab_user where uid = ? ";
		//2 调用runner的 query方法
		try {
			User u  = qr.query(sql, new  BeanHandler<User>(User.class), id);
			//3 返回
			return u;
		} catch (SQLException e) {
			e.printStackTrace();
			throw new RuntimeException("查询用户失败!");
		}
	}

}


User:

 

 

package cn.hcx.user.domain;

import java.io.File;

public class User {
	private String uid;
	private String username;
	private String loginname;
	private String loginpass;
	private String gender;
	private String birthday;
	private String education;
	private String cellphone;
	private String hobby;
	private String filepath;
	private String filename;
	private String remark;
//upload 字段在数据库中并没有列与之对应
// 接受表单提交的是否有简历的参数
	private String upload;
	


UserAction:

 

package cn.hcx.user.web.action;

import java.io.File;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletContext;

import org.apache.struts2.ServletActionContext;

import cn.hcx.user.dao.UserDao;
import cn.hcx.user.dao.UserDaoImpl;
import cn.hcx.user.domain.User;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.util.ValueStack;
import com.sun.xml.internal.ws.util.ReadOnlyPropertyException;

public class UserAction extends ActionSupport implements ModelDriven<User> {
	private UserDao ud = new UserDaoImpl();
	private User u = new User();
	
	
	//处理用户登录请求
	public String login(){
		//1 校验
		//2 根据登录名调用Dao,获得用户对象
		User user  = ud.getUserByLoginName(u.getLoginname());
				//没有获得=> 添加错误消息,提示用户名不存在
		if(user == null){
				addActionError("用户名不存在!");
				return "login";
		}
		//3 比对密码 
		if(!user.getLoginpass().equals(u.getLoginpass())){
			//比对失败=>添加错误,提示密码不正确
				addActionError("密码不正确!");
				return "login";
		}
		//4 将User对象放入session域作为登录标识
		Map<String, Object> sessionScope = ActionContext.getContext().getSession();
		sessionScope.put("user", user);
		//5 重定向到成功页面
		return "home";
		
	}
	//-----------------------------------------------------------------------------------------
	//查询用户列表
	public String list(){
		// 1 调用Dao的查询列表方法
		List<User> list = ud.getUserByCondition(u);
		//2 将列表放入request域
		Map<String,Object> requestScope = (Map<String, Object>) ActionContext.getContext()
																			.get("request");
		requestScope.put("list", list);
		//3 转发到list页面
		return "list";
		
	}
	//---------------------------------------------------------------
	//查看用户详情
	public String view(){
		//1 查询用户根据id
		User user = ud.getUserByUid(u.getUid());
		
		//2 将user对象放入值栈栈顶
		ValueStack vs = ActionContext.getContext().getValueStack();
		
		vs.push(user);
		//3转发到查看页面
		return "view";
		
		/*//2放入request域
		//3转发
*/		
	}
	//------------------------------------------------------------------------
	private String filePath;
	private String fileName ;
	public String download(){
		//1 根据id查找用户
		User user = ud.getUserByUid(u.getUid());
		//2 拿到用户的文件路径,文件名称
		filePath = user.getFilepath();
		fileName = user.getFilename();
		//3 返回结果
		
		return "download";
		
	}
	//filePath => /upload/23b798f5-0fc9-4add-9af9-fe8581a458ae
	public InputStream getDoc(){
		//1 获得servletcontext对象
		ServletContext sc = ServletActionContext.getServletContext();
		//2根据路径获得流
		return sc.getResourceAsStream(filePath);
		
	}
	
	public String getFileName(){
	try {
		return URLEncoder.encode(fileName, "utf-8");
	} catch (UnsupportedEncodingException e) {
		e.printStackTrace();
		throw new RuntimeException("不可楞!");
	}
	}
	//----------------------------------------------------------------------------------------
	private File upload2;
	
	private String upload2FileName;
	
	
	
	public String getUpload2FileName() {
		return upload2FileName;
	}
	public void setUpload2FileName(String upload2FileName) {
		this.upload2FileName = upload2FileName;
	}
	public File getUpload2() {
		return upload2;
	}
	public void setUpload2(File upload2) {
		this.upload2 = upload2;
	}
	public String add(){
		String uuid = UUID.randomUUID().toString();
		if(upload2 != null){
			// 1 上传的文件转存
				//1> 找到upload文件夹 绝对路径
			String dirPath = ServletActionContext.getServletContext().getRealPath("/upload");
				//2>生成 文件名称(uuid)
				//3> 转存
			File targetFile = new File(dirPath+"/"+uuid);
			
			upload2.renameTo(targetFile);
			
			// 2 将转存的路径 以及 文件的原始名称封装到User对象
			u.setFilepath("/upload/"+uuid);
			u.setFilename(upload2FileName);
		}
		// 3 使用随机字符串设置user的id
		u.setUid(uuid);
		// 4 调用dao保存user
		ud.saveUser(u);
		// 5 重定向到用户列表
		return "rlist";
	}
	
	//-----------------------------------------------------------------------------------------
	//专门校验login的
	public void validateLogin(){
		//数据校验
		if(u.getLoginname() == null || u.getLoginname().trim().equals("")){
			addFieldError("loginname", "用户名不能为空!");
		}
		
		if(u.getLoginpass() == null || u.getLoginpass().trim().equals("")){
			addFieldError("loginpass", "密码不能为空!");
		}
	}
	
	public User getModel() {
		return u;
	}
	
}


LoginIterceptor:

 

 

package cn.hcx.user.web.interceptor;

import java.util.Map;

import cn.hcx.user.domain.User;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.MethodFilterInterceptor;

public class LoginInterceptor extends MethodFilterInterceptor {

	@Override
	//凡是进入拦截器,都需要有登录状态才能放行
	protected String doIntercept(ActionInvocation invocation) throws Exception {
			//1 获得session
			Map<String,Object> sessionScope = ActionContext.getContext().getSession();
			//2 从session找出User对象
			User u = (User) sessionScope.get("user");
			//3 判断User对象是否存在
			if(u==null){
				//不存在=>没有登录=>转发登录页面
				return "login";
			}
			
				//存在=>登录了=>放行
		return invocation.invoke();
	}

}


struts.xml:

 

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>
	<constant name="struts.devMode" value="true" />
	<constant name="struts.action.extension" value="do" />
	
    <package name="user" namespace="/" extends="struts-default">
    	<interceptors>
    		<!-- 配置自己的拦截器 -->
    		<interceptor name="login" class="cn.hcx.user.web.interceptor.LoginInterceptor"></interceptor>
    		<!-- 配置自己的拦截器栈 -->
    		<interceptor-stack name="myDefaultStack">
    			<!-- 加入自己的拦截器 -->
    			<interceptor-ref name="login">
    			<!-- login方法不拦截,其他都拦截 -->
    				<param name="excludeMethods">login</param>
    			</interceptor-ref>
    			<!-- 加入默认18个拦截器的拦截器栈 -->
    			<interceptor-ref name="defaultStack"></interceptor-ref>
    		</interceptor-stack>
    	</interceptors>
    	<!-- 指定当前包,默认拦截器栈为myDefaultStack -->
    	<default-interceptor-ref name="myDefaultStack"></default-interceptor-ref>
    	<!-- 全局错误配置 -->
    	<global-exception-mappings>
    		<!-- 如果出现java.lang.RuntimeException的异常,那么转发到error对应的页面 -->
    			<exception-mapping result="error" exception="java.lang.RuntimeException"></exception-mapping>
    	</global-exception-mappings>
    	
    	<action name="UserAction_*" class="cn.hcx.user.web.action.UserAction" method="{1}" >
    			<result name="error" >/user/error1.jsp</result>
    			<result name="login" >/login/login.jsp</result>
    			<result name="home" type="redirect"  >/login/home.jsp</result>
    			<result name="list"  >/user/list.jsp</result>
    			<result name="view"  >/user/view.jsp</result>
    			<result name="rlist" type="redirectAction">
		             <param name="actionName">UserAction_list</param>
		             <param name="namespace">/</param>
         		</result>
    			<result name="download" type="stream" >
    					 <param name="contentType">application/msword</param>
				   		 <param name="inputName">doc</param>
				  		 <param name="contentDisposition">attachment;filename="${fileName}"</param>
				  		 <param name="bufferSize">1024</param>
    			</result>
    			
    			<result name="input" >/login/login.jsp</result>
    			
    	</action>
    </package>
</struts>


web.xml:

 

 

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
	xmlns="http://java.sun.com/xml/ns/javaee" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
	
	<filter>
		<filter-name>struts2</filter-name>
		<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
	</filter>
	<filter-mapping>
		<filter-name>struts2</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
	
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

 

 

 

 

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值