整理一下从前写的SSH框架的例子,供新人学习,使用到了注解的方式.
链接:https://pan.baidu.com/s/16i5dDIoDi4gOMsZfPvz6eg
提取码:pjqa
对新同学的建议:最好的学习方法是自己手动敲一遍,切不可看过别人写的,就觉得自己会做了
使用方式
1、首先将项目mywork3.rar解压,导入到myeclipse中,注意修改applicationContext.xml 中用户名、密码,jdk使用1.6以上的就可以。
解压后其目录结构如下:
2、在mysql中新建数据库mydb
3、导入SQL文件 user.sql
4、启动项目,输入http://localhost:8080/mywork3/ 即可打开页面
源码备份
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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<!-- 用来定位Spring XML文件的上下文位置 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<!-- spring监听 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 过滤器将 Hibernate Session 绑定到请求线程中,它将自动被 Spring 的事务管理器探测到 -->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>false</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<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>/*</url-pattern>
</filter-mapping>
</web-app>
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:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"> <!-- 用注解方法注入bean 上边schemaLocation的三条语句顺序很重要,否则报错 -->
<context:annotation-config />
<context:component-scan base-package="com" /> <!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="123456" />
</bean> <!-- 配置sessionFactory ,数据库配置在hibernate.cfg.xml中-->
<!--LocalSessionFactoryBean 加载bean方式 <mapping resource="com/model/User.hbm.xml"/>
AnnotationSessionFactoryBean 加载bean方式 <mapping class="com.model.User"/> ,它主要功能是取消了hbm.xml文件
-->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 配置实体描述文件 -->
<property name="mappingResources">
<list>
<value>com/model/User.hbm.xml</value>
</list>
</property>
<!--扫描com.cuangwu包下以及子包种有 @Service @Controller @Repository @Component 注解的类,一旦发现,则将其纳入到spring容器中管理
此spring.jar必须是 Spring2.5以上版本的,因为,Spring2.5之前org.springframework.orm.hibernate3.LocalSessionFactoryBean类中,
并没有 packageToScan 这个属性,只有mappingResuorces这个属性。而packageToScan这个属性正是映射包中的类,而mappingResuorces只是映射某个文件。-->
<!-- <property name="packagesToScan" > <list> <value>com.model</value>
</list> </property> -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.format_sql">true</prop>
<prop key="hibernate.hbn2dd1.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean> <!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" read-only="true" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
<!-- aop代理设置-->
<aop:config>
<aop:pointcut expression="execution(public * com.service..*.*(..))"
id="myPointcut" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="myPointcut" />
</aop:config>
</beans>
struts.xml
<?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>
<constant name="struts.i18n.encoding" value="UTF-8" />
<package name="struts2" extends="struts-default" namespace="/">
<!-- 配置action当与spring整合,class=bean的名称(如果bean没有指定value,则首写字母要小写)) -->
<action name="add" class="userAction" method="addUser" >
<result name="success">success.jsp</result>
<result name="error">fail.jsp</result>
</action>
<action name="query" class="userAction" method="queryUser">
<result name="success">index.jsp</result>
</action>
<action name="delete" class="userAction" method="deleteUser">
<result name="success">success.jsp</result>
<result name="error">fail.jsp</result>
</action>
<action name="edit" class="userAction" method="editUser">
<result name="editUser">editUser.jsp</result>
<result name="success">success.jsp</result>
</action>
</package>
</struts>
com.action.UserAction.java
package com.action; import java.util.List;
import javax.annotation.Resource; import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.model.User;
import com.opensymphony.xwork2.ActionSupport;
import com.service.UserService; @Component("userAction")
@Scope("prototype")
public class UserAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
@Autowired
private UserService userService; private User user; private String searchText; private List<User> users; public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public UserService getUserService() {
return userService;
}
@Resource
public void setUserService(UserService userService) {
this.userService = userService;
} public String addUser(){
if(userService.exits(user.getUsername())){
return ERROR;
}
userService.save(user);
return SUCCESS;
} public String queryUser(){
searchText = getParam("queryText");
users = userService.queryUsers(searchText);
return SUCCESS;
} public String editUser(){
try {
Integer param = Integer.parseInt(getParam("param"));
if(param == 0){
Integer id = Integer.parseInt(getParam("id"));
user = userService.getUser( id);
return "editUser";
}else if(param == 1){
userService.modifyUser(user);
}
} catch (Exception e) {
e.printStackTrace();
}
return SUCCESS;
} public String deleteUser(){
try {
Integer param = Integer.parseInt(getParam("id"));
userService.deleteUser(param);
} catch (Exception e) {
e.printStackTrace();
}
return queryUser() ;
}
public String getSearchText() {
return searchText;
}
public void setSearchText(String searchText) {
this.searchText = searchText;
}
protected String getParam(String key){
return ServletActionContext.getRequest().getParameter(key);
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
com.dao.UserDao.java
package com.dao; import java.util.List;
import javax.annotation.Resource;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.stereotype.Component;
import com.model.User; @Component
public class UserDAO {
private HibernateTemplate hibernateTemplate; public HibernateTemplate getHibernateTemplate() {
return hibernateTemplate;
} @Resource
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
} public void save(User user){
hibernateTemplate.save(user);
}
public void update(User user){
hibernateTemplate.update(user);
}
public void delete(Integer id){
User user=getUser(id);
hibernateTemplate.delete(user);
}
public User getUser(Integer id){
return (User)this.hibernateTemplate.load(User.class,id);
}
public List<User> findByUsername(String username){
return (List<User>) hibernateTemplate.find("from User u where u.username = ?",username);
}
public List<User> queryByUsername(String username){
return (List<User>) hibernateTemplate.find("from User u where u.username like ?","%"+username+"%");
}
public List<User> findAllUsers(){
return this.getHibernateTemplate().find("from User order by id");
}
}
com.model.User.java
package com.model; import java.io.Serializable; public class User implements Serializable{ private static final long serialVersionUID = 1L;
/**
* 用户id
*/
private int id;
/**
* 用户名
*/
private String username;
/**
* 用户密码
*/
private String userpassword;
/**
* 用户信息
*/
private String usermessage;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getUserpassword() {
return userpassword;
}
public void setUserpassword(String userpassword) {
this.userpassword = userpassword;
}
public String getUsermessage() {
return usermessage;
}
public void setUsermessage(String usermessage) {
this.usermessage = usermessage;
}
public static long getSerialversionuid() {
return serialVersionUID;
} }
com.model.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"> <hibernate-mapping>
<class name="com.model.User" table="user" catalog="mydb">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="assigned"></generator>
</id>
<property name="username" type="java.lang.String">
<column name="username" length="30" not-null="true" unique="true"/>
</property>
<property name="userpassword" type="java.lang.String">
<column name="userpassword" length="30" not-null="true" />
</property>
<property name="usermessage" type="java.lang.String">
<column name="usermessage" length="30" />
</property>
</class>
</hibernate-mapping>
com.service.UserService.java
package com.service;
import java.util.List; import com.model.User; public interface UserService {
/**
* 判断用户是否存在
*/
public boolean exits(String username);
/**
* 保存用户
*/
public void save(User user);
/**
* 修改用户
*/
public void modifyUser(User user);
/**
* 删除用户
*/
public void deleteUser(Integer id);
/**
* 获取指定id用户
*/
public User getUser(Integer id);
/**
* 获取用户列表
*/
public List<User> queryUsers(String username);
}
com.service.UserServiceImp.java
package com.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.dao.UserDAO;
import com.model.User; @Service("userService")
public class UserServiceImp implements UserService {
@Autowired
private UserDAO userDAO; @Override
public boolean exits(String username){
List<User> userList = userDAO.findByUsername(username);
if(userList.size()>0)
return true;
else
return false;
} @Override
public List<User> queryUsers(String username){
if(username == null || "".equals(username))
return userDAO.findAllUsers();
else return userDAO.queryByUsername(username);
} @Override
public User getUser(Integer id){
return userDAO.getUser(id);
} @Override
@Transactional
public void save(User user){
userDAO.save(user);
} @Override
@Transactional
public void modifyUser(User user){
userDAO.update(user);
} @Override
@Transactional
public void deleteUser(Integer id){
userDAO.delete(id);
}
}
com.util.HibernateUtil.java
package com.util; import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration; public class HibernateUtil {
private static SessionFactory sf;
static{
SessionFactory sf = new Configuration().configure().buildSessionFactory();
}
}
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>SSH</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="SSH"> </head> <body>
编辑User
<form action="edit.action" method="get">
ID:<input type="text" name="user.id" value="${user.id}" readonly="readonly"><br/>
UserName:<input type="text" name="user.username" value="${user.username}"><br/>
UserPassword:<input type="password" name="user.userpassword" value="${user.userpassword}"><br/>
UserMessage:<input type="text" name="user.usermessage" value="${user.usermessage}"><br/>
<input type="hidden" name="param" value="1"/>
<input type="submit" value="提交">
<input type="reset" value="重置">
</form>
</body>
</html>
fail.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>fail</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="fail"> </head> <body>
<div style="red;">fail</div><br/>
UserName不能相同
<a href="query.action?queryText=">返回主页</a>
</body>
</html>
index.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>SSH</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="SSH"> </head> <body>
添加user,如果姓名没有冲突,那么就添加到数据库,如果姓名冲突了就不能添加,返回失败页面
<form action="add.action" method="get">
UserName:<input type="text" name="user.username"><br />
UserPassword:<input type="password" name="user.userpassword"><br />
UserMessage:<input type="text" name="user.usermessage"><br />
<input type="submit" value="提交"> <input type="reset"
value="重置">
</form>
根据姓名查询,若不输入,则查询全部
<form action="query.action" method="post">
UserName: <input type="text" name="queryText" value="${searchText }" />
<input type="submit" value="查询" />
</form> <table width="70%" border="1px" align="center" cellpadding="0"
cellspacing="0">
<thead>
<tr bgcolor="#ff0">
<th width="25%">编号</th>
<th width="25%">姓名</th>
<th width="25%">信息</th>
<th width="25%">操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="user" items="${users }">
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.usermessage}</td>
<td><a href="edit.action?param=0&id=${user.id}">编辑</a> <a
href="delete.action?id=${user.id}">删除</a></td>
</tr>
</c:forEach>
</tbody>
</table> </body>
</html>
success.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>SSH</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="SSH"> </head> <body>
添加user,如果姓名没有冲突,那么就添加到数据库,如果姓名冲突了就不能添加,返回失败页面
<form action="add.action" method="get">
UserName:<input type="text" name="user.username"><br />
UserPassword:<input type="password" name="user.userpassword"><br />
UserMessage:<input type="text" name="user.usermessage"><br />
<input type="submit" value="提交"> <input type="reset"
value="重置">
</form>
根据姓名查询,若不输入,则查询全部
<form action="query.action" method="post">
UserName: <input type="text" name="queryText" value="${searchText }" />
<input type="submit" value="查询" />
</form> <table width="70%" border="1px" align="center" cellpadding="0"
cellspacing="0">
<thead>
<tr bgcolor="#ff0">
<th width="25%">编号</th>
<th width="25%">姓名</th>
<th width="25%">信息</th>
<th width="25%">操作</th>
</tr>
</thead>
<tbody>
<c:forEach var="user" items="${users }">
<tr>
<td>${user.id}</td>
<td>${user.username}</td>
<td>${user.usermessage}</td>
<td><a href="edit.action?param=0&id=${user.id}">编辑</a> <a
href="delete.action?id=${user.id}">删除</a></td>
</tr>
</c:forEach>
</tbody>
</table> </body>
</html>
原创文章,欢迎转载,转载请注明出处