我的SSH框架实例(附源码),


  整理一下从前写的SSH框架的例子,供新人学习,使用到了注解的方式.

  源码和数据库文件在百度网盘:http://pan.baidu.com/s/1hsH3Hh6
  提取码:br27

  对新同学的建议:最好的学习方法是自己手动敲一遍,切不可看过别人写的,就觉得自己会做了

使用方式

  1、首先将项目mywork3.rar解压,导入到myeclipse中,注意修改applicationContext.xml 中用户名、密码,jdk使用1.6以上的就可以。

  解压后其目录结构如下:

  2、在mysql中新建数据库mydb

  3、导入SQL文件 user.sql

  4、启动项目,输入http://localhost:8080/mywork3/ 即可打开页面

 

源码备份

web.xml

1 <?xml version="1.0" encoding="UTF-8"?> 2 <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 4 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 5 http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> 6 <welcome-file-list> 7 <welcome-file>index.jsp</welcome-file> 8 </welcome-file-list> 9 <!-- 用来定位Spring XML文件的上下文位置 --> 10 <context-param> 11 <param-name>contextConfigLocation</param-name> 12 <param-value>classpath:applicationContext.xml</param-value> 13 </context-param> 14 <!-- spring监听 --> 15 <listener> 16 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> 17 </listener> 18 <!-- 过滤器将 Hibernate Session 绑定到请求线程中,它将自动被 Spring 的事务管理器探测到 --> 19 <filter> 20 <filter-name>openSessionInViewFilter</filter-name> 21 <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class> 22 <init-param> 23 <param-name>singleSession</param-name> 24 <param-value>false</param-value> 25 </init-param> 26 </filter> 27 <filter-mapping> 28 <filter-name>openSessionInViewFilter</filter-name> 29 <url-pattern>/*</url-pattern> 30 </filter-mapping> 31 <filter> 32 <filter-name>struts2</filter-name> 33 <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> 34 </filter> 35 <filter-mapping> 36 <filter-name>struts2</filter-name> 37 <url-pattern>/*</url-pattern> 38 </filter-mapping> 39 </web-app> View Code

 applicationContext.xml

1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 4 xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 5 xsi:schemaLocation="http://www.springframework.org/schema/beans 6 http://www.springframework.org/schema/beans/spring-beans-2.5.xsd 7 http://www.springframework.org/schema/context 8 http://www.springframework.org/schema/context/spring-context-2.5.xsd 9 http://www.springframework.org/schema/aop 10 http://www.springframework.org/schema/aop/spring-aop-2.5.xsd 11 http://www.springframework.org/schema/tx 12 http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> 13 14 <!-- 用注解方法注入bean 上边schemaLocation的三条语句顺序很重要,否则报错 --> 15 <context:annotation-config /> 16 <context:component-scan base-package="com" /> 17 18 <!-- 数据库连接池 --> 19 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 20 destroy-method="close"> 21 <property name="driverClassName" value="com.mysql.jdbc.Driver" /> 22 <property name="url" value="jdbc:mysql://localhost:3306/mydb?useUnicode=true&amp;characterEncoding=UTF-8" /> 23 <property name="username" value="root" /> 24 <property name="password" value="123456" /> 25 </bean> 26 27 <!-- 配置sessionFactory ,数据库配置在hibernate.cfg.xml中--> 28 <!--LocalSessionFactoryBean 加载bean方式 <mapping resource="com/model/User.hbm.xml"/> 29 AnnotationSessionFactoryBean 加载bean方式 <mapping class="com.model.User"/> ,它主要功能是取消了hbm.xml文件 30 --> 31 <bean id="sessionFactory" 32 class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean"> 33 <property name="dataSource" ref="dataSource" /> 34 <!-- 配置实体描述文件 --> 35 <property name="mappingResources"> 36 <list> 37 <value>com/model/User.hbm.xml</value> 38 </list> 39 </property> 40 <!--扫描com.cuangwu包下以及子包种有 @Service @Controller @Repository @Component 注解的类,一旦发现,则将其纳入到spring容器中管理 41 此spring.jar必须是 Spring2.5以上版本的,因为,Spring2.5之前org.springframework.orm.hibernate3.LocalSessionFactoryBean类中, 42 并没有 packageToScan 这个属性,只有mappingResuorces这个属性。而packageToScan这个属性正是映射包中的类,而mappingResuorces只是映射某个文件。--> 43 <!-- <property name="packagesToScan" > <list> <value>com.model</value> 44 </list> </property> --> 45 <property name="hibernateProperties"> 46 <props> 47 <prop key="hibernate.format_sql">true</prop> 48 <prop key="hibernate.hbn2dd1.auto">update</prop> 49 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 50 </props> 51 </property> 52 </bean> 53 <bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"> 54 <property name="sessionFactory" ref="sessionFactory" /> 55 </bean> 56 57 <!-- 配置事务管理器 --> 58 <bean id="transactionManager" 59 class="org.springframework.orm.hibernate3.HibernateTransactionManager"> 60 <property name="sessionFactory" ref="sessionFactory" /> 61 </bean> 62 <tx:advice id="txAdvice" transaction-manager="transactionManager"> 63 <tx:attributes> 64 <tx:method name="find*" read-only="true" /> 65 <tx:method name="add*" propagation="REQUIRED" /> 66 <tx:method name="delete*" propagation="REQUIRED" /> 67 <tx:method name="update*" propagation="REQUIRED" /> 68 </tx:attributes> 69 </tx:advice> 70 <!-- aop代理设置--> 71 <aop:config> 72 <aop:pointcut expression="execution(public * com.service..*.*(..))" 73 id="myPointcut" /> 74 <aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut" /> 75 </aop:config> 76 </beans> View Code

 struts.xml

1 <?xml version="1.0" encoding="UTF-8" ?> 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN" 3 "http://struts.apache.org/dtds/struts-2.0.dtd"> 4 <struts> 5 <constant name="struts.i18n.encoding" value="UTF-8" /> 6 <package name="struts2" extends="struts-default" namespace="/"> 7 <!-- 配置action当与spring整合,class=bean的名称(如果bean没有指定value,则首写字母要小写)) --> 8 <action name="add" class="userAction" method="addUser" > 9 <result name="success">success.jsp</result> 10 <result name="error">fail.jsp</result> 11 </action> 12 <action name="query" class="userAction" method="queryUser"> 13 <result name="success">index.jsp</result> 14 </action> 15 <action name="delete" class="userAction" method="deleteUser"> 16 <result name="success">success.jsp</result> 17 <result name="error">fail.jsp</result> 18 </action> 19 <action name="edit" class="userAction" method="editUser"> 20 <result name="editUser">editUser.jsp</result> 21 <result name="success">success.jsp</result> 22 </action> 23 </package> 24 </struts> View Code

 com.action.UserAction.java

1 package com.action; 2 3 import java.util.List; 4 import javax.annotation.Resource; 5 6 import org.apache.struts2.ServletActionContext; 7 import org.springframework.beans.factory.annotation.Autowired; 8 import org.springframework.context.annotation.Scope; 9 import org.springframework.stereotype.Component; 10 import com.model.User; 11 import com.opensymphony.xwork2.ActionSupport; 12 import com.service.UserService; 13 14 @Component("userAction") 15 @Scope("prototype") 16 public class UserAction extends ActionSupport{ 17 /** 18 * 19 */ 20 private static final long serialVersionUID = 1L; 21 @Autowired 22 private UserService userService; 23 24 private User user; 25 26 private String searchText; 27 28 private List<User> users; 29 30 public User getUser() { 31 return user; 32 } 33 public void setUser(User user) { 34 this.user = user; 35 } 36 public UserService getUserService() { 37 return userService; 38 } 39 @Resource 40 public void setUserService(UserService userService) { 41 this.userService = userService; 42 } 43 44 public String addUser(){ 45 if(userService.exits(user.getUsername())){ 46 return ERROR; 47 } 48 userService.save(user); 49 return SUCCESS; 50 } 51 52 public String queryUser(){ 53 searchText = getParam("queryText"); 54 users = userService.queryUsers(searchText); 55 return SUCCESS; 56 } 57 58 public String editUser(){ 59 try { 60 Integer param = Integer.parseInt(getParam("param")); 61 if(param == 0){ 62 Integer id = Integer.parseInt(getParam("id")); 63 user = userService.getUser( id); 64 return "editUser"; 65 }else if(param == 1){ 66 userService.modifyUser(user); 67 } 68 } catch (Exception e) { 69 e.printStackTrace(); 70 } 71 return SUCCESS; 72 } 73 74 public String deleteUser(){ 75 try { 76 Integer param = Integer.parseInt(getParam("id")); 77 userService.deleteUser(param); 78 } catch (Exception e) { 79 e.printStackTrace(); 80 } 81 return queryUser() ; 82 } 83 public String getSearchText() { 84 return searchText; 85 } 86 public void setSearchText(String searchText) { 87 this.searchText = searchText; 88 } 89 protected String getParam(String key){ 90 return ServletActionContext.getRequest().getParameter(key); 91 } 92 public List<User> getUsers() { 93 return users; 94 } 95 public void setUsers(List<User> users) { 96 this.users = users; 97 } 98 } View Code

 com.dao.UserDao.java

1 package com.dao; 2 3 import java.util.List; 4 import javax.annotation.Resource; 5 import org.springframework.orm.hibernate3.HibernateTemplate; 6 import org.springframework.stereotype.Component; 7 import com.model.User; 8 9 @Component 10 public class UserDAO { 11 private HibernateTemplate hibernateTemplate; 12 13 public HibernateTemplate getHibernateTemplate() { 14 return hibernateTemplate; 15 } 16 17 @Resource 18 public void setHibernateTemplate(HibernateTemplate hibernateTemplate) { 19 this.hibernateTemplate = hibernateTemplate; 20 } 21 22 public void save(User user){ 23 hibernateTemplate.save(user); 24 } 25 public void update(User user){ 26 hibernateTemplate.update(user); 27 } 28 public void delete(Integer id){ 29 User user=getUser(id); 30 hibernateTemplate.delete(user); 31 } 32 public User getUser(Integer id){ 33 return (User)this.hibernateTemplate.load(User.class,id); 34 } 35 public List<User> findByUsername(String username){ 36 return (List<User>) hibernateTemplate.find("from User u where u.username = ?",username); 37 } 38 public List<User> queryByUsername(String username){ 39 return (List<User>) hibernateTemplate.find("from User u where u.username like ?","%"+username+"%"); 40 } 41 public List<User> findAllUsers(){ 42 return this.getHibernateTemplate().find("from User order by id"); 43 } 44 } View Code

 com.model.User.java

1 package com.model; 2 3 import java.io.Serializable; 4 5 public class User implements Serializable{ 6 7 private static final long serialVersionUID = 1L; 8 /** 9 * 用户id 10 */ 11 private int id; 12 /** 13 * 用户名 14 */ 15 private String username; 16 /** 17 * 用户密码 18 */ 19 private String userpassword; 20 /** 21 * 用户信息 22 */ 23 private String usermessage; 24 public int getId() { 25 return id; 26 } 27 public void setId(int id) { 28 this.id = id; 29 } 30 public String getUsername() { 31 return username; 32 } 33 public void setUsername(String username) { 34 this.username = username; 35 } 36 public String getUserpassword() { 37 return userpassword; 38 } 39 public void setUserpassword(String userpassword) { 40 this.userpassword = userpassword; 41 } 42 public String getUsermessage() { 43 return usermessage; 44 } 45 public void setUsermessage(String usermessage) { 46 this.usermessage = usermessage; 47 } 48 public static long getSerialversionuid() { 49 return serialVersionUID; 50 } 51 52 53 54 } View Code

 com.model.User.hbm.xml

1 <?xml version="1.0" encoding="utf-8"?> 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 4 5 <hibernate-mapping> 6 <class name="com.model.User" table="user" catalog="mydb"> 7 <id name="id" type="java.lang.Integer"> 8 <column name="id" /> 9 <generator class="assigned"></generator> 10 </id> 11 <property name="username" type="java.lang.String"> 12 <column name="username" length="30" not-null="true" unique="true"/> 13 </property> 14 <property name="userpassword" type="java.lang.String"> 15 <column name="userpassword" length="30" not-null="true" /> 16 </property> 17 <property name="usermessage" type="java.lang.String"> 18 <column name="usermessage" length="30" /> 19 </property> 20 </class> 21 </hibernate-mapping> View Code

 com.service.UserService.java

1 package com.service; 2 import java.util.List; 3 4 import com.model.User; 5 6 public interface UserService { 7 /** 8 * 判断用户是否存在 9 */ 10 public boolean exits(String username); 11 /** 12 * 保存用户 13 */ 14 public void save(User user); 15 /** 16 * 修改用户 17 */ 18 public void modifyUser(User user); 19 /** 20 * 删除用户 21 */ 22 public void deleteUser(Integer id); 23 /** 24 * 获取指定id用户 25 */ 26 public User getUser(Integer id); 27 /** 28 * 获取用户列表 29 */ 30 public List<User> queryUsers(String username); 31 } View Code

 com.service.UserServiceImp.java

1 package com.service; 2 3 import java.util.List; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Service; 7 import org.springframework.transaction.annotation.Transactional; 8 import com.dao.UserDAO; 9 import com.model.User; 10 11 @Service("userService") 12 public class UserServiceImp implements UserService { 13 @Autowired 14 private UserDAO userDAO; 15 16 @Override 17 public boolean exits(String username){ 18 List<User> userList = userDAO.findByUsername(username); 19 if(userList.size()>0) 20 return true; 21 else 22 return false; 23 } 24 25 @Override 26 public List<User> queryUsers(String username){ 27 if(username == null || "".equals(username)) 28 return userDAO.findAllUsers(); 29 else return userDAO.queryByUsername(username); 30 } 31 32 @Override 33 public User getUser(Integer id){ 34 return userDAO.getUser(id); 35 } 36 37 @Override 38 @Transactional 39 public void save(User user){ 40 userDAO.save(user); 41 } 42 43 @Override 44 @Transactional 45 public void modifyUser(User user){ 46 userDAO.update(user); 47 } 48 49 @Override 50 @Transactional 51 public void deleteUser(Integer id){ 52 userDAO.delete(id); 53 } 54 } View Code

 com.util.HibernateUtil.java

1 package com.util; 2 3 import org.hibernate.SessionFactory; 4 import org.hibernate.cfg.Configuration; 5 6 public class HibernateUtil { 7 private static SessionFactory sf; 8 static{ 9 SessionFactory sf = new Configuration().configure().buildSessionFactory(); 10 } 11 } View Code

 editUser.jsp

1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 3 <% 4 String path = request.getContextPath(); 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 6 %> 7 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 9 <html> 10 <head> 11 <base href="<%=basePath%>"> 12 13 <title>SSH</title> 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="SSH"> 19 20 </head> 21 22 <body> 23 编辑User 24 <form action="edit.action" method="get"> 25 ID:<input type="text" name="user.id" value="${user.id}" readonly="readonly"><br/> 26 UserName:<input type="text" name="user.username" value="${user.username}"><br/> 27 UserPassword:<input type="password" name="user.userpassword" value="${user.userpassword}"><br/> 28 UserMessage:<input type="text" name="user.usermessage" value="${user.usermessage}"><br/> 29 <input type="hidden" name="param" value="1"/> 30 <input type="submit" value="提交"> 31 <input type="reset" value="重置"> 32 </form> 33 </body> 34 </html> View Code

 fail.jsp

1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme() + "://" 5 + request.getServerName() + ":" + request.getServerPort() 6 + path + "/"; 7 %> 8 9 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 10 <html> 11 <head> 12 <base href="<%=basePath%>"> 13 14 <title>fail</title> 15 <meta http-equiv="pragma" content="no-cache"> 16 <meta http-equiv="cache-control" content="no-cache"> 17 <meta http-equiv="expires" content="0"> 18 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 19 <meta http-equiv="description" content="fail"> 20 21 </head> 22 23 <body> 24 <div>25 UserName不能相同 26 <a href="query.action?queryText=">返回主页</a> 27 </body> 28 </html> View Code

 index.jsp

1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 3 <% 4 String path = request.getContextPath(); 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 6 %> 7 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 9 <html> 10 <head> 11 <base href="<%=basePath%>"> 12 13 <title>SSH</title> 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="SSH"> 19 20 </head> 21 22 <body> 23 添加user,如果姓名没有冲突,那么就添加到数据库,如果姓名冲突了就不能添加,返回失败页面 24 <form action="add.action" method="get"> 25 UserName:<input type="text" name="user.username"><br /> 26 UserPassword:<input type="password" name="user.userpassword"><br /> 27 UserMessage:<input type="text" name="user.usermessage"><br /> 28 <input type="submit" value="提交"> <input type="reset" 29 value="重置"> 30 </form> 31 根据姓名查询,若不输入,则查询全部 32 <form action="query.action" method="post"> 33 UserName: <input type="text" name="queryText" value="${searchText }" /> 34 <input type="submit" value="查询" /> 35 </form> 36 37 <table width="70%" border="1px" align="center" cellpadding="0" 38 cellspacing="0"> 39 <thead> 40 <tr bgcolor="#ff0"> 41 <th width="25%">编号</th> 42 <th width="25%">姓名</th> 43 <th width="25%">信息</th> 44 <th width="25%">操作</th> 45 </tr> 46 </thead> 47 <tbody> 48 <c:forEach var="user" items="${users }"> 49 <tr> 50 <td>${user.id}</td> 51 <td>${user.username}</td> 52 <td>${user.usermessage}</td> 53 <td><a href="edit.action?param=0&id=${user.id}">编辑</a> <a 54 href="delete.action?id=${user.id}">删除</a></td> 55 </tr> 56 </c:forEach> 57 </tbody> 58 </table> 59 60 </body> 61 </html> View Code

 success.jsp

1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> 3 <% 4 String path = request.getContextPath(); 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 6 %> 7 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 9 <html> 10 <head> 11 <base href="<%=basePath%>"> 12 13 <title>SSH</title> 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="SSH"> 19 20 </head> 21 22 <body> 23 添加user,如果姓名没有冲突,那么就添加到数据库,如果姓名冲突了就不能添加,返回失败页面 24 <form action="add.action" method="get"> 25 UserName:<input type="text" name="user.username"><br /> 26 UserPassword:<input type="password" name="user.userpassword"><br /> 27 UserMessage:<input type="text" name="user.usermessage"><br /> 28 <input type="submit" value="提交"> <input type="reset" 29 value="重置"> 30 </form> 31 根据姓名查询,若不输入,则查询全部 32 <form action="query.action" method="post"> 33 UserName: <input type="text" name="queryText" value="${searchText }" /> 34 <input type="submit" value="查询" /> 35 </form> 36 37 <table width="70%" border="1px" align="center" cellpadding="0" 38 cellspacing="0"> 39 <thead> 40 <tr bgcolor="#ff0"> 41 <th width="25%">编号</th> 42 <th width="25%">姓名</th> 43 <th width="25%">信息</th> 44 <th width="25%">操作</th> 45 </tr> 46 </thead> 47 <tbody> 48 <c:forEach var="user" items="${users }"> 49 <tr> 50 <td>${user.id}</td> 51 <td>${user.username}</td> 52 <td>${user.usermessage}</td> 53 <td><a href="edit.action?param=0&id=${user.id}">编辑</a> <a 54 href="delete.action?id=${user.id}">删除</a></td> 55 </tr> 56 </c:forEach> 57 </tbody> 58 </table> 59 60 </body> 61 </html> View Code

  

原创文章,欢迎转载,转载请注明出处

相关内容

    暂无相关文章