1,有了struts2的基础知识之后,先来一个简单的后端dao,做一个CRUD,基本上初级程序员都要写一下这个;
搞一个用户管理的dao来练下手,先上实体图,如图1:
根据这个得到实体类:
接下来定义基本的CRUD接口:
使用easy-db实现db的操作;
package com.cutter.web.account.dao.achieve; import java.io.IOException; import java.io.Reader; import java.math.BigDecimal; import java.net.URL; import java.nio.CharBuffer; import java.sql.Array; import java.sql.Blob; import java.sql.Clob; import java.sql.Connection; import java.sql.Date; import java.sql.NClob; import java.sql.ParameterMetaData; import java.sql.PreparedStatement; import java.sql.Ref; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Time; import java.sql.Timestamp; import java.util.Calendar; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import org.apache.log4j.Logger; import org.pureart.persistement.database.easydb.IUStH; import org.pureart.persistement.database.easydb.ParamReadStH; import org.pureart.persistement.database.easydb.ReadStH; import org.pureart.persistement.database.easydb.DB; import com.cutter.web.account.dao.entity.User; import com.cutter.web.account.dao.inter.UserDao; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; public class UserDaoAchieve extends BaseDaoAchieve<User> implements UserDao { private static final Logger log = Logger.getLogger(UserDaoAchieve.class); private static final String GETBYID_SQL = " SELECT * FROM dt_user WHERE id=? ;"; private static final String DELETEBYID_SQL = " DELETE FROM dt_user WHERE id=? ;"; private static final String LIST_ALL_SQL = " SELECT * FROM test.dt_user ;"; private static final String COUNT_ALL_SQL = " SELECT count(*) FROM dt_user ;"; private static final String LIST_ALL_BY_PAGE_SQL = " SELECT * FROM dt_user LIMIT ?,? ;"; private static final String ADD_USER_SQL = " INSERT INTO dt_user(userName,email,password,createDate,roleId) VALUES(?,?,?,?,?) ;"; private static final String MODIFY_USER_SQL = " update dt_user set userName=? , email=? , password=? , createDate=? , roleId=? WHERE id=? ;"; @Override public boolean update(final User entity) { try { if (entity.getId() > 0) {//更新 return DB.insertUpdate(MODIFY_USER_SQL, new IUStH() { @Override public void handleInsertUpdate(PreparedStatement stmt) throws SQLException { stmt.setString(1, entity.getUserName()); stmt.setString(2, entity.getEmail()); stmt.setString(3, entity.getPassword()); stmt.setDate(4, new Date(System.currentTimeMillis())); stmt.setInt(5, entity.getRoleId()); stmt.setInt(6, entity.getId()); stmt.executeUpdate(); } }); } else {//插入 return DB.insertUpdate(ADD_USER_SQL, new IUStH() { @Override public void handleInsertUpdate(PreparedStatement stmt) throws SQLException { stmt.setString(1, entity.getUserName()); stmt.setString(2, entity.getEmail()); stmt.setString(3, entity.getPassword()); stmt.setDate(4, new Date(System.currentTimeMillis())); stmt.setInt(5, entity.getRoleId()); stmt.executeUpdate(); } }); } } catch (SQLException e) { log.error("更新用户信息异常!"); e.printStackTrace(); } return false; } @Override public User get(final int id) { final User user = new User(); try { DB.select(GETBYID_SQL, new ParamReadStH() { @Override public void handleRead(ResultSet rs) throws SQLException { if (rs.next()) { handleResult(rs, user); } } @Override public void setParams(PreparedStatement stmt) throws SQLException { stmt.setInt(1, id); } }); return user; } catch (SQLException e) { log.error("查询用户信息异常!"); e.printStackTrace(); } return null; } @Override public boolean delete(final int id) { try { return DB.insertUpdate(DELETEBYID_SQL, new IUStH() { @Override public void handleInsertUpdate(PreparedStatement stmt) throws SQLException { stmt.setInt(1, id); stmt.executeUpdate(); } }); } catch (SQLException e) { log.error("删除用户异常!"); e.printStackTrace(); } return false; } @Override public boolean batchDelete(final int[] idArray) { try { return DB.insertUpdate(DELETEBYID_SQL, new IUStH() { @Override public void handleInsertUpdate(PreparedStatement stmt) throws SQLException { for (int id : idArray) { stmt.setInt(1, id); stmt.addBatch(); } stmt.executeBatch(); } }); } catch (SQLException e) { log.error("批量删除用户信息异常!"); e.printStackTrace(); } return false; } @Override public ImmutableList<User> listAll() { try { final List<User> userList = Lists.newLinkedList(); DB.select(LIST_ALL_SQL, new ReadStH() { @Override public void handleRead(ResultSet rs) throws SQLException { while (rs.next()) { User user = new User(); handleResult(rs, user); userList.add(user); } } }); log.info(userList); return ImmutableList.copyOf(userList); } catch (SQLException e) { log.error("查询所有的用户异常!"); e.printStackTrace(); } return null; } @Override public ImmutableList<User> list(final int pageSize, final int page) { try { final List<User> userList = Lists.newLinkedList(); DB.select(LIST_ALL_SQL, new ParamReadStH() { @Override public void handleRead(ResultSet rs) throws SQLException { while (rs.next()) { User user = new User(); handleResult(rs, user); userList.add(user); } } @Override public void setParams(PreparedStatement stmt) throws SQLException { int start = pageSize * (page - 1); int end = start + pageSize; stmt.setInt(1, start); stmt.setInt(2, end); } }); return ImmutableList.copyOf(userList); } catch (SQLException e) { log.error("查询所有的用户异常!"); e.printStackTrace(); } return null; } private void handleResult(ResultSet rs, User user) throws SQLException { user.setId(rs.getInt("id")); user.setUserName(rs.getString("userName")); user.setEmail(rs.getString("email")); user.setPassword(rs.getString("password")); user.setCreateDate(rs.getDate("createDate")); user.setRoleId(rs.getInt("roleId")); } @Override public int getCount() { final AtomicInteger count = new AtomicInteger(0); try { DB.select(COUNT_ALL_SQL, new ReadStH() { @Override public void handleRead(ResultSet rs) throws SQLException { if (rs.next()) { count.lazySet(rs.getInt(1)); } } }); return count.get(); } catch (SQLException e) { log.error("查询用户的数量异常!"); e.printStackTrace(); } return 0; } }
action的代码:
package com.cutter.web.account.action.user;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.struts2.interceptor.RequestAware;
import com.cutter.web.account.dao.achieve.UserDaoAchieve;
import com.cutter.web.account.dao.entity.User;
import com.cutter.web.account.dao.inter.UserDao;
import com.opensymphony.xwork2.ActionSupport;
public class UserManagerAction extends ActionSupport implements RequestAware {
private static final Logger log = Logger.getLogger(UserManagerAction.class);
private User user;
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private Map<String, Object> requestMap;
final UserDao userDao = new UserDaoAchieve();
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String listUser() throws Exception {
requestMap.put("users", userDao.listAll());
return SUCCESS;
}
public String addUser() {
log.info("add传递过来的参数:" + user);
userDao.update(user);
return SUCCESS;
}
public String editUser() {
log.info("edit传递过来的参数:" + user);
userDao.update(user);
return SUCCESS;
}
public String deleteUser() {
log.info("传递过来的id:" + getId());
userDao.delete(getId());
return SUCCESS;
}
public String listUserByPage() {
final UserDao userDao = new UserDaoAchieve();
requestMap.put("users", userDao.listAll());
return SUCCESS;
}
@Override
public void setRequest(java.util.Map<String, Object> request) {
requestMap = request;
}
@Override
public String execute() throws Exception {
return SUCCESS;
}
public String editPage() throws Exception {
requestMap.put("user", userDao.get(id));
return SUCCESS;
}
}
配置文件写法:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="user" extends="struts-default" namespace="/account">
<action name="login" class="com.cutter.web.account.action.user.LoginOutAction" method="index" >
<result name="success">/manager/adminLogin.jsp</result>
</action>
<action name="loginSubmit" class="com.cutter.web.account.action.user.LoginOutAction" method="login">
<result name="success">/manager/home.jsp</result>
<result name="input">/manager/adminLogin.jsp</result>
</action>
<action name="addUserPage" class="com.cutter.web.account.action.user.UserManagerAction" method="execute">
<result name="success">/manager/user/addList.jsp</result>
</action>
<action name="editUserPage" class="com.cutter.web.account.action.user.UserManagerAction" method="editPage">
<result name="success">/manager/user/editList.jsp</result>
</action>
<action name="listUser" class="com.cutter.web.account.action.user.UserManagerAction" method="listUser">
<result name="success"><!-- /manager/userManage/listUser.jsp-->
/manager/user/userList.jsp
</result>
</action>
<action name="deleteUser" class="com.cutter.web.account.action.user.UserManagerAction" method="deleteUser">
<result type="redirectAction">listUser
</result>
</action>
<action name="editUser" class="com.cutter.web.account.action.user.UserManagerAction" method="editUser">
<result type="redirectAction">listUser
</result>
</action>
<action name="addUser" class="com.cutter.web.account.action.user.UserManagerAction" method="addUser">
<result type="redirectAction">listUser</result>
</action>
</package>
</struts>
暂时对struts2的标签不熟悉,这里使用基本的jsp标签来展示数据:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>用户列表</title>
</head>
<body>
<a href="../account/addUserPage.do">增加用户</a>
<br>
<table width="100%" height="auto" border="2px" bordercolor="green">
<tr>
<td>id</td>
<td>用户名</td>
<td>密码</td>
<td>邮箱</td>
<td>创建日期</td>
<td>角色</td>
<td>编辑</td>
</tr>
<c:forEach var="user" items="${users}">
<tr>
<td>${user.id}</td>
<td>${user.userName}</td>
<td>${user.password}</td>
<td>${user.email}</td>
<td>${user.createDate}</td>
<td>${user.roleId}</td>
<td>
<a href="../account/editUserPage.do?id=${user.id}">编辑</a>
<a href="../account/deleteUser.do?id=${user.id}">删除</a>
</td>
</tr>
</c:forEach>
</table>
</body>
</html>
简单的实现了CRUD,效果如图:
2,tiles简单布局
打算先弄一个简单的后台模版出来,头尾和右侧导航是可以复用的,总体设计图如下:
后续接着写,先这样。