本文共 16663 字,大约阅读时间需要 55 分钟。
配置如下图:
点击finish,Struts1框架创建完成,在目录里就能看见Struts1配置文件了,接下来在这个配置文件里画架构图。
创建jsp页
将其放在WEB-INF下
建一个表单,右键-New-Form,表单不显示出图。form表单是和前台form表单里的元素相对应的,就像Javabean是和数据库字段一一对应的一样。
配置如下图
接下来建Action同表单建法。
配置如下图,勾选去掉
在jsp和action中间连线,表示jsp发送请求时去找action,action有一个表单对应。
Action收到请求后处理请求,然后跳转到下一个主页面jsp
建主页面jsp,然后在action和这个主页面jsp连线。
在主页面上做点击操作,需要在跳到一个jsp,所以需要在建一个action和jsp页。
登录不成功返回原页面,err ,下图中的name,在action里传值给jsp时,action里return mapping.findForward("err");括号内的内容要和下图中的name一致。
Web部分完成
以上是Struts1框架的基本搭建流程。
接下来用Struts1框架和JDBC做一个树形。
工程目录如下
struts-config.xml配置文件代码如下:
config.properties链接数据库的配置文件代码如下:
characterEncoding=utf-8避免JDBC操作出现乱码
driver=org.gjt.mm.mysql.Driverurl=jdbc:mysql://localhost:3306/test?characterEncoding=utf-8uname=rootupass=123456DbUtils链接数据库的工具类,代码如下:
package com.chenmei.struts.utils;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.Properties;public class DbUtils { //给自己建一个静态的私有属性 private static DbUtils dl; //建私有属性 private static String driver; private static String url; private static String uname; private static String upass; //建一个私有的构造方法,防止随意new它 @SuppressWarnings("static-access") private DbUtils() throws Exception{ //加载配置文件 Properties p = new Properties(); p.load(this.getClass().getClassLoader().getResourceAsStream("config.properties")); this.driver = p.getProperty("driver"); this.url = p.getProperty("url"); this.uname = p.getProperty("uname"); this.upass = p.getProperty("upass"); //加载驱动程序到虚拟机中 Class.forName(this.driver); } //写一个公有方法,带返回对象,让外边可以new它 public static synchronized DbUtils getInstance() throws Exception{ if(dl == null){ dl = new DbUtils(); } return dl; } //连接数据库对象 public Connection getConnection() throws Exception{ Connection conn = DriverManager.getConnection(url, uname, upass); return conn; } //重载下面的方法 public static void close(ResultSet rs, PreparedStatement ps){ close(rs, ps, null); } public static void close(PreparedStatement ps){ close(null, ps, null); } public static void close(Connection conn){ close(null, null, conn); } //关闭资源方法 public static void close(ResultSet rs, PreparedStatement ps, Connection conn){ if(rs != null){ try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } if(ps != null){ try { ps.close(); } catch (Exception e) { e.printStackTrace(); } } if(rs != null){ try { rs.close(); } catch (Exception e) { e.printStackTrace(); } } }}ResponseUtil用到了该类里的向页面传值方法和时间处理方法,代码如下:
//将结果集输出在页面 public static void write(HttpServletResponse response,Object o)throws Exception{ response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println(o.toString()); out.flush(); out.close(); }
public static String formatDate(Date date,String format){ String result=""; SimpleDateFormat sdf=new SimpleDateFormat(format); if(date!=null){ result=sdf.format(date); } return result; }对应数据库建了三个Javabean,分别是DeptBean,EmpBean和SalaryBean类,代码不列出了。
MainMode代码如下:
package com.chenmei.struts.mode;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.ArrayList;import java.util.List;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import com.chenmei.struts.pojo.DeptBean;import com.chenmei.struts.utils.DbUtils;/** * 查询部门列表 * 查询dept_id,作为第一层树的节点 */public class MainMode { public ListMainAction代码如下:getDeptList(Connection conn){ String sql = "select dept_id,name FROM department"; PreparedStatement ps = null; ResultSet rs = null; List deptList = new ArrayList (); try { ps = conn.prepareStatement(sql); rs = ps.executeQuery(); while(rs.next()){ DeptBean deptBean=new DeptBean(); deptBean.setDept_id(rs.getInt("dept_id")); deptBean.setName(rs.getString("name")); deptList.add(deptBean); } } catch (Exception e) { System.out.println("获取部门列表出错!"); e.printStackTrace(); }finally{ DbUtils.close(rs, ps); } return deptList; } /** * 查询月份,并根据employee_id过滤 * 查出数据后拼成jsonarray返回给action */ public JSONArray getMonthList(Connection conn, String deptId) { String sql="SELECT month FROM salary WHERE employee_id IN (SELECT employee_id FROM employee WHERE dept_id = ?) GROUP BY month"; PreparedStatement ps = null; ResultSet rs = null; JSONArray jsonArray = new JSONArray() ; try { ps = conn.prepareStatement(sql); ps.setString(1, deptId); rs = ps.executeQuery(); while(rs.next()){ JSONObject jsonObject=new JSONObject(); jsonObject.put("id", rs.getString(1)); jsonObject.put("text", rs.getString(1)); jsonObject.put("state", "close"); jsonArray.add(jsonObject); } } catch (Exception e) { System.out.println("获取月份列表出错!"); e.printStackTrace(); }finally{ DbUtils.close(rs, ps); } return jsonArray; } /** * 查询总条数 */ public int getSalaryCount(Connection conn, String month, String deptId){ String sql = "SELECT COUNT(employee_id) FROM salary WHERE month = '"+month+"' AND employee_id IN (SELECT employee_id FROM employee WHERE dept_id = '"+deptId+"') ORDER BY month,employee_id"; PreparedStatement ps = null; ResultSet rs = null; try{ ps=conn.prepareStatement(sql); rs=ps.executeQuery(); if(rs.next()){ return rs.getInt(1); }else{ return 0; } }catch(Exception ex){ System.out.println("获取合计条数失败"); ex.printStackTrace(); } finally{ //DbUtils.close(rs, ps);//不能关闭,关闭报错 } return 0; } /** * 分页显示工资内容 */ public JSONArray getSalaryList(Connection conn, String month, String deptId, int page, int rows) throws Exception { String sql="select sal.salary_id,sal.employee_id,sal.salary,sal.salary_add,sal.salary_total,sal.month,emp.dept_id,emp.name,emp.code from salary AS sal "+ " LEFT JOIN employee AS emp on emp.employee_id = sal.employee_id "+ " where sal.month='"+month+"' and sal.employee_id in (SELECT employee_id from employee where employee.dept_id='"+deptId+"' ) group by sal.salary_id limit ?,? "; PreparedStatement ps = null; ResultSet rs = null; JSONArray jsonArray = new JSONArray() ; try{ ps=conn.prepareStatement(sql); ps.setInt(1, (page-1)*rows); ps.setInt(2, page*rows); rs=ps.executeQuery(); //将查出的内容循环输出放入jsonArray返回给action while(rs.next()){ JSONObject jsonObject=new JSONObject(); jsonObject.put("salary_id",rs.getString(1)); jsonObject.put("employee_id", rs.getString(2)); jsonObject.put("salary", rs.getString(3)); jsonObject.put("salary_add",rs.getString(4)); jsonObject.put("salary_total", rs.getString(5)); jsonObject.put("month", rs.getString(6)); jsonObject.put("dept_id", rs.getString(7)); jsonObject.put("name", rs.getString(8)); jsonObject.put("code", rs.getString(9)); jsonArray.add(jsonObject); } }catch(Exception ex){ System.out.println("获取工资信息错误"); ex.printStackTrace(); } finally{ DbUtils.close(rs, ps); } return jsonArray; } /* 第二种写法 public ResultSet getSalaryList(Connection conn, String month, String deptId, int page, int rows) throws Exception { String sql="select * from salary AS sal "+ " LEFT JOIN employee AS emp on emp.employee_id = sal.employee_id "+ " where sal.month='"+month+"' and sal.employee_id in (SELECT employee_id from employee where employee.dept_id='"+deptId+"' ) group by sal.salary_id limit ?,? "; PreparedStatement ps = null; ResultSet rs = null; JSONArray jsonArray = new JSONArray() ; try{ ps=conn.prepareStatement(sql); ps.setInt(1, (page-1)*rows); ps.setInt(2, page*rows); rs=ps.executeQuery(); }catch(Exception ex){ System.out.println("获取工资信息错误"); ex.printStackTrace(); } finally{ //DbUtils.close(rs, ps); } return rs; }*/ public void addSalarySave(Connection conn,int dept_id, String name,String code,String salary,String month) { String sql="INSERT INTO employee (dept_id,name,code) VALUES(?,?,?)"; String sql1="INSERT INTO salary (employee_id,salary,month) VALUES((SELECT employee_id FROM employee ORDER BY employee_id DESC LIMIT 1),?,?)"; PreparedStatement ps = null; PreparedStatement ps1 = null; try { ps = conn.prepareStatement(sql); ps.setInt(1, dept_id); ps.setString(2, name); ps.setString(3, code); ps.executeUpdate(); ps1 = conn.prepareStatement(sql1); ps1.setString(1, salary); ps1.setString(2, month); ps1.executeUpdate(); } catch (Exception e) { System.out.println("向工资表添加内容出错!"); e.printStackTrace(); }finally{ DbUtils.close(ps); DbUtils.close(ps1); } }}
package com.chenmei.struts.action;import java.io.PrintWriter;import java.sql.Connection;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import org.apache.struts.action.ActionForm;import org.apache.struts.action.ActionForward;import org.apache.struts.action.ActionMapping;import org.apache.struts.actions.DispatchAction;import com.chenmei.struts.mode.MainMode;import com.chenmei.struts.pojo.DeptBean;import com.chenmei.struts.utils.DbUtils;public class MainAction extends DispatchAction { /** * 第一层树 * 得到deptId */ public ActionForward getDeptList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("text/html;charset=utf-8");//设置发送到客户端的响应的内容类型 Connection conn = null; try { conn = DbUtils.getInstance().getConnection(); MainMode mainMode = new MainMode(); Listindex.jsp代码如下:deptList = mainMode.getDeptList(conn); conn.close(); JSONArray jsonArray=new JSONArray();//拼jsonarray,按easyUI的API里给出的格式拼 for(DeptBean bean:deptList){ JSONObject jsonObject =new JSONObject(); jsonObject.put("id",bean.getDept_id()); jsonObject.put("text",bean.getName()); jsonObject.put("state","closed"); jsonArray.add(jsonObject); } PrintWriter out = response.getWriter(); //out.println(jsonArray.toString()); out.println(jsonArray);//将jsonarray输出到页面 out.flush();//清空缓冲区数据 out.close(); } catch (Exception e) { e.printStackTrace(); }finally{ DbUtils.close(conn); } return null; } /** * 第二层树 * 得到月份 */ public ActionForward getMonthList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String deptId = request.getParameter("deptId"); if(deptId == null){ deptId = ""; } Connection conn = null; try { conn = DbUtils.getInstance().getConnection(); MainMode mainMode = new MainMode(); JSONArray jsonArray = mainMode.getMonthList(conn, deptId); conn.close(); //如果该方法在getWriter()方法被调用之前调用,那么响应的字符编码将仅从给出的内容类型中设置。该方法如果在getWriter()方法被调用之后或者在被提交之后调用,将不会设置响应的字符编码 //下面的五句可以写在一个方法里,用时直接调用 response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println(jsonArray.toString()); out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); }finally{ DbUtils.close(conn); } return null; } /** * 点击月份显示工资列表 */ public ActionForward getSalaryList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String month = request.getParameter("month"); if (month==null){ month=""; } String deptId = request.getParameter("deptId"); if (deptId==null){ deptId=""; } MainMode mainMode=new MainMode(); Connection conn = null; try{ //获取翻页信息 int page=Integer.valueOf(request.getParameter("page")==null? "1":request.getParameter("page")); int rows=Integer.valueOf(request.getParameter("rows")==null? "20":request.getParameter("rows")); //向页面返回JSONObject JSONObject result = new JSONObject(); //链接数据库 conn = DbUtils.getInstance().getConnection(); //获取总记录数 int total = mainMode.getSalaryCount(conn,month,deptId); //调取mode里的JSONArray数据 JSONArray jsonArray = mainMode.getSalaryList(conn, month, deptId, page, rows); //放到JSONObject里传到页面 result.put("rows", jsonArray); result.put("total", total); //向页面传值 response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println(jsonArray.toString()); out.flush(); out.close(); }finally{ conn.close(); } return null; } // public ActionForward getSalaryList(ActionMapping mapping, ActionForm form,// HttpServletRequest request, HttpServletResponse response) throws Exception {// String month = request.getParameter("month");// if (month==null){// month="";// }// String deptId = request.getParameter("deptId");// if (deptId==null){// deptId="";// }// MainMode mainMode=new MainMode();// Connection conn = null;// try{// //获取翻页信息// int page=Integer.valueOf(request.getParameter("page")==null? "1":request.getParameter("page"));// int rows=Integer.valueOf(request.getParameter("rows")==null? "20":request.getParameter("rows"));// // JSONObject result = new JSONObject();// conn = DbUtils.getInstance().getConnection();// //获取总记录数// int total = mainMode.getSalaryCount(conn,month,deptId);// JSONArray jsonarray = ResponseUtil.formatRsToJsonArray(// mainMode.getSalaryList(conn,month,deptId,page,rows));// /*格式化jsonarray的,可以写到一个方法里// ResultSet rs = mainMode.getSalaryList(conn, month, deptId, page, rows);// ResultSetMetaData md=rs.getMetaData();// int num=md.getColumnCount();// JSONArray array=new JSONArray();// while(rs.next()){// JSONObject mapOfColValues=new JSONObject();// for(int i=1;i<=num;i++){// Object o=rs.getObject(i);// if(o instanceof Date){ //instanceof是一个运算符,返回布尔类型。格式是object instanceof class,这里是判断object类型的o是否是date类型,是返回true。// mapOfColValues.put(md.getColumnName(i), formatDate((Date)o, "yyyy-MM-dd"));// }else{// mapOfColValues.put(md.getColumnName(i), rs.getObject(i)); // }// }// array.add(mapOfColValues);// }// */// result.put("rows", jsonarray);// result.put("total", total); // //调向页面传值的方法// ResponseUtil.write(response, result);// }finally{// conn.close();// }// return null;// } /* 日期处理,可以写到一个方法里 public static String formatDate(Date date,String format){ String result=""; SimpleDateFormat sdf=new SimpleDateFormat(format); if(date!=null){ result=sdf.format(date); } return result; }*/ //添加方法 public ActionForward addSalarySave(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { response.setContentType("text/html;charset=utf-8");//设置发送到客户端的响应的内容类型 String name = request.getParameter("name"); String code = request.getParameter("code"); String salary = request.getParameter("salary"); String month = request.getParameter("month"); int dept_id = Integer.parseInt(request.getParameter("dept_id")); Connection conn = null; boolean result = false; try { conn = DbUtils.getInstance().getConnection(); MainMode mainMode = new MainMode(); mainMode.addSalarySave(conn, dept_id, name, code, salary, month); result = true; PrintWriter out = response.getWriter(); out.println(result);//将jsonarray输出到页面 out.flush();//清空缓冲区数据 out.close(); } catch (Exception e) { e.printStackTrace(); }finally{ DbUtils.close(conn); } return null; } }
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>预览效果图: 源码下载链接:https://pan.baidu.com/s/1slwQNZB 密码 : q3sf主页 工资表
姓名 人员编号 应发工资