手工搭建亲测代码如下:
一、开项目引入SSH jar包,一般网上都能搜到;
二、SSH整合
配置文件:
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"> <!-- 数据库配置,这里是oracle 数据库 --> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"> </property> <property name="url" value="jdbc:oracle:thin:@192.168.11.23:1521:test"> </property> <property name="username" value="test"></property> <property name="password" value="test"></property> </bean> <!-- 用户sessionFactory-userInfo --> <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.Oracle9Dialect </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> <bean id="uploadAct" class="org.ssh.action.UpLoadAct" /> <bean id="downloadAct" class="org.ssh.action.FileDownLoad" /> </beans>
<?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/sucess.jsp</result> <result name="succesUp">/jsp/sucessUp.jsp</result> <result name="successquery">/jsp/query.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> <action name="upload" class="uploadAct" /> <action name="FileDownLoad" class="downloadAct" > <result name="success" type="stream"> <param name="contentType">text/plain</param> <param name="contentDisposition">attachment;fileName="${fileName}"</param> <param name="inputName">downloadFile</param> <param name="bufferSize">1024</param> </result> </action> </package> </struts>
</pre><pre name="code" class="html">
</pre><pre name="code" class="html">web.xml
</pre><pre name="code" class="html"><pre name="code" class="java"><?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>
</pre><pre name="code" class="html">
UserInfo.hbm.xml
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd "> <!-- Mapping file autogenerated by MyEclipse Persistence Tools --> <hibernate-mapping> <class name="org.ssh.pojo.Userinfo" table="USERINFO" schema="U2"> <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" /> </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" /> </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>
UserInfo.java 和 UserInfo.hbm.xml 对应,可以引入myeclipse的hibenate 组件后再配置xml文件,这样可以使用其自带的数据库映射功能自动生成 UserInfo.java和 UserInfo.hbm.xml
package org.ssh.pojo; import java.math.BigDecimal; /** * Userinfo entity. @author MyEclipse Persistence Tools */ public class Userinfo implements java.io.Serializable { // Fields private int id; private String uname; private String sex; private String password; private String telphone; private String address; // Constructors /** default constructor */ public Userinfo() { } /** minimal constructor */ public Userinfo(String uname, String sex) { this.uname = uname; this.sex = sex; } /** full constructor */ public Userinfo(String uname, String sex, String password, String telphone, String address) { this.uname = uname; this.sex = sex; this.password = password; this.telphone = telphone; this.address = address; } // Property accessors public int getId() { return this.id; } public void setId(int 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; } }
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) { e.printStackTrace(); return ERROR; } } public String doQuery(){ searchText = getParam("queryText"); users = userService.queryUsers(searchText,Userinfo.class); ActionContext.getContext().getSession().put("userquery", users); 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; } }
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 List<T> queryUserloader(String uname){ if(uname == null || "".equals(uname)) return null; 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; } }
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 (T) this.getHibernateTemplate().get(clazz, id); } }
前台jsp页面只给出登录页index.jsp 和登录成功页面 sucess.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> <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>
<%@ page language="java" import="java.util.*,com.opensymphony.xwork2.ActionContext,java.util.List,java.lang.Class,org.ssh.dao.BaseDao,org.ssh.service.UserManagerService,org.ssh.pojo.Userinfo" pageEncoding="UTF-8"%> <%@ taglib prefix="s" uri="/struts-tags" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; Object param =ActionContext.getContext().getSession().get("userinfo"); Userinfo userss=(Userinfo)param; int id=userss.getId(); String uname=userss.getUname(); String Password=userss.getPassword(); String Sex=userss.getSex(); String Telphone=userss.getTelphone(); String Address=userss.getAddress(); //String [] strs=new String[os.length]; //for(int i=0;i<os.length;i++){ // strs[i]=os[i].toString(); // System.out.println("Str["+strs[i]+"]="+strs[i]); //} //String str=param.getClass(); /////String strs=param.toString(); ///list.add(param); ///int size=list.size(); ///list.get(1); ///UserManagerService service =new UserManagerService(); %> <!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" onclick="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> <tr align="center" height="24px"> <td width="100"><%=id %></td> <td width="160"><%=uname %></td> <td width="70"><%=Sex %></td> <td width="150"><%=Telphone %></td> <td width="300"><%=Address %></td> <td width="120"> <a href="edit.action?param=0&id=<%=id %>">编辑</a> <a href="delete.action?id=<%=id %>">删除</a> </td> </tr> </table> <s:form action="upload.action" method="post" enctype="multipart/form-data">
项目目录如下,仅供参考:
<img src="http://img.blog.csdn.net/20150723105517786?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" alt="" /> <div style="margin-left:180px;margin-top: 200px;"> 文件上传: <input type="file" name="file" id="dofile""/> <input type="submit" value="上传" name="idupload" id="idupload" height="30px;" /> </div> </s:form> <div style="margin-left:180px;margin-top: 100px;" ><a href="<%=path %>/jsp/workSpace.jsp">工作台</a></div> <div style="margin-left:180px;margin-top: 100px;" ><a href="<%=path %>/jsp/downLoad.jsp">文件下载</a></div> </body> </html>