转自:http://blog.csdn.net/yunji3344/article/details/8297182
我们来写一个简单的例子,这个例子是参考网上的一个工程
完整的工程目录如下:
首先我们创建好Userinfo.java , BaseDao.java , UserManagerService.java还有UserManagerAct.java这三个文件。并放到相应的包里面去分别是org.ssh.pojo,org.ssh.dao,org.ssh.service,org.ssh.action。如上图所示;下面逐一分析这个几个类
1.Userinfo.java 这是一个pojo类,也就是实体类。先看看代码先
- package org.ssh.pojo;
- /**
- * 用户信息
- */
- public class Userinfo implements java.io.Serializable {
- private static final long serialVersionUID = 5866268712137826050L;
- /**用户id*/
- private Integer id;
- /**用户名*/
- private String uname;
- /**性别*/
- private String sex;
- /**密码*/
- private String password;
- /**电话号码*/
- private String telphone;
- /**住址*/
- private String address;
- public Userinfo() {
- }
- public Integer getId() {
- return this.id;
- }
- public void setId(Integer id) {
- this.id = id;
- }
- public String getUname() {
- return this.uname;
- }
- public void setUname(String uname) {
- this.uname = uname;
- }
- public String getSex() {
- return this.sex;
- }
- public void setSex(String sex) {
- this.sex = sex;
- }
- public String getPassword() {
- return this.password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- public String getTelphone() {
- return this.telphone;
- }
- public void setTelphone(String telphone) {
- this.telphone = telphone;
- }
- public String getAddress() {
- return this.address;
- }
- public void setAddress(String address) {
- this.address = address;
- }
- }
- <?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="org.ssh.pojo.Userinfo" table="userinfo" catalog="myssh">
- <id name="id" type="java.lang.Integer">
- <column name="id" />
- <generator class="assigned"></generator>
- </id>
- <property name="uname" type="java.lang.String">
- <column name="uname" length="30" not-null="true" unique="true"/>
- </property>
- <property name="sex" type="java.lang.String">
- <column name="sex" length="10" not-null="true" />
- </property>
- <property name="password" type="java.lang.String">
- <column name="password" length="20" not-null="true" />
- </property>
- <property name="telphone" type="java.lang.String">
- <column name="telphone" length="15" />
- </property>
- <property name="address" type="java.lang.String">
- <column name="address" length="50" />
- </property>
- </class>
- </hibernate-mapping>
2.BaseDao.java 这个类主要实现数据库的操作,这里只是一些简单的实现。上代码
- package org.ssh.dao;
- import java.io.Serializable;
- import java.util.List;
- import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
- /**
- * 数据库io操作
- */
- public class BaseDao extends HibernateDaoSupport {
- /**查询*/
- public <T> List<T> getObjects(String queryString){
- return (List<T>)this.getHibernateTemplate().find(queryString);
- }
- /**查询所有*/
- public <T> List<T> getAllObjects(Class<T> clazz){
- return this.getHibernateTemplate().loadAll(clazz);
- }
- /**添加一个*/
- public <T> void addObject(T clazz){
- this.getHibernateTemplate().save(clazz);
- }
- /**更新指定的*/
- public <T> void updateObject(T clazz){
- this.getHibernateTemplate().update(clazz);
- }
- /**删除指定的*/
- public <T> void deleteObject(T clazz){
- this.getHibernateTemplate().delete(clazz);
- }
- /**通过id获取*/
- public <T> T getObject(Class<T> clazz,Serializable id){
- return this.getHibernateTemplate().get(clazz, id);
- }
- }
3.UserManagerService.java 用户管理业务逻辑的实现,这个是业务逻辑层,业务逻辑在这里实现,这里操作数据库是调用上一层dao层代码。上代码
- package org.ssh.service;
- import java.util.List;
- import org.ssh.dao.BaseDao;
- /**
- * 用户管理业务逻辑的实现
- * */
- public class UserManagerService<T> {
- private BaseDao dao;
- public T doLogin(String userName,String password) throws Exception{
- if(userName == null || password == null) return null;
- String queryString = "SELECT u FROM Userinfo u WHERE u.uname = '"+userName +"' AND u.password = "+password;
- List<T> users = dao.getObjects(queryString);
- return users.get(0);
- }
- public List<T> queryUsers(String uname,Class<T> clazz){
- if(uname == null || "".equals(uname))
- return dao.getAllObjects(clazz);
- String queryString = "SELECT u FROM Userinfo u WHERE u.uname like '"+uname+"%'";
- return dao.getObjects(queryString);
- }
- public void addUser(T user) throws Exception{
- dao.addObject(user);
- }
- public void modifyUser(T user) throws Exception{
- dao.updateObject(user);
- }
- public void deleteUser(int id,Class<T> clazz) throws Exception{
- T u = dao.getObject(clazz, id);
- dao.deleteObject(u);
- }
- public T getUser(Class<T> clazz, int id){
- return dao.getObject(clazz, id);
- }
- public BaseDao getDao() {
- return dao;
- }
- public void setDao(BaseDao dao) {
- this.dao = dao;
- }
- }
4.UserManagerAct.java 这是一个action,充当视图控制器的角色,也就是mvc中的c。直接与外部打交道,可以供客户端调用,也可以和jsp等调用,这一层通过调用业务逻辑层来完成功能。不直接操作数据库,业务逻辑也不在这里实现。一些界面控制可以在这里实现,上代码
- package org.ssh.action;
- import java.util.List;
- import org.apache.struts2.ServletActionContext;
- import org.ssh.pojo.Userinfo;
- import org.ssh.service.UserManagerService;
- import com.opensymphony.xwork2.ActionContext;
- import com.opensymphony.xwork2.ActionSupport;
- /**
- * 用户管理控制器
- * */
- public class UserManagerAct extends ActionSupport {
- private static final long serialVersionUID = -281275682819237996L;
- private Userinfo user = new Userinfo();
- private UserManagerService<Userinfo> userService;
- private List<Userinfo> users;
- private String searchText;
- public String doLogin(){
- if(this.user.getUname() == null || this.user.getPassword() == null) return INPUT;
- try {
- Userinfo user = userService.doLogin(this.user.getUname(), this.user.getPassword());
- if(user != null){
- ActionContext.getContext().getSession().put("userinfo", user);
- return doQuery();
- }else
- return INPUT;
- } catch (Exception e) {
- return ERROR;
- }
- }
- public String doQuery(){
- searchText = getParam("queryText");
- users = userService.queryUsers(searchText,Userinfo.class);
- return SUCCESS;
- }
- public String doAdd(){
- String result = "";
- try {
- String param = getParam("param");
- if(Integer.parseInt(param) > 0){
- user.setId(0);
- userService.addUser(user);
- result = doQuery();
- }else
- result = "addUser";
- } catch (Exception e) {
- e.printStackTrace();
- }
- return result;
- }
- public String doEdit(){
- try {
- Integer param = Integer.parseInt(getParam("param"));
- if(param == 0){
- Integer id = Integer.parseInt(getParam("id"));
- user = userService.getUser(Userinfo.class, id);
- return "editUser";
- }else if(param == 1){
- userService.modifyUser(user);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return doQuery();
- }
- public String doDelete(){
- try {
- Integer param = Integer.parseInt(getParam("id"));
- userService.deleteUser(param,Userinfo.class);
- } catch (Exception e) {
- e.printStackTrace();
- }
- return doQuery();
- }
- protected String getParam(String key){
- return ServletActionContext.getRequest().getParameter(key);
- }
- public UserManagerService<Userinfo> getUserService() {
- return userService;
- }
- public void setUserService(UserManagerService<Userinfo> userService) {
- this.userService = userService;
- }
- public List<Userinfo> getUsers() {
- return users;
- }
- public Userinfo getUser() {
- return user;
- }
- public void setUser(Userinfo user) {
- this.user = user;
- }
- public String getSearchText() {
- return searchText;
- }
- public void setSearchText(String searchText) {
- this.searchText = searchText;
- }
- }
至此所有的java代码已经完成接下来我们还要配置一些内容,目的是让ssh使用上面的代码。
1.配置applicationContext.xml文件
- <?xml version="1.0" encoding="UTF-8"?>
- <beans
- xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:p="http://www.springframework.org/schema/p"
- xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
- <!-- 数据库配置 -->
- <bean id="dataSource"
- class="org.apache.commons.dbcp.BasicDataSource">
- <property name="driverClassName"
- value="com.mysql.jdbc.Driver">
- </property>
- <property name="url"
- value="jdbc:mysql://localhost:3306/myssh">
- </property>
- <property name="username" value="anan"></property>
- <property name="password" value="xxxxxx"></property>
- </bean>
- <!-- -->
- <bean id="sessionFactory"
- class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
- <property name="dataSource">
- <ref bean="dataSource" />
- </property>
- <property name="hibernateProperties">
- <props>
- <prop key="hibernate.dialect">
- org.hibernate.dialect.MySQLDialect
- </prop>
- <prop key="hibernate.hbm2ddl.auto">update</prop>
- </props>
- </property>
- <!-- 配置实体描述文件 -->
- <property name="mappingResources">
- <list>
- <value>org/ssh/pojo/Userinfo.hbm.xml</value>
- </list>
- </property>
- </bean>
- <bean id="userAct" class="org.ssh.action.UserManagerAct" scope="prototype">
- <property name="userService" ref="userService"></property>
- </bean>
- <bean id="userService" class="org.ssh.service.UserManagerService">
- <property name="dao" ref="dao"></property>
- </bean>
- <bean id="dao" class="org.ssh.dao.BaseDao">
- <property name="sessionFactory" ref="sessionFactory"/>
- </bean>
- </beans>
这里主要是配置了hibernate加载我们的实体类Userinfo
同时配置了spring加载我们的dao,service和action...
2.struts.xml 配置action
- <?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>
- <constant name="struts.objectFactory" value="spring" />
- <package name="MySSH" extends="struts-default">
- <global-results>
- <result name="error">/jsp/error.jsp</result>
- <result name="success">/jsp/success.jsp</result>
- </global-results>
- <action name="userManagerAct" class="userAct" method="doLogin">
- <result name="login">/index.jsp</result>
- </action>
- <action name="query" class="userAct" method="doQuery" />
- <action name="delete" class="userAct" method="doDelete" />
- <action name="edit" class="userAct" method="doEdit">
- <result name="editUser">/jsp/editUser.jsp</result>
- </action>
- <action name="add" class="userAct" method="doAdd">
- <result name="addUser">/jsp/addUser.jsp</result>
- </action>
- </package>
- </struts>
3.最后配置web.xml
- <?xml version="1.0" encoding="UTF-8"?>
- <web-app version="3.0"
- 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_3_0.xsd">
- <display-name></display-name>
- <!-- Spring配置和监听start -->
- <context-param>
- <param-name>contextConfigLocation</param-name>
- <param-value>/WEB-INF/classes/application*.xml</param-value>
- </context-param>
- <listener>
- <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
- </listener>
- <!--end-->
- <welcome-file-list>
- <welcome-file>index.jsp</welcome-file>
- </welcome-file-list>
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>
- org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
- </filter-class>
- </filter>
- <filter-mapping>
- <filter-name>struts2</filter-name>
- <url-pattern>*.action</url-pattern>
- </filter-mapping></web-app>
好了,配置完成了。接下来还要写一些jsp文件让这个蛋疼的东西飞起来
1.index.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- 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>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- </head>
- <body>
- <font size="4">这个一个 struts2,spring 和 hibernate 使用的例子。请用以下账号密码登录<br>
- 默认账号/密码: <font color="red">anan/123</font><br>
- <br>请事先在数据库插入用户信息
- </font>
- <br>
- <br>
- <form action="userManagerAct.action" method="post">
- <table>
- <tr>
- <td>username</td><td><input type="text" name="user.uname"/></td>
- <td>password</td><td><input type="password" name="user.password"/></td><td>密 码</td><td></td>
- </tr>
- <tr>
- <td colspan="2">
- <input type="submit" value="submit">
- <input type="reset" value="reset">
- </td>
- </tr>
- </table>
- </form>
- </body>
- </html>
2.addUser.jsp
- <%@ 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+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>user list page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- </head>
- <body>
- <form action="add.action" method="post">
- <table width="500" align="center">
- <caption>ADD USER INFORMATION</caption>
- <tr height="26px">
- <td width="150px" align="right">UNAME</td>
- <td width="350px">
- <input type="hidden" name="param" value="1"/>
- <input type="text" name="user.uname" value="${user.uname }"/>
- </td>
- </tr>
- <tr height="26px">
- <td align="right">PASSWORD</td>
- <td><input type="password" name="user.password" value="${user.password }"/></td>
- </tr>
- <tr height="26px">
- <td align="right">SEX</td>
- <td>
- <select name="user.sex">
- <option value="male">male</option>
- <option value="female">female</option>
- </select>
- </td>
- </tr>
- <tr height="26px">
- <td align="right">TELPHONE</td>
- <td><input type="text" name="user.telphone" value="${user.telphone }"/></td>
- </tr>
- <tr height="26px">
- <td align="right">ADDRESS</td>
- <td><input type="text" name="user.address" value="${user.address }"/></td>
- </tr>
- <tr height="26px">
- <td colspan="2" align="center" width="500">
- <input type="submit" value="Save"/>
- <input type="button" value="Back" onclick="window.history.back(-1)"/>
- </td>
- </tr>
- </table>
- </form>
- </body>
- </html>
3.editUser.jsp
- <%@ 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+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>user list page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- </head>
- <body>
- <form action="edit.action" method="post">
- <table width="500" align="center">
- <caption>User Information Edit</caption>
- <tr height="26px">
- <td width="150px" align="right">NO.</td>
- <td width="350px">
- <input type="text" name="user.id" value="${user.id }" readonly="readonly"/>
- <input type="hidden" name="user.password" value="${user.password }"/>
- <input type="hidden" name="param" value="1"/>
- </td>
- </tr>
- <tr height="26px">
- <td width="160" align="right">UNAME</td>
- <td><input type="text" name="user.uname" value="${user.uname }"/></td>
- </tr>
- <tr height="26px">
- <td width="70" align="right">SEX</td>
- <td>
- <select name="user.sex">
- <option value="male">male</option>
- <option value="female">female</option>
- </select>
- </td>
- </tr>
- <tr height="26px">
- <td width="150" align="right">TELPHONE</td>
- <td><input type="text" name="user.telphone" value="${user.telphone }"/></td>
- </tr>
- <tr height="26px">
- <td width="300" align="right">ADDRESS</td>
- <td><input type="text" name="user.address" value="${user.address }"/></td>
- </tr>
- <tr height="26px">
- <td colspan="2" align="center">
- <input type="submit" value="Save"/>
- <input type="button" value="Back" onclick="window.history.back(-1)"/>
- </td>
- </tr>
- </table>
- </form>
- </body>
- </html>
4.error.jsp
- <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
- <%
- 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>My JSP 'error.jsp' starting page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <!--
- <link rel="stylesheet" type="text/css" href="styles.css">
- -->
- </head>
- <body>
- 登录失败,2秒后自动转到登录页面....
- <script type="text/javascript">
- setTimeout(reDo, 2000);
- function reDo(){
- window.location.href = "/struts2_spring_hibernate1.0/index.jsp";
- }
- </script>
- </body>
- </html>
5.sucess.jsp
- <%@ 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+"/";
- %>
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <base href="<%=basePath%>">
- <title>user list page</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- </head>
- <body>
- <form action="query.action" method="post">
- <table align="center">
- <tr>
- <td style="vertical-align: middle;">USERNAME
- <input type="text" style="width: 300px;height: 30px;font-size: 16px" name="queryText" value="${searchText }"/>
- <input type="submit" value="Query" style="width: 100px;height: 30px;font-size: 16px"/>
- <input type="button" value="Add" style="width: 100px;height: 30px;font-size: 16px"
- οnclick="window.location.href='add.action?param=0'"/>
- </td>
- </tr>
- </table>
- </form>
- <table align="center" border="1" cellpadding="0" cellspacing="0" bordercolor="#3366cc">
- <tr align="center" bgcolor="#3399cc" height="26px">
- <td width="100">NO.</td>
- <td width="160">UNAME</td>
- <td width="70">SEX</td>
- <td width="150">TELPHONE</td>
- <td width="300">ADDRESS</td>
- <td width="120">EDIT/DELETE</td>
- </tr>
- <c:forEach var="user" items="${users }">
- <tr align="center" height="24px">
- <td width="100">${user.id}</td>
- <td width="160">${user.uname}</td>
- <td width="70">${user.sex }</td>
- <td width="150">${user.telphone }</td>
- <td width="300">${user.address}</td>
- <td width="120">
- <a href="edit.action?param=0&id=${user.id}">编辑</a>
- <a href="delete.action?id=${user.id}">删除</a>
- </td>
- </tr>
- </c:forEach>
- </table>
- </body>
- </html>
全部文件应该都搞定了,相比上一次的工程需要添加一些jar包,稍后我把整个工程代码上传。或者大家自己去找缺少的jar包
运行一下:
程序运行成功,有点成就感...
总结一下:
基于ssh开发环境搭建相比起来确实麻烦不少,特别是jar的依赖,而且要整套搞起来东西还是挺多的。但是搞鼓完了之后收获还是蛮大的,之前学习的很多概念性的东西都不理解,搞完这个之后貌似都有点感觉了。ssh真不愧是经典的框架之一,下次我将用注解来实现
工程下载地址:
http://download.csdn.net/detail/yunji3344/4890206