java jsp struts2 实现查询功能的思路
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java jsp struts2 实现查询功能的思路相关的知识,希望对你有一定的参考价值。
请给我思路,或者给代码例子也可以,谢谢!
很感谢两位的回答.但是我还是有些问题:在ACTION中调用request是不是要引入什么包呢?
在代码中第四行提示 request cannot be resolved
public String execute()
ArrayList al = new ArrayList();
ManageDB mdb=new ManageDB();
al=mdb.getSerInfo(impId, impName);
request.setAttrubites(al);
return SUCCESS;
public String getImpName()
return impName;
public void setImpId(int impId)
this.impId = impId;
public void setImpName(String impName)
this.impName = impName;
public String execute()
ArrayList al = new ArrayList();
ManageDB mdb=new ManageDB();
al=mdb.getSerInfo(impId, impName);
request.setAttrubites(al);
return SUCCESS;
package com.hnkj.company.user.struts2.action;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.util.Date;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import com.hnkj.company.common.BaseAction;
import com.hnkj.company.commonality.model.TLog;
import com.hnkj.company.user.model.TUsers;
import com.hnkj.company.user.service.UserService;
import com.hnkj.company.util.MD5Util;
public class UserAction extends BaseAction implements SessionAware,ServletRequestAware, ServletResponseAware
private String message;
private HttpServletRequest request;
private HttpServletResponse response;
private Map session;
private UserService userService;
private String username;
private String password;
private MD5Util md5=new MD5Util();
private TUsers user;
/**
* 用户登录
* @return
*/
public String login()throws Exception
java.text.SimpleDateFormat formats=new java.text.SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
String date=formats.format(new Date());
String pwd=md5.getMD5ofStr(password);
TUsers user=userService.userLogin(username,pwd);
if(user!=null)
//查找用户id
TUsers s=userService.findByUser(username);
//得到该用户登录次数
int count=s.getUCount();
int userid=s.getUserId();
//加载该类
TUsers t_user=(TUsers)userService.getObject(TUsers.class, userid);
t_user.setUserId(userid);
t_user.setUCount(count+1);
userService.updateUser(t_user);
//登录日志
TLog log=new TLog();
try
log.setLogDate(formats.parse(date));
catch (ParseException e)
e.printStackTrace();
log.setLogName("用户"+username+"登录系统");
log.setLogtype(0);
userService.addLog(log);
//写cookie操作
Cookie cooki;
cooki=new Cookie("tz_username",String.valueOf(username));//用户ID
cooki.setMaxAge(60*60*24*365);//cookie时间
cooki.setPath("/"); //根据个人的不用,在不同功能的路径下创建
response.addCookie(cooki);
session.put("user", user);
session.put("username", username);
return "personmanager";
else
message=username+"用户名错误或者密码错误..";
return "login";
/**
* 检查用户名
* @return
* @throws Exception
*/
public String check()
try
String name=new String(request.getParameter("username").getBytes("ISO8859-1"),"utf-8");
response.setContentType("text;charset=GBK");
PrintWriter pw = response.getWriter();
TUsers t_user= userService.findByUser(name);
if(t_user!=null)
pw.print("have");
pw.close();
else
pw.print("nothave");
pw.close();
catch (IOException e)
e.printStackTrace();
return null;
public String register()throws Exception
java.text.SimpleDateFormat formats=new java.text.SimpleDateFormat("yyyy-MM-dd");
String date=formats.format(new Date());
TUsers t_user=new TUsers();
t_user.setUsername(user.getUsername());
String password=md5.getMD5ofStr(user.getPassword());
t_user.setPassword(password);
t_user.setGender(user.getGender());
t_user.setReallyname(user.getReallyname());
t_user.setEmail(user.getEmail());
t_user.setBirthday(user.getBirthday());
t_user.setProblem(user.getProblem());
t_user.setResult(user.getResult());
t_user.setAddress(user.getAddress());
t_user.setPhone(user.getPhone());
t_user.setState(0);
t_user.setCreateDate(formats.parse(date));
t_user.setUCount(0);
userService.addUser(t_user);
//ServletContext sc = getServletContext();
//RequestDispatcher rd = null;
// rd = sc.getRequestDispatcher("/index.jsp"); //定向的页面
//rd.forward(request, response);
//RequestDispatcher requestDispatcher=request.getRequestDispatcher("/jsp/testbean.jsp");
//requestDispatcher.forward(request,response);
response.sendRedirect(request.getContextPath()+"/userLogin.jsp");
return null;
/**
* 修改个人详细信息
* @return
* @throws IOException
*/
public String update() throws IOException
java.text.SimpleDateFormat formats=new java.text.SimpleDateFormat("yyyy-MM-dd");
String date=formats.format(new Date());
TUsers t_user=(TUsers)userService.getObject(TUsers.class, user.getUserId());
//t_user.setUsername(user.getUsername());
String pwd=md5.getMD5ofStr(user.getPassword());
t_user.setUserId(user.getUserId());
t_user.setPassword(pwd);
t_user.setGender(user.getGender());
t_user.setReallyname(user.getReallyname());
t_user.setEmail(user.getEmail());
t_user.setBirthday(user.getBirthday());
t_user.setProblem(user.getProblem());
t_user.setResult(user.getResult());
t_user.setAddress(user.getAddress());
t_user.setPhone(user.getPhone());
userService.updateUser(t_user);
message="修改成功..";
//response.sendRedirect(request.getContextPath()+"/user/updateUser.jsp");
return "update_success";
public String getUsername()
return username;
public void setUsername(String username)
this.username = username;
public String getPassword()
return password;
public void setPassword(String password)
this.password = password;
public void setServletRequest(HttpServletRequest request)
this.request=request;
public void setServletResponse(HttpServletResponse response)
this.response=response;
public void setSession(Map session)
this.session=session;
public String getMessage()
return message;
public void setMessage(String message)
this.message = message;
public HttpServletRequest getRequest()
return request;
public void setRequest(HttpServletRequest request)
this.request = request;
public HttpServletResponse getResponse()
return response;
public void setResponse(HttpServletResponse response)
this.response = response;
public Map getSession()
return session;
public UserService getUserService()
return userService;
public void setUserService(UserService userService)
this.userService = userService;
public TUsers getUser()
return user;
public void setUser(TUsers user)
this.user = user;
参考技术A 在JSP页面中设置一个文本框 输入想要查询的关键字 提交表单后 表单传给struts里面的action
action里面接收到来自前面表单里面的信息,调用后台的业务逻辑执行查询操作
查询得到的信息放在一个对象里面存起来,在action里面request.setAttrubites()存进去,action再跳转到前面的JSP页面
在JSP页面取出request里面的对象显示出来 参考技术B struts2里的request不能直接用,可以实现接口或者用ServletActionContext.getRequest()的方式拿 参考技术C 不需要引入包
java--easyUI+struts+JSP实现简单的增删查改
1.数据库工具类
package com.xiaoxiong.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnUtil { //定义连接数据库参数 private static String drivers = "com.mysql.jdbc.Driver"; private static String url = "jdbc:mysql://localhost:3306/easyui"; private static String user = "root"; private static String password = "a123456"; private static Connection conn = null; //连接数据库 public static Connection getConnection(){ try { //加载驱动 Class.forName(drivers); //连接数据库 conn = DriverManager.getConnection(url, user, password); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return conn; } //关闭数据库 public void close(){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
package com.xiaoxiong.util; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * 执行Sql语句 * @author user * */ public class DBUtil { //声明JDBC对象 private Connection conn = null; //预编译sql private PreparedStatement ps = null; //接收查询返回的结果 private ResultSet rs = null; //初始化操作,连接数据库 public void init(){ conn = ConnUtil.getConnection(); } /** * 执行查询语句 * @param sql sql语句 * @param parameters 参数 * @return */ public ResultSet executeQuery(String sql, Object...parameters){ //连接数据库 init(); try { //预编译sql ps = conn.prepareStatement(sql); System.out.println("============"+sql); //为sql传值 for(int i=1; i<=parameters.length; i++){ ps.setObject(i, parameters[i-1]); System.out.println("-------------->"+parameters[i-1]); } //执行sql返回结果集 rs = ps.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } return rs; } public int executUpdate(String sql, Object...parameters){ init(); try { ps = conn.prepareStatement(sql); for (int i = 1; i <= parameters.length; i++) { ps.setObject(i, parameters[i-1]); } return ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } return 0; } //关闭数据库 public void close(){ try { if(rs!=null){ rs.close(); } if(ps!=null){ ps.close(); } if(conn!=null){ conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } }
2.entity类
package com.xiaoxiong.bean; public class Dept { private int deptno; private String dname; private String loc; public Dept() { } public Dept(int deptno, String dname, String loc) { super(); this.deptno = deptno; this.dname = dname; this.loc = loc; } public int getDeptno() { return deptno; } public void setDeptno(int deptno) { this.deptno = deptno; } public String getDname() { return dname; } public void setDname(String dname) { this.dname = dname; } public String getLoc() { return loc; } public void setLoc(String loc) { this.loc = loc; } }
package com.xiaoxiong.bean; import java.util.Date; public class Emp { private int empno; private String ename; private String job; private Date hiredate; private String mgr; private int sal; private int comm; private int deptno; public Emp() { } public Emp(String ename, String job, Date hiredate, String mgr, int sal, int comm, int deptno) { this.ename = ename; this.job = job; this.hiredate = hiredate; this.mgr = mgr; this.sal = sal; this.comm = comm; this.deptno = deptno; } public int getEmpno() { return empno; } public void setEmpno(int empno) { this.empno = empno; } public String getEname() { return ename; } public void setEname(String ename) { this.ename = ename; } public String getJob() { return job; } public void setJob(String job) { this.job = job; } public Date getHiredate() { return hiredate; } public void setHiredate(Date hiredate) { this.hiredate = hiredate; } public String getMgr() { return mgr; } public void setMgr(String mgr) { this.mgr = mgr; } public int getSal() { return sal; } public void setSal(int sal) { this.sal = sal; } public int getComm() { return comm; } public void setComm(int comm) { this.comm = comm; } public int getDeptno() { return deptno; } public void setDeptno(int deptno) { this.deptno = deptno; } }
3.sql处理类
package com.xiaoxiong.dao; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.xiaoxiong.bean.Dept; import com.xiaoxiong.bean.Emp; import com.xiaoxiong.util.DBUtil; public class EmpDao { //实例化一个数据库工具对象 DBUtil db = new DBUtil(); private ResultSet rs = null; public List getAvgSalary(){ StringBuffer sql = new StringBuffer(); sql.append("SELECT AVG(e.sal) as avgSalary,e.deptno from emp e GROUP BY e.deptno "); List list = new ArrayList(); Map map = null; rs = db.executeQuery(sql.toString()); System.out.println("查询部门平均薪资!"); try { while(rs.next()){ map = new HashMap(); map.put("avgSalary", rs.getInt(1)); map.put("deptno", rs.getInt(2)); list.add(map); System.out.println(rs.getInt(1)+":"+rs.getInt(2)); } } catch (SQLException e) { e.printStackTrace(); } System.out.println(list); return list; } /** * 删除用户信息 * @param empno * @return */ public int delete(int empno){ StringBuffer sql = new StringBuffer(); sql.append("delete from emp where empno = ?"); try { return db.executUpdate(sql.toString(), empno); } catch (Exception e) { e.printStackTrace(); } finally{ db.close(); } return 0; } /** * 添加员工数据 * @param emp * @return */ public int addEmp(Emp emp){ StringBuffer sql = new StringBuffer(); sql.append("insert into emp(ename,job,mgr,hiredate,sal,comm,deptno) "); sql.append("values(?,?,?,?,?,?,?) "); try { return db.executUpdate(sql.toString(),emp.getEname() ,emp.getJob(),emp.getMgr(),emp.getHiredate(),emp.getSal() ,emp.getComm(),emp.getDeptno()); } catch (Exception e) { e.printStackTrace(); } finally{ db.close(); } return 0; } /** * 修改员工 * @param emp * @return */ public int update(Emp emp){ StringBuffer sql = new StringBuffer(); sql.append("update emp set ename=? ,job=?, mgr=?, hiredate=?, sal=?, comm=?, deptno=? "); sql.append("where empno=?"); try { return db.executUpdate(sql.toString(), emp.getEname(), emp.getJob(), emp.getMgr(), emp.getHiredate(), emp.getSal(), emp.getComm(),emp.getDeptno(),emp.getEmpno()); } catch (Exception e) { e.printStackTrace(); } finally{ db.close(); } return 0; } /** * 查询上级 * @return */ public List searchMgr(){ List list = new ArrayList(); StringBuffer sql = new StringBuffer(); sql.append("select empno, ename from emp where job in(?,?,?) "); rs = db.executeQuery(sql.toString(), "MANAGER","ANALYST","PRESIDENT"); try { while(rs.next()){ Emp emp = new Emp(); emp.setEmpno(rs.getInt("empno")); emp.setEname(rs.getString("ename")); list.add(emp); } } catch (SQLException e) { e.printStackTrace(); } finally{ db.close(); } return list; } /** * 查询部门信息 * @return */ public List searchDept(){ List list = new ArrayList(); StringBuffer sql = new StringBuffer(); sql.append("select * from dept "); rs = db.executeQuery(sql.toString()); try { while(rs.next()){ Dept dept = new Dept(); dept.setDeptno(rs.getInt("deptno")); dept.setDname(rs.getString("dname")); dept.setLoc(rs.getString("loc")); list.add(dept); } } catch (SQLException e) { e.printStackTrace(); } finally{ db.close(); } return list; } /** * 查询所有数据 * @return */ public List getAll(){ //创建list集合存储查询结果集 List list = new ArrayList(); //编写sql逻辑,调用DBUtil的executeQuery执行 StringBuilder sql = new StringBuilder(); sql.append("select * from emp "); rs = db.executeQuery(sql.toString()); try { //迭代出数据,存储到list集合中 while(rs.next()){ Emp emp = new Emp(); emp.setEmpno(rs.getInt("empno")); emp.setDeptno(rs.getInt("deptno")); emp.setEname(rs.getString("ename")); emp.setHiredate(rs.getDate("hiredate")); emp.setJob(rs.getString("job")); emp.setMgr(rs.getString("mgr")); emp.setComm(rs.getInt("comm")); emp.setSal(rs.getInt("sal")); list.add(emp); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ db.close(); } return list; } /** * 通过员工名模糊查询 * @param page * @param rows * @param name * @return */ public List<Emp> searchByName(int page,int rows,String name){ List<Emp> list = new ArrayList<Emp>(); StringBuffer sql = new StringBuffer(); sql.append("select * from emp where ename like ? limit ?,?"); System.out.println("输入查询的用户名为:"+name); rs = db.executeQuery(sql.toString(), "%" + name + "%", (page-1)*rows, rows); System.out.println("模糊查询的结果为:"+rs); try { //迭代出数据,存储到list集合中 while(rs.next()){ Emp emp = new Emp(); emp.setEmpno(rs.getInt("empno")); emp.setDeptno(rs.getInt("deptno")); emp.setEname(rs.getString("ename")); emp.setHiredate(rs.getDate("hiredate")); emp.setJob(rs.getString("job")); emp.setMgr(rs.getString("mgr")); emp.setComm(rs.getInt("comm")); emp.setSal(rs.getInt("sal")); list.add(emp); } }catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ db.close(); } return list; } /** * 分页查询 * @param page * @param rows * @return */ public List<Emp> searchPage(int page, int rows){ List<Emp> list = new ArrayList<Emp>(); System.out.println("page="+page+":rows"+rows); StringBuilder sql = new StringBuilder(); sql.append("select * from emp limit ?,? "); rs = db.executeQuery(sql.toString(), (page-1)*rows, rows); try { //迭代出数据,存储到list集合中 while(rs.next()){ Emp emp = new Emp(); emp.setEmpno(rs.getInt("empno")); emp.setDeptno(rs.getInt("deptno")); emp.setEname(rs.getString("ename")); //日期格式的转换 emp.setHiredate(rs.getDate("hiredate")); emp.setJob(rs.getString("job")); emp.setMgr(rs.getString("mgr")); emp.setComm(rs.getInt("comm")); emp.setSal(rs.getInt("sal")); list.add(emp); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally{ db.close(); } return list; } /** * 模糊匹配数据的总数 * @param name * @return */ public int getCountByName(String name){ StringBuilder sql = new StringBuilder(); sql.append("select count(*) from emp where ename like ?"); int count = 0; rs = db.executeQuery(sql.toString(), "%" + name + "%"); try { while(rs.next()){ count = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } return count; } /** * 查询总数 * @return */ public int getCount(){ StringBuilder sql = new StringBuilder(); sql.append("select count(*) from emp "); int count = 0; rs = db.executeQuery(sql.toString()); try { while(rs.next()){ count = rs.getInt(1); } } catch (SQLException e) { e.printStackTrace(); } return count; } }
4.action类
package com.xiaoxiong.action; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.google.gson.Gson; import com.opensymphony.xwork2.ActionSupport; import com.xiaoxiong.bean.Dept; import com.xiaoxiong.dao.EmpDao; public class DeptAction extends ActionSupport { EmpDao dao = new EmpDao(); /** * 查询dept * @return * @throws IOException */ public String searchDept() throws IOException { List<Dept> list = new ArrayList<Dept>(); Dept dept = new Dept(); dept.setDeptno(-1); dept.setDname("请选择"); list = dao.searchDept(); // 将查询到的结果转为json数据 list.add(0, dept); Gson gson = new Gson(); String json = gson.toJson(list); System.out.println(json); // 数据回传给浏览器端 HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); response.getWriter().println(json); return this.NONE; } }
package com.xiaoxiong.action; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; import org.apache.struts2.ServletActionContext; import com.google.gson.Gson; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.xiaoxiong.bean.Dept; import com.xiaoxiong.bean.Emp; import com.xiaoxiong.dao.EmpDao; public class EmpAction extends ActionSupport implements ModelDriven<Emp> { private Emp emp; private Integer rows; private Integer page; private String ename; // 实例化一个dao类 EmpDao dao = new EmpDao(); public String avgSalary() throws IOException{ List list = new ArrayList(); list = dao.getAvgSalary(); System.out.println("访问avgSalaryAction"); //转换为json数据 String json = new Gson().toJson(list); System.out.println("-------------json"+json); ServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html; charset=utf-8"); response.getWriter().println(json); return this.NONE; } /** * 删除模块 * @return * @throws IOException */ public String delete() throws IOException { // 创建map存储执行的结果 Map map = new HashMap(); // 做异常处理 try { // 修改员工信息 dao.delete(emp.getEmpno()); map.put("result", true); map.put("message", "数据删除成功"); } catch (Exception e) { map.put("result", false); map.put("message", e.getMessage()); } // 将数据转换为json格式 String json = new Gson().toJson(map); ServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html; charset=utf-8"); response.getWriter().println(json); return this.NONE; } /** * 修改用户 * * @return * @throws IOException */ public String update() throws IOException { // 创建map存储执行的结果 Map map = new HashMap(); // 做异常处理 try { // 修改员工信息 dao.update(emp); map.put("result", true); map.put("message", "数据修改成功"); } catch (Exception e) { map.put("result", false); map.put("message", e.getMessage()); } System.out.println("empno:" + emp.getEmpno() + "ename:" + emp.getEname() + "----job:" + emp.getJob() + "----deptno:" + emp.getDeptno() + "----mgr:" + emp.getMgr() + "----hiredate:" + emp.getHiredate() + "----sal:" + emp.getSal() + "----comm:" + emp.getComm()); String json = new Gson().toJson(map); ServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html; charset=utf-8"); response.getWriter().println(json); return this.NONE; } /** * 新增用户以上是关于java jsp struts2 实现查询功能的思路的主要内容,如果未能解决你的问题,请参考以下文章