一、数据库脚本
create database if not exists `struts2_crud_db`; USE `struts2_crud_db`; DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` varchar(32) NOT NULL, `username` varchar(50) DEFAULT NULL, `password` varchar(50) DEFAULT NULL, `age` int(11) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=gbk;
二、代码
1.页面
(1)login.jsp(登录页面)
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> </head> <body> <form action="login.action" method="post"> 用户名:<input name="user.username" type="text"> <br /> 密码:<input name="user.password" type="password"> <br /> <input value="提交" type="submit"> </form> </body> </html>
(2)list.jsp(列表页面)
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <%@ taglib prefix="s" uri="/struts-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <mce:script type="text/javascript" src="<%=path%><!-- /js/zxc.js"> // --></mce:script> <title>My JSP 'list.jsp' starting page</title> </head> <body style="align:center" mce_style="align:center"> <p> <a href="${pageContext.request.contextPath}/add.jsp" mce_href="${pageContext.request.contextPath}/add.jsp">添加</a> </p> <div> <form action="list.action" method="post" name="form"> <!-- 判断用户是否为空 --> <s:if test="(pageListData.dataList!=null)&&(!pageListData.dataList.isEmpty())"> <h2>用户列表</h2> <!-- 遍历用户 --> <table border="1"> <tr> <td> 序号 </td> <td> 用户姓名 </td> <td> 用户密码 </td> <td> 用户年龄 </td> <td> 修改 </td> <td> 删除 </td> </tr> <s:iterator value="#request.pageListData.dataList" id="u" status="st"> <tr> <td> <s:property value="#st.index+1+(currentPage-1)*pageSize" /> </td> <td> <s:property value="#u.username" /> </td> <td> <s:property value="#u.password" /> </td> <td> <s:property value="#u.age" /> </td> <td> <a href="${pageContext.request.contextPath}/update.action?user.id=${u.id}">修改</a> </td> <td> <a href="${pageContext.request.contextPath}/delete.action?user.id=${u.id}">删除</a> </td> </tr> </s:iterator> </table> <s:property value="#request.pageListData.footer" escape="false"/> </s:if> <s:else> <div> 无用户 </div> </s:else> </form> </div> </body> </html>
(3)add.jsp(增加页面)
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>用户添加</title> </head> <body> <form action="add.action" method="post"> 用户名:<input type="text" name="user.username"/><br/> 密码:<input type="text" name="user.password"/><br/> 年龄:<input type="text" name="user.age"/><br/> <input type="submit" value="提交"/> </form> </body> </html>
(4)edit.jsp(修改页面)
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <%@ taglib prefix="s" uri="/struts-tags"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>用户添加</title> </head> <body> <form action="save.action" method="post"> <input type="hidden" name="user.id"value="<s:property value='user.id'/>"/> 用户名:<input type="text" name="user.username" value="<s:property value='user.username'/>"/><br/> 密码:<input type="text" name="user.password" value="<s:property value='user.password'/>"/><br/> 年龄:<input type="text" name="user.age" value="<s:property value='user.age'/>"/><br/> <input type="submit" value="提交"/> </form> </body> </html>
2.模型层
(1)User.java
package bean; /** * User entity. @author MyEclipse Persistence Tools */ public class User implements java.io.Serializable { // Fields private String id; private String username; private String password; private Integer age; // Constructors /** default constructor */ public User() { } /** minimal constructor */ public User(String id) { this.id = id; } /** full constructor */ public User(String id, String username, String password, Integer age) { this.id = id; this.username = username; this.password = password; this.age = age; } // Property accessors public String getId() { return this.id; } public void setId(String id) { this.id = id; } public String getUsername() { return this.username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public Integer getAge() { return this.age; } public void setAge(Integer age) { this.age = age; } }
(2)User.hbm.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="bean.User" table="user" catalog="struts2_crud_db"> <id name="id" type="java.lang.String"> <column name="id" length="32" /> <generator class="uuid.hex" /> </id> <property name="username" type="java.lang.String"> <column name="username" length="50" /> </property> <property name="password" type="java.lang.String"> <column name="password" length="50" /> </property> <property name="age" type="java.lang.Integer"> <column name="age" /> </property> </class> </hibernate-mapping>
3.DAO层
(1)BaseHibernateDAO.java
package dao; import org.hibernate.Session; /** * Data access object (DAO) for domain model * @author MyEclipse Persistence Tools */ public class BaseHibernateDAO implements IBaseHibernateDAO { public Session getSession() { return HibernateSessionFactory.getSession(); } }
(2)IBaseHibernateDAO.java
package dao; import org.hibernate.Session; /** * Data access interface for domain model * @author MyEclipse Persistence Tools */ public interface IBaseHibernateDAO { public Session getSession(); }
(3)HibernateSessionFactory.java
package dao; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.cfg.Configuration; /** * Configures and provides access to Hibernate sessions, tied to the * current thread of execution. Follows the Thread Local Session * pattern, see {@link http://hibernate.org/42.html }. */ public class HibernateSessionFactory { /** * Location of hibernate.cfg.xml file. * Location should be on the classpath as Hibernate uses * #resourceAsStream style lookup for its configuration file. * The default classpath location of the hibernate config file is * in the default package. Use #setConfigFile() to update * the location of the configuration file for the current session. */ private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml"; private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>(); private static Configuration configuration = new Configuration(); private static org.hibernate.SessionFactory sessionFactory; private static String configFile = CONFIG_FILE_LOCATION; static { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } private HibernateSessionFactory() { } /** * Returns the ThreadLocal Session instance. Lazy initialize * the <code>SessionFactory</code> if needed. * * @return Session * @throws HibernateException */ public static Session getSession() throws HibernateException { Session session = (Session) threadLocal.get(); if (session == null || !session.isOpen()) { if (sessionFactory == null) { rebuildSessionFactory(); } session = (sessionFactory != null) ? sessionFactory.openSession() : null; threadLocal.set(session); } return session; } /** * Rebuild hibernate session factory * */ public static void rebuildSessionFactory() { try { configuration.configure(configFile); sessionFactory = configuration.buildSessionFactory(); } catch (Exception e) { System.err .println("%%%% Error Creating SessionFactory %%%%"); e.printStackTrace(); } } /** * Close the single hibernate session instance. * * @throws HibernateException */ public static void closeSession() throws HibernateException { Session session = (Session) threadLocal.get(); threadLocal.set(null); if (session != null) { session.close(); } } /** * return session factory * */ public static org.hibernate.SessionFactory getSessionFactory() { return sessionFactory; } /** * return session factory * * session factory will be rebuilded in the next call */ public static void setConfigFile(String configFile) { HibernateSessionFactory.configFile = configFile; sessionFactory = null; } /** * return hibernate configuration * */ public static Configuration getConfiguration() { return configuration; } }
(4)UserDAO.java
package dao; import java.util.HashMap; import java.util.List; import java.util.Map; import org.hibernate.LockMode; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Example; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import bean.User; public class UserDAO extends BaseHibernateDAO { private static final Logger log = LoggerFactory.getLogger(UserDAO.class); // property constants public static final String USERNAME = "username"; public static final String PASSWORD = "password"; public static final String AGE = "age"; public boolean save(User transientInstance) { boolean flag = false; try { Session session = getSession(); Transaction tr = session.beginTransaction(); session.save(transientInstance); tr.commit(); flag = true; session.flush(); session.close(); log.debug("save successful"); } catch (RuntimeException re) { log.error("save failed", re); throw re; } return flag; } public boolean update(User transientInstance) { boolean flag = false; try { Session session = getSession(); Transaction tr = session.beginTransaction(); session.update(transientInstance); tr.commit(); flag = true; session.flush(); session.close(); log.debug("update successful"); } catch (RuntimeException re) { log.error("update failed", re); throw re; } return flag; } public boolean delete(User persistentInstance) { boolean flag = false; try { Session session = getSession(); Transaction tr = session.beginTransaction(); session.delete(persistentInstance); tr.commit(); flag = true; session.flush(); session.close(); log.debug("delete successful"); } catch (RuntimeException re) { log.error("delete failed", re); throw re; } return flag; } public User findById(java.lang.String id) { log.debug("getting User instance with id: " + id); try { User instance = (User) getSession().get("bean.User", id); return instance; } catch (RuntimeException re) { log.error("get failed", re); throw re; } } public Map findAll(int currentPage, int pageSize) { Map map = null; List dataList = null; try { map = new HashMap(); String queryString = "from User"; Session session = getSession(); Query queryObject = session.createQuery(queryString); queryObject.setFirstResult((currentPage-1) * pageSize).setMaxResults( pageSize); dataList = queryObject.list(); map.put("dataList", dataList); String hql = "select count(*) from User"; queryObject = getSession().createQuery(hql); map.put("totalCount", queryObject.list().get(0)); session.flush(); session.close(); } catch (RuntimeException re) { throw re; } return map; } public User checkLogin(User user) { List list = null; try { String hql = "from User where username=? and password=?"; Session session=getSession(); Query query = session.createQuery(hql); query.setString(0, user.getUsername()); query.setString(1, user.getPassword()); list = query.list(); session.flush(); session.close(); } catch (Exception e) { e.printStackTrace(); } return list != null && list.size() > 0 ? (User) list.get(0) : null; } public static void main(String args[]) { User user = new User(); user.setUsername("zxc"); user.setPassword("123"); user.setAge(23); new UserDAO().save(user); } }
4.业务层
UserService.java
package service; import java.util.List; import java.util.Map; import bean.User; import dao.UserDAO; public class UserService { private UserDAO dao=new UserDAO(); public boolean save(User transientInstance) { return dao.save(transientInstance); } public boolean update(User transientInstance) { return dao.update(transientInstance); } public boolean delete(User persistentInstance) { return dao.delete(persistentInstance); } public User findById(String id) { return dao.findById(id); } public Map findAll(int currentPage, int pageSize) { return dao.findAll(currentPage, pageSize); } public User checkLogin(User user){ return dao.checkLogin(user); } }
5.公用util
(1)PageListData.java(分页组件)
package util; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; public class PageListData { private List dataArray = null; private int totalCount = 0; private int pageSize = 0; private int currentPage = 1; private int totalPage=0; private List dataList; private String footer; public PageListData(){} public PageListData(int totalCount,int pageSize,int currentPage,List dataList){ setTotalCount(totalCount); setPageSize(pageSize); setCurrentPage(currentPage); setDataList(dataList); setFooter(getFooter()); } public List getDataArray() { return dataArray; } public void setDataArray(List dataArray) { this.dataArray = dataArray; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public List getDataList() { return dataList; } public void setDataList(List dataList) { this.dataList = dataList; } public int getTotalPage() { if (totalCount % pageSize == 0) { return totalCount / pageSize; } else { return totalCount / pageSize + 1; } } public void setTotalPage(int totalPage) { this.totalPage = totalPage; } public void setFooter(String footer){ this.footer=footer; } public String getFooter() { StringBuffer pageStr = new StringBuffer(""); pageStr.append("<p class='pages'>"); int totalPages = getTotalPage(); int prevPage = getCurrentPage() - 1; int nextPage=getCurrentPage()+1; pageStr.append("<span style="color:#049ed0;" mce_style="color:#049ed0;">第" + currentPage + "页/共" + totalPages + "页</span> "); if (currentPage > 1) pageStr .append("<span><a style="cursor: pointer;text-decoration:underline;color:#049ed0;" mce_style="cursor: pointer;text-decoration:underline;color:#049ed0;"onclick='document.getElementById(/"pages/").value=1;document.getElementById(/"pages/").form.submit();'>首页</a></span> "); if (currentPage == 1) pageStr .append("<span style="color:#049ed0;" mce_style="color:#049ed0;">首页</span> "); if (currentPage > 1) pageStr .append("<span><a style="cursor: pointer;text-decoration:underline;color:#049ed0;" mce_style="cursor: pointer;text-decoration:underline;color:#049ed0;" onclick='document.getElementById(/"pages/").value=" + prevPage + ";document.getElementById(/"pages/").form.submit();'>上一页</a></span> "); if (currentPage <= 1) pageStr .append("<span style="color:#049ed0;" mce_style="color:#049ed0;">上一页</span> "); if (currentPage < totalPages) pageStr .append("<span><a style="cursor: pointer;text-decoration:underline;color:#049ed0;" mce_style="cursor: pointer;text-decoration:underline;color:#049ed0;" onclick='document.getElementById(/"pages/").value=" + nextPage + ";document.getElementById(/"pages/").form.submit();'>下一页</a></span> "); if (currentPage >= totalPages) pageStr.append("<span style="color:#049ed0;" mce_style="color:#049ed0;">下一页</span> "); if (currentPage < totalPages) pageStr .append("<span><a style="cursor: pointer;text-decoration:underline;color:#049ed0;" mce_style="cursor: pointer;text-decoration:underline;color:#049ed0;" onclick='document.getElementById(/"pages/").value=" + totalPages + ";document.getElementById(/"pages/").form.submit();'>末页</a></span> "); if (currentPage == totalPages) pageStr .append("<span style="color:#049ed0;" mce_style="color:#049ed0;"末页</span> "); pageStr .append("<span style="color:#049ed0;" mce_style="color:#049ed0;">跳转至第:<input type='text' value='" + currentPage + "'id='jumpPageBox' size='4' onblur='checkCurrentPage(document.getElementById(/"jumpPageBox/").value," + totalPages + ")'/>页<input style="color:#049ed0;" mce_style="color:#049ed0;" type='button' value='跳转' onclick='document.getElementById(/"pages/").value=document.getElementById(/"jumpPageBox/").value;document.getElementById(/"pages/").form.submit();'/></span>"); pageStr.append("</p>"); pageStr.append("<input type='hidden' value='" + currentPage + "' name='currentPage' id='pages' />"); pageStr.append("<input type='hidden' value='" + pageSize + "' name='pageSize' id='pageSize' />"); return pageStr.toString(); } }
(2)zxc.js
function $(id){ return document.getElementById(id); } function refresh(){ $("imgCode").src="<%=path%>/servlet/textBufferedImage?timestampt="+new Date().getTime(); alert($("imgCode").src); } function del(name){ if(confirm("你确定要删除该文件吗?")){ window.location.href=$("path").value+"/fileUpDownLoad.do?method=deleteFile&filesavename="+name; } } function query(){ window.location.href=$("path").value+"/fileUpDownLoad.do?method=getFileList"; } function download(name){ var url=$("path").value+"/fileUpDownLoad.do?method=downloadFile&downfilename="+name; window.location.href=url; } function checkCurrentPage(input,totalPages){ if(input.match(/^/D*$/)){ alert("只能输入数字!"); document.getElementById("jumpPageBox").value=document.getElementById("pages").value; document.getElementById("jumpPageBox").focus(); }else if(input>totalPages||input.value<=0){ alert("对不起,你输入的页码有误!"); document.getElementById("jumpPageBox").value=document.getElementById("pages").value; document.getElementById("jumpPageBox").focus(); } } function showInfo(info){ var width=400; var height=300; windowX=(screen.width-width)/2; windowY=(screen.height-height)/2; features="top="+windowY+",left="+windowX+",width="+width+",height="+height+",menubar=no,resizable=no"; window.open($("path").value+"/fileUpDownLoad.do?method=showFileInfo&info="+info,"",features); } function openUpwin(){ var width=700; var height=500; windowX=(screen.width-width)/2; windowY=(screen.height-height)/2; features="top="+windowY+",left="+windowX+",width="+width+",height="+height+",menubar=no,resizable=no"; window.open("uploadfile.jsp","",features); } function quit(){ window.location.href=$("path").value+"/fileUpDownLoad.do?method=logout"; }
6.业务逻辑Action层
UserAction.java
package action; import java.util.HashMap; import java.util.List; import java.util.Map; import service.UserService; import util.PageListData; import bean.User; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; import dao.UserDAO; public class UserAction extends ActionSupport { private User user; private UserService service=new UserService(); private PageListData pageListData; private int currentPage=1; private int pageSize=2; public UserService getService() { return service; } public void setService(UserService service) { this.service = service; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public String login(){ User u=service.checkLogin(user); if(u!=null){ ActionContext.getContext().getSession().put("user", user); return "success"; }else{ return "input"; } } public String add(){ if(service.save(user)) return "success"; else return "add"; } public String update(){ user=service.findById(user.getId()); return "update"; } public String list(){ Map map=service.findAll(currentPage,pageSize); pageListData=new PageListData( Integer.parseInt(map.get("totalCount").toString()),pageSize,currentPage,(List)map.get("dataList")); return "list"; } public String save(){ User u=service.findById(user.getId()); u.setUsername(user.getUsername()); u.setPassword(user.getPassword()); u.setAge(user.getAge()); if(service.update(u)) return "success"; else return "update"; } public String delete(){ User u=service.findById(user.getId()); if(service.delete(u)) return "success"; else return "success"; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public void setPageListData(PageListData pageListData) { this.pageListData = pageListData; } public PageListData getPageListData() { return pageListData; } }
7.配置文件
(1)struts.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"> <struts> <package name="default" extends="struts-default" namespace="/"> <action name="*" class="action.UserAction" method="{1}"> <result name="success" type="redirect">list.action</result> <result name="list" >list.jsp</result> <result name="input">login.jsp</result> <result name="add">add.jsp</result> <result name="update">edit.jsp</result> </action> </package> </struts>
(2)Hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"> <!-- Generated by MyEclipse Hibernate Tools. --> <hibernate-configuration> <session-factory> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <property name="connection.url">jdbc:mysql://localhost:3306/struts2_crud_db</property> <property name="connection.username">root</property> <property name="connection.password">123</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="myeclipse.connection.profile">mysql5</property> <property name="show_sql">true</property> <mapping resource="dao/User.hbm.xml"/> </session-factory> </hibernate-configuration>
(3)web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app>
(4)log4j.properties
log4j.rootLogger=INFO,A1 # /u8f93/u51fa/u5230/u63a7/u5236/u53f0 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%d{yyyy-MM-dd HH/:mm/:ss} [/u65E5/u5FD7/u4FE1/u606F] %m%n
8.运行效果图
此工程已经上传到csdn,请搜索struts2CRUD下载