最近开始着手struts2的学习,版本是struts-2.0.6,倒腾了一个多月了,零零散散的,想法一直在改变,起先就是想做个普通的信息管理系统,用struts2+JSP,接着发现web页面太丑,我不会界面操作,对于html语言也只是停留在简单的能看,想起来以前接触过ExtJs,哎呀 ,现成的界面做好调用就可以岂不快哉,说干就干下了个ext-2.0.2., 一晚上加一上午加一下午终于调通了,暂时可以把数据利用DAO的方式简单的从mysql5.1里提取然后显示在Ext的表格(grid)上了==! 似不似很丢人
效果图如下:
好吧,我想你看出来了我是个小菜鸟,原谅我吧 ,我有大牛的梦想的啦,有兴趣的话看看我接下来的具体实施吧,其实还是很纠结的
开发工具 MyEclipse5.5.1,部署如下:
DAO模式 连接数据库
package DAO;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// 连接数据库,配置数据库
public class DAOBase implements DAO {
public Connection getConnection() {
String connectURL = "jdbc:mysql://localhost/test";
String user = "root";
String password = "123";
try{
Class.forName("com.mysql.jdbc.Driver");// 加载驱动程序
Connection connection = DriverManager.getConnection(connectURL, user, password);
return connection;
}catch (SQLException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
struts2作为图文表现层,使模型和动作分开,Employee.java模型类
package entity;
public class Employee {
private int id;
private String firstName;
private String lastName;
public Employee() {
}
public Employee(int id, String firstName, String lastName) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
//转化为JSON格式
public String toString() {
return "{id:" + id +
",firstName:'" + firstName +
"',lastName:'" + lastName +
"'}";
}
}
EmployeeActioin.java动作类
package entity;
import entity.Employee;
import entity.EmployeeManager;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import java.util.List;
import com.opensymphony.xwork2.ModelDriven;
// 使用ModelDriven拦截器
public class EmployeeAction extends ActionSupport implements Preparable,ModelDriven{
private static final long serialVersionUID = 1L;
private Employee employee;
private int employeeId;
private List<Employee> employees;
//ModelDriven拦截器自动调用的方法
public Object getModel(){
return employee;
}
//Prepable拦截器自动调用的方法
public void prepare() throws Exception {
if (employeeId == 0) {
employee = new Employee();
} else {
employee = EmployeeManager.find(employeeId);
}
}
// set、get方法
public int getEmployeeId() {
return employeeId;
}
public void setEmployeeId(int employeeId) {
this.employeeId = employeeId;
}
public List<Employee> getEmployees() {
return employees;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
public void setEmployees(List<Employee> employees) {
this.employees = employees;
}
//方法
public String list() {
employees = EmployeeManager.getEmployees();
return SUCCESS;
}
public String create() {
EmployeeManager.create(employee);
return SUCCESS;
}
public String edit() {
return SUCCESS;
}
public String update() {
EmployeeManager.update(employee);
employees = EmployeeManager.getEmployees();
return SUCCESS;
}
public String delete() {
EmployeeManager.delete(employeeId);
employees = EmployeeManager.getEmployees();
return SUCCESS;
}
}
页面显示的关键类EmployeeDAOMySQLImpl.java,截取关键的search方法用于执行sql语句提取数据库数据填充对象Employee对象,放入List<Employee>中储存,并返回。。
public List<Employee> searchEmployees(EmployeeSearchCriteria searchCriteria)
throws DAOException {
List<Employee> employees = new ArrayList<Employee>();
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
// Build the search criterias
StringBuilder criteriaSql = new StringBuilder(512);
criteriaSql.append(SEARCH_EMPLOYEES_SQL);
if (searchCriteria.getFirstName() != null) {
criteriaSql.append("firstName LIKE '%"
+ DBUtil.fixSqlFieldValue(searchCriteria.getFirstName())
+ "%' AND ");
}
if (searchCriteria.getLastName() != null) {
criteriaSql.append("lastName LIKE '%"
+ DBUtil.fixSqlFieldValue(searchCriteria.getLastName())
+ "%' AND ");
}
// Remove unused 'And' & 'WHERE'
if (criteriaSql.substring(criteriaSql.length() - 5).equals(" AND "))
criteriaSql.delete(criteriaSql.length() - 5,
criteriaSql.length() - 1);
if (criteriaSql.substring(criteriaSql.length() - 7).equals(" WHERE "))
criteriaSql.delete(criteriaSql.length() - 7,
criteriaSql.length() - 1);
try {
/*
* 注意和上述几种方法中的 PreparedStatement比较,此处用的是statement
*/
connection = getConnection();
statement = connection.createStatement();
// System.out.println(criteriaSql.toString());
resultSet = statement.executeQuery(criteriaSql.toString());
while (resultSet.next()) {
Employee employee = new Employee();
employee.setId(resultSet.getInt("id"));
employee.setFirstName(resultSet.getString("firstName"));
employee.setLastName(resultSet.getString("lastName"));
employees.add(employee);
System.out.println("运行到employee.toString():"+ employee.toString());
}
resultSet.close();
statement.close();
} catch (SQLException e) {
throw new DAOException();
} finally {
try {
connection.close();
} catch (SQLException ex) {
}
}
System.out.println("运行到searchEmployees(……)" + employees);
return employees;
}
此时employees里存储了从底层数据库提取的数据,格式是:
[{id:1,firstName:'hu',lastName:'ying'}, {id:2,firstName:'gan',lastName:'likun'}]
可是Ext能够读取的格式是json的,如下:
{employee:[{id:1,firstName:'hu',lastName:'ying'}, {id:2,firstName:'gan',lastName:'likun'}]}
困扰了很久的难点就在这儿,于是在参考了《深入浅出Ext JS》的基础下,我决定红圈圈里动刀子了
list.jsp
<%@ page contentType="application/json;charset=utf-8" import="entity.*" %><%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
out.print("{employee:"+EmployeeManager.getEmployees()+"}");
System.out.println("运行到list.jsp "+"{employee:"+EmployeeManager.getEmployees()+"}");
%>
student.js
Ext.onReady(function() { Ext.QuickTips.init(); var StudentRecord = Ext.data.Record.create([ {name: 'id', type: 'int'}, {name: 'firstName', type: 'string'}, {name: 'lastName', type: 'string'} ]); var store = new Ext.data.Store({ proxy: new Ext.data.HttpProxy({url: './list.jsp'}), reader: new Ext.data.JsonReader({ root: 'employee' },StudentRecord), remoteSort: true }); store.load({params:{start:0,limit:15}}); var columns = new Ext.grid.ColumnModel([ {header: '编号', dataIndex: 'id'}, {header: '姓氏', dataIndex: 'firstName'}, {header: '名称', dataIndex: 'lastName'} ]); columns.defaultSortable = true; // grid start var grid = new Ext.grid.GridPanel({ title: '学生信息列表', region: 'center', loadMask: true, store: store, cm: columns, sm: new Ext.grid.RowSelectionModel({singleSelect:true}), viewConfig: { forceFit: true }, bbar: new Ext.PagingToolbar({ pageSize: 15, store: store, displayInfo: true }) }); // grid end // 单击修改信息 start grid.on('rowclick', function(grid, rowIndex, event) { var record = grid.getStore().getAt(rowIndex); form.getForm().loadRecord(record); form.buttons[0].setText('修改'); }); // 单击修改信息 end // layout start var viewport = new Ext.Viewport({ layout: 'border', items: [{ region: 'north', contentEl: 'head' }, grid] }); // layout end });
于是小攻告成,有了开始的那个久违的画面 ,时间仓促,讲解不详细,等我大功告成的时候再补全咯
我未来的设想结果是这个样子滴,就是多加个表单(Form)