在Java中按照编号和姓名查询和组合查询

1.首先要在前台的界面上定义两个文本框,并且两个文本框都有自己的name的值,文本框的样式自己设计,点击查询的时候,会向form表单中的action跳转

姓名:

//定义文本框的类型 //查询按钮

员工编号:

2.在java中的servlet文件中写action=select2的方法,点击查询的时候,跳转到这个servlet文件中

else if(action != null && action.equals("select2")) {
		//接收表单的值
		String no = "";
		String name = "";
		//判断no和name文本框是否为空
		no=request.getParameter("no")==null?"":request.getParameter("no");
		name=request.getParameter("name")==null?"":request.getParameter("name");
		//定义employeeDao
		EmployeeDao employeeDao = new EmployeeDao();
		try {
			//定义一个集合并且从employeeDao中调用查询的方法
			List employeeList = employeeDao.chaxun(no, name);
			/*System.out.println(employeeList);*/
		        //将employeeList的值赋给employeeList
			request.setAttribute("employeeList",employeeList);
		} catch (Exception e) {
			e.printStackTrace();
		}
		//完成之后跳转到employee中的manager.jsp文件中
		request.getRequestDispatcher("/employee/manager.jsp").forward(request, response);
	}

3.在Dao文件中编写查询的方法,和sql语句

public List chaxun(String no,String name) throws Exception{//把no和name作为参数传过来
          //编写一个sql语句不是String语句
    	  StringBuffer sql = new StringBuffer("select ID,TASK_USER_ID,TASK_DEPT_ID,EM_NO,EM_XM,EM_XB,EM_SR,EM_ZW,EM_ZZ,EM_SFZH from task_employee");
    	  Connection conn = null;
          PreparedStatement stmt = null;
          conn = getConn();
          //定义一个employeeList的集合
          List employeeList = new ArrayList(); 
    	  try {	
    		        //判断no不为空,name为空的时候
			if(!no.equals("") && name.equals("")) {
				sql.append(" where EM_NO like '%"+no+"%'");
			}
			//判断name不为空,no为空的时候
			if(!name.equals("") && no.equals("")) {
				sql.append(" where EM_XM like '%"+name+"%'");	
			}
			//判断no和name都不为空的时候
			if(!name.equals("") && !no.equals("")) {
				sql.append(" where EM_NO like'%"+no+"%'and EM_XM like '%"+name+"%'");
			}
			//将sql语句转化为String类型的
			String sql1 = sql.toString();
			conn = getConn();
			stmt = conn.prepareStatement(sql1);
			ResultSet rs = stmt.executeQuery();
			//把结果集中的值取出来,然后放在employee中
			while (rs.next()) {
				Employee e = new Employee();
				e.setId(rs.getInt(1));
				e.setUserid(rs.getInt(2));
				e.setDeptid(rs.getInt(3));
				e.setNo(rs.getString(4));
				e.setName(rs.getString(5));
				e.setSex(rs.getString(6));
				e.setBirthday(rs.getDate(7));
				e.setDuty(rs.getString(8));
				e.setAddress(rs.getString(9));
				e.setNumber(rs.getString(10));
				employeeList.add(e);
			}
			
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
    	        //返回employeeList的集合
		return employeeList;
    }

你可能感兴趣的:(在Java中按照编号和姓名查询和组合查询)