java业界的框架之多,品类之繁可谓浩如烟海。就web开发而言,大多遵从MVC的设计原则,web层struts 、springMVC 持久化层hibernate 、 mybatis 还有与其他业务服务的应用容器如ejb spring 等世人皆知。 本文以案例的形式简单介绍下Spring3.2+Struts2.1.8+Mybatis3.2.7 开发框架。
项目结构如下:
需要引入的jar包
ok jar包都引入完成了,下面开始配置一些配置文件
注: 由于mybatis3发布的时间晚与spring3,故mybatis3与spring3整合的jar包由mybatis提供。如mybatis-spring-1.2.1.jar 就是mybatis团队开发的用来集成spring的jar包
struts与spring集成的jar包则为struts-spring-plugin-2.1.8.jar
首先是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">
<!--struts2 过滤器配置 -->
<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>
<!--配置spring 监听器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
spring 的配置文件 appliactionContext.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-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
">
<!-- 自动扫描与装配bean -->
<context:component-scan base-package="com.jelly.ssm01"></context:component-scan>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
<!-- 数据连接信息 -->
<property name="jdbcUrl" value="jdbc:mysql://127.0.0.1:3316/ssm01?useUnicode=true&characterEncoding=UTF-8">
</property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="user" value="root"></property>
<property name="password" value="winmshl"></property>
<!-- 其他配置 -->
<!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 -->
<property name="initialPoolSize" value="3"></property>
<!--连接池中保留的最小连接数。Default: 3 -->
<property name="minPoolSize" value="3"></property>
<!--连接池中保留的最大连接数。Default: 15 -->
<property name="maxPoolSize" value="5"></property>
<!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
<property name="acquireIncrement" value="3"></property>
<!-- 控制数据源内加载的PreparedStatements数量。如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0 -->
<property name="maxStatements" value="8"></property>
<!--maxStatementsPerConnection定义了连接池内单个连接所拥有的最大缓存statements数。Default: 0 -->
<property name="maxStatementsPerConnection" value="5"></property>
<!--最大空闲时间,1800秒内未使用则连接被丢弃。若为0则永不丢弃。Default: 0 -->
<property name="maxIdleTime" value="1800"></property>
</bean>
<!-- 2 配置mybatis 的SqlSessionFactoryBean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--引入数据源dataSource -->
<property name="dataSource" ref="dataSource"></property>
<!-- 实体bean自动别名 -->
<property name="typeAliasesPackage" value="com.jelly.ssm01.entity"></property>
</bean>
<!-- 3 自动扫描mapper sql映射文件base包 xxxMapper.xml 和xxxMapper 的dao接口文件 -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.jelly.ssm01.mapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>
<!--4 配置spring 事务管理器 -->
<bean id="txTransactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--5 使用声明事务 -->
<tx:annotation-driven transaction-manager="txTransactionManager"/>
</beans>
struts 的配置文件 struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.action.extension" value="html,action," />
<constant name="struts.devMode" value="false" />
<constant name="struts.i18n.encoding" value="UTF-8" />
<constant name="struts.objectFactory" value="spring"/>
<!--用户信息管理 -->
<package name="userManage" namespace="/" extends="json-default">
<action name="user" class="userAction">
<result name="dispatcher">${dispatcherPage}</result>
</action>
</package>
</struts>
其他配置文件 ,log4j.properties配置文件
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=error, stdout
#log4j.logger.org.hibernate=info
#log4j.logger.org.hibernate=debug
#log4j.logger.org.apache.ibatis=debug
log4j.logger.com.jelly.ssm01=debug
注:整合后的效果。
就struts而言,struts2的action交由spring容器进行创建和管理,而不再是web服务器。<constant name="struts.objectFactory" value="spring"/> struts配置文件中的这个常量配置的作用就是声明spring为struts2的action的创建工厂。
就mybatis而言,SqlSessionFactory不在是在程序中手工创建而是交由spring容器创建(在spring容器启动时即创建了一个SqlSessionFactory对象),mybatis的SqlSession的
打开、提交和事务回滚也均由spring容器来统一管理。开发者无需再花时间和精力来编码session事务开、关、提交、回滚等操作,大大提高了开发效率。
ok配置文件都已经配置完成,下面开始正式编码。
先创建一个实体bean 一个简单的User对象
package com.jelly.ssm01.entity;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
private static final long serialVersionUID = -5816986280391870731L;
private int id;
private String name;
private Date Birthday;
private double salary;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getBirthday() {
return Birthday;
}
public void setBirthday(Date birthday) {
Birthday = birthday;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", Birthday=" + Birthday
+ ", salary=" + salary + "]";
}
public User(int id, String name, Date birthday, double salary) {
super();
this.id = id;
this.name = name;
Birthday = birthday;
this.salary = salary;
}
public User(String name, Date birthday, double salary) {
super();
this.name = name;
Birthday = birthday;
this.salary = salary;
}
public User() {
super();
}
}
创建数据库,并在数据库中创建一个t_user 表
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`birthday` varchar(255) DEFAULT NULL,
`salary` double DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8;
创建UserAction类
package com.jelly.ssm01.action;
import java.util.List;
import javax.annotation.Resource;
import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.jelly.ssm01.entity.User;
import com.jelly.ssm01.service.UserService;
@Controller
@Scope("prototype")
public class UserAction {
private String dispatcherPage;
private List<User> userList;
private User user;
@Resource
private UserService userService;
public String execute(){
this.userList= userService.getUserList();
this.dispatcherPage="/pages/user/userlist.jsp";
return "dispatcher";
}
public String addUser(){
this.dispatcherPage="/pages/user/userAdd.jsp";
return "dispatcher";
}
public String addUserSubmit(){
try {
int i= userService.addUser(this.user);
System.out.println(i);
ServletActionContext.getResponse().sendRedirect("user.html");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String deleteUser(){
try {
String id=ServletActionContext.getRequest().getParameter("id");
int i=userService.deleteUser(Integer.parseInt(id));
System.out.println(i);
ServletActionContext.getResponse().sendRedirect("user.html");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String updateUser(){
String id=ServletActionContext.getRequest().getParameter("id");
this.user=userService.findUserById(Integer.parseInt(id));
this.dispatcherPage="/pages/user/userUpdate.jsp";
return "dispatcher";
}
public String updateUserSubmit(){
try {
System.out.println(this.user);
int i=userService.updateUser(user);
System.out.println(i);
ServletActionContext.getResponse().sendRedirect("user.html");
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public String getDispatcherPage() {
return dispatcherPage;
}
public void setDispatcherPage(String dispatcherPage) {
this.dispatcherPage = dispatcherPage;
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
创建UserService
package com.jelly.ssm01.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.jelly.ssm01.entity.User;
import com.jelly.ssm01.mapper.UserMapper;
@Service
@Transactional //声明事务
public class UserService {
@Resource //采用spring 依赖注入 注入mapper接口
private UserMapper userMapper;
public List<User> getUserList() {
try {
List<User> userList=userMapper.findAll();
return userList;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public int addUser(User user) {
try {
int i= userMapper.save(user);
return i;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
public int deleteUser(int id) {
try {
int i=userMapper.delete(id);
return i;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
public int updateUser(User user) {
try {
int i= userMapper.update(user);
return i;
} catch (Exception e) {
e.printStackTrace();
return -1;
}
}
public User findUserById(int id) {
try {
User user= userMapper.findById(id);
return user;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
创建UserMapper.java的接口文件和UserMapper.xml的映射文件。 注:xxxMapper.java 和xxxMapper.xml 文件必须放在同一目录下
UserMapper.java文件
package com.jelly.ssm01.mapper;
import java.util.List;
import com.jelly.ssm01.entity.User;
public interface UserMapper {
public int save(User user);
public int update(User user);
public int delete(int id);
public User findById(int id);
public List<User> findAll();
}
UserMapper.xml 文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jelly.ssm01.mapper.UserMapper">
<insert id="save" parameterType="User">
insert into t_user(name,birthday,salary) values(#{name},#{birthday},#{salary})
</insert>
<update id="update" parameterType="User">
update t_user t
<set>
<if test="name!=null">
t.name=#{name},
</if>
<if test="birthday!=null">
t.birthday=#{birthday},
</if>
<if test="salary!=null">
t.salary=#{salary},
</if>
</set>
where t.id=#{id}
</update>
<delete id="delete" parameterType="int" >
delete from t_user where id=#{id}
</delete>
<select id="findById" parameterType="int" resultType="User">
select * from t_user t where t.id=#{id}
</select>
<select id="findAll" resultType="User" >
select * from t_user
</select>
</mapper>
jsp文件:
/pages/user/userlist.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'userlist.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">
</head>
<body>
<table border="1" bordercolor="#999" >
<tr>
<td>ID </td>
<td>姓名 </td>
<td>生日 </td>
<td >薪资</td>
<td colspan="2" align="center"><a href="user!addUser.html">添加</a></td>
</tr>
<c:forEach items="${userList}" var="user">
<tr>
<td>${user.id }</td>
<td>${user.name }</td>
<td>${user.birthday}</td>
<td>${user.salary}</td>
<td><a href="user!updateUser.html?id=${user.id}">修改</a></td>
<td><a href="user!deleteUser.html?id=${user.id}" οnclick="return confirm('确定删除吗?')">删除</a></td>
</tr>
</c:forEach>
</table>
</body>
</html>
/pages/user/userAdd.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'userlist.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">
</head>
<body>
<form action="user!addUserSubmit.html" method="post">
用户名: <input name="user.name"/> <br/>
生 日: <input name="user.birthday"/> <br/>
薪 资: <input name="user.salary"/> <br/>
<input type="submit" value="提交" />
</form>
</body>
</html>
/pages/user/userUpdate.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'userlist.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">
</head>
<body>
<form action="user!updateUserSubmit.html" method="post">
用户名: <input name="user.name" value="${user.name }"/> <br/>
生 日: <input name="user.birthday" value="${user.birthday}"/> <br/>
薪 资: <input name="user.salary" value="${user.salary }"/> <br/>
<input type="submit" value="提交" />
</form>
</body>
</html>
ok ,最后我们部署项目到tomcat服务器中,运行tomcat服务器,看下运行效果。
点击添加、修改、删除均可完成相应操作(此处不再演示)
项目源码:点击这里请下载 http://yunpan.cn/c33aSZKzJEHbp 访问密码 4ac8 (项目采用utf8编码)