用eclipse创建mybatis+maven+web项目可以看我之前的文章
首先贴出最终项目的pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.qdsoft</groupId>
<artifactId>ExamSystem</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<!-- spring与mybatis整合所需jar -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.1</version>
</dependency>
<!-- Convention插件 实现struts的零配置 零配置并不是没有配置,而是通过约定大于配置的方式,大量通过约定来调度页面的跳转而使得配置大大减少
默认所有的结果页面都存储在WEB-INF/content下 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-convention-plugin</artifactId>
<version>2.3.16.2</version>
</dependency>
<!-- 用于方便的浏览项目中的所有action及其与jsp view的映射 运行后,浏览 http://localhost:8080/{你的项目名称}/config-browser/
即可看到当前项目中的所有action -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-config-browser-plugin</artifactId>
<version>2.3.16.2</version>
</dependency>
<!-- 该插件来管理Struts2的对象创建以及对象的依赖关系 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-spring-plugin</artifactId>
<version>2.3.16.2</version>
</dependency>
<!-- Spring-Context的依赖注入功能 spring-context实现了Spring注入容器并且依赖:spring-core,spring-expression,spring-aop以及spring-beans
这些依赖包使容器可以支持Spring的一些核心技术 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!-- component-scan -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>4.3.2.RELEASE</version>
</dependency>
<!-- 事务用到 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.6</version>
</dependency>
<!-- 数据源,数据库连接池 -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.36</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
<scope>provided</scope>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.20</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<!-- surefire 插件用来在maven构建生命周期的test phase执行一个应用的单元测试 -->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>8080</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
</project>
建表
数据库名为:demo
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for provinces
-- ----------------------------
DROP TABLE IF EXISTS `provinces`;
CREATE TABLE `provinces` (
`id` int(11) NOT NULL,
`name` varchar(5) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of provinces
-- ----------------------------
INSERT INTO `provinces` VALUES ('1', '北京');
INSERT INTO `provinces` VALUES ('2', '上海');
INSERT INTO `provinces` VALUES ('3', '山东');
INSERT INTO `provinces` VALUES ('4', '湖南');
-- ----------------------------
-- Table structure for users
-- ----------------------------
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`email` varchar(20) DEFAULT NULL,
`password` varchar(20) DEFAULT NULL,
`gender` varchar(2) DEFAULT NULL,
`birthdate` date DEFAULT NULL,
`province` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of users
-- ----------------------------
INSERT INTO `users` VALUES ('1', 'tom', 'tom@qdsoft.com', null, 'M', null, null);
INSERT INTO `users` VALUES ('2', 'rose', 'rose@qdsoft.com', null, 'F', null, null);
INSERT INTO `users` VALUES ('4', 'jack', 'jack@qq.com', null, 'M', null, '1');
INSERT INTO `users` VALUES ('5', 'jack', 'jack@qq.com', null, 'M', null, '1');
Spring整合mybatis
Configuration.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<settings>
<!-- 将mybatis的执行过程显示在控制台
<setting name="logImpl" value="STDOUT_LOGGING" /> -->
<!-- 在用到级联属性的时候才会查询 -->
<setting name="lazyLoadingEnabled" value="true" />
<!--true: 把所有级联查询都执行 -->
<setting name="aggressiveLazyLoading" value="false" />
<!-- 将下划线格式转换为驼峰格式: table:user_name java: userName -->
<setting name="mapUnderscoreToCamelCase" value="true" />
</settings>
<typeAliases>
<package name="cn.qdsoft.model" />
</typeAliases>
</configuration>
spring-mybatis.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"
xmlns:mybatis-spring="http://mybatis.org/schema/mybatis-spring"
xsi:schemaLocation="http://mybatis.org/schema/mybatis-spring http://mybatis.org/schema/mybatis-spring-1.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 配置一个数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=utf8" />
<property name="username" value="root" />
<property name="password" value="" />
</bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:/Configuration.xml" />
<property name="mapperLocations" value="classpath*:/*.mapper.xml" />
</bean>
<!-- 在指定包下自动查找mybatis的dao接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.qdsoft.dao" />
<property name="sqlSessionFactory" ref="sqlSessionFactory" />
</bean>
</beans>
user.mapper.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="cn.qdsoft.dao.UserDAO">
<select id="findAll" resultType="User">
select id,name,email,password,birthdate,gender,province
from users
</select>
<select id="findById" resultType="User">
select id,name,email,password,birthdate,gender,province
from users
where id=#{id}
</select>
<insert id="insert" parameterType="User">
INSERT INTO users (
name,
email,
gender,
birthdate,
province
) VALUES (
#{name},
#{email},
#{gender},
#{birthdate},
#{province}
)
</insert>
</mapper>
编写与数据库对应的实体类
User.java
package cn.qdsoft.model;
import java.sql.Date;
public class User {
private Long id;
private String name;
private String email;
private String password;
private String gender;// M:男,F:女
private Date birthdate;
private Long province;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate(Date birthdate) {
this.birthdate = birthdate;
}
public Long getProvince() {
return province;
}
public void setProvince(Long province) {
this.province = province;
}
}
Province.java
package cn.qdsoft.model;
public class Province {
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
编写接口类
UserDAO.java
package cn.qdsoft.dao;
import java.util.List;
import cn.qdsoft.model.User;
public interface UserDAO {
List<User> findAll();
User findById(Long id);
public void insert(User user);
}
ProvinceDAO.java
package cn.qdsoft.dao;
import java.util.List;
import cn.qdsoft.model.Province;
public interface ProvinceDAO {
List<Province> findAll();
}
编写测试类
package cn.qdsoft.dao;
import javax.annotation.Resource;
import org.junit.Test;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import cn.qdsoft.model.User;
@ContextConfiguration("classpath:/spring-mybatis.xml")
public class UserDAOTest extends AbstractJUnit4SpringContextTests {
@Resource
private UserDAO userDAO;
@Test
public void findById() {
User user = userDAO.findById(1L);
System.out.println(user.getEmail());
}
@Test
public void insert(){
User user = new User();
user.setName("jack");
user.setEmail("jack@qq.com");
user.setGender("M");
user.setProvince(1L);
userDAO.insert(user);
}
}
然后UserDAOTest.java右击,run as ->JUnit Test
在控制台输出 tom@qdsoft.com 就算成功啦
Spring整合Struts2
Struts2负责流程,Spring负责对象的创建,Action和Service都由Spring框架负责创建
1.在pom.xml中添加jar依赖
2.在web.xml里配置spring和Struts2的核心配置文件
①配置启动的spring的listener和spring配置文件的param
②配置Struts2框架的核心调度器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<!-- 用于指定Spring的配置文件路径 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:/spring-*.xml</param-value>
</context-param>
<!-- 服务器启动时,通过监听器初始化Spring的配置环境
监听器,默认加载文件是:/WEB-INF/applicationContext.xml -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置Struts2框架的核心调度器 -->
<filter>
<filter-name>struts</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
3.在Struts.xml中配置action类
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<!-- 修改配置文件不用重启tomcat的方法
注意:tomcat目录不能有空格!!!
-->
<constant name="struts.devMode" value="true" />
<constant name="struts.configuration.xml.reload" value="true" />
<constant name="struts.convention.default.parent.package"
value="one" />
<package name="one" namespace="" extends="struts-default">
<!-- 在这个package里可以共用的结果集,每个action中都可以使用这个result -->
<global-results>
<result name="list" type="redirectAction">list</result>
</global-results>
</package>
</struts>
4.在spring-struts.xml中配置service类
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
<!-- 给类加上spring组件注解,@Component,@Repository,@Service,@Controller,
就会将这个对象作为Bean注册进Spring容器-->
<context:component-scan base-package="cn.qdsoft.service" />
</beans>
依次贴出代码
BaseAction.java
package cn.qdsoft;
import com.opensymphony.xwork2.ActionSupport;
public class BaseAction extends ActionSupport {
public static final String LIST = "list";
public boolean isLogined() {
return false;
}
}
UserAction.java
package cn.qdsoft.actions;
import javax.annotation.Resource;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import cn.qdsoft.BaseAction;
import cn.qdsoft.service.UserService;
@Namespace("/user")
public class UserAction extends BaseAction {
// 必须声明为接口类型;important!!!
@Resource
private UserService userService;
private String hello;
// 也在一个package中,package的名字不知道
// 父package 名字叫one
@Action("list")
public String list() {
System.out.println("user list............................");
hello = userService.list();
return SUCCESS;
}
public String getHello() {
return hello;
}
public void setHello(String hello) {
this.hello = hello;
}
}
UserService.java
package cn.qdsoft.service;
public interface UserService {
String list();
}
UserServiceImpl.java
package cn.qdsoft.service.impl;
import org.springframework.stereotype.Service;
import cn.qdsoft.service.UserService;
@Service
public class UserServiceImpl implements UserService {
@Override
public String list() {
System.out.println("userService called....");
return "hello world";
}
}
list.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>list.jsp</h1>
<h2>${hello }</h2>
</body>
</html>
整合结束