SSH学习-Struts2+Spring+MyBatis的整合配置
Struts2是一个前端框架,应用于表现层,和Spring整合后,持久层可以选择MyBatis,也可以选择Hibernate,这里先选择MyBatis,学习如何整合Struts2+Spring+MyBatis。本文将以浏览器发送一个action请求到服务端,返回一个json字符串为例,来实际整合并应用,接下来是整合的大致步骤:
(1)导包
(2)web.xml配置listener,context-param,filter
(3)配置spring-*.xml,包括组件扫描,和MyBatis相关的配置(SqlSessionFactoryBean和MapperScannerConfigurer)
(4)配置struts.xml,主要是package,action和result
(5)创建DAO持久层
(6)创建Service层
(7)创建Controller层
导包
导包要考虑到版本兼容性问题,如Spring现在在更新换代,但是和Struts2不一定能完美整合,有可能启动Spring容器的时候会报错。下面是能成功启用的包,期间数据库驱动包版本过低,导致和本地的MySQL版本不兼容导致报错连接不上数据库服务器,后面更新驱动包版本才解决问题。
<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>com.boe</groupId> <artifactId>SSH03</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <dependencies> <!-- 导入struts基础包 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.3.8</version> </dependency> <!-- struts2和spring整合需要的包 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-spring-plugin</artifactId> <version>2.3.8</version> </dependency> <!-- result类型为json需要额外导包 --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-json-plugin</artifactId> <version>2.3.8</version> </dependency> <!-- spring和myBatis整合需要导入的包 --> <!--导入junit测试包--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <classifier>sources</classifier> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <classifier>javadoc</classifier> </dependency> <!-- 导入数据库连接池包 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- oracle驱动包 --> <!-- <dependency> <groupId>com.oracle</groupId> <artifactId>ojdbc6</artifactId> <version>11.2.0.1.0</version> </dependency> --> <!-- MySQL驱动包,台式机使用MySQL8.0,使用最新驱动--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.46</version> </dependency> <!-- 关键:导入Mybatis-Spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> <classifier>sources</classifier> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> <classifier>javadoc</classifier> </dependency> <!-- 导入Mybatis的包 --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> <classifier>sources</classifier> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> <classifier>javadoc</classifier> </dependency> <!-- 调用JDCB的包--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.2.8.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.2.8.RELEASE</version> <classifier>sources</classifier> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.2.8.RELEASE</version> <classifier>javadoc</classifier> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.0.5.RELEASE</version> </dependency> </dependencies> </project>
web.xml配置listener,context-param,filter
配置这个没什么好说,就是将Struts2和Spring整合到一起。
<?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"> <display-name>SSH03</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 指定spring配置文件位置 --> <context-param> <param-name>contextConfigLocation</param-name> <!-- 由于param-name名字写错,写成contextLocationConfig,导致报错 --> <!-- 报错提示为Could not open ServletContext resource [/WEB-INF/applicationContext.xml --> <!-- 由于配置错误,会默认从WEB-INF下寻找applicationContext.xml文件进行解析,只有正确配置了context-param,才会解析自定配置的spring-mvc.xml --> <param-value>classpath:config/spring-*.xml</param-value> </context-param> <!-- 配置listener,用于启动spring容器 --> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!-- 配置struts2主控制器 --> <filter> <filter-name>mvc</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> <init-param> <!-- 告诉struts2,struts.xml文件的读取位置, 如果配置了inti-param标签,需要在param-value标签添加struts-default.xml和struts-plugin.xml两个文件,默认情况是自动读取,不需要添加 手动情况下需要添加这两个文件进行读取 --> <param-name>config</param-name> <param-value> struts-default.xml, struts-plugin.xml, config/struts.xml </param-value> </init-param> </filter> <filter-mapping> <filter-name>mvc</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
配置spring-*.xml,包括组件扫描,和MyBatis相关的配置
这个一块是整合MyBatis和Spring,使用Spring的配置文件完成组件扫描,数据库连接,自动创建SqlSessionFactoryBean,以及配置MapperScannerConfigurer完成接口扫描。这里将不展示properties属性文件。这一块配置过程中出现了一些小问题,自己手写时出现单词打错,属性名记忆不清楚的情况。
<?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:util="http://www.springframework.org/schema/util" xmlns:jee="http://www.springframework.org /schema/jee" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"> <context:component-scan base-package="*"></context:component-scan> <!-- 读取属性文件 --> <util:properties id="db" location="classpath:config/jdbc.properties"></util:properties> <!-- 配置basicDataSource --> <bean id="bs" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="#{db.driver}"/> <property name="url" value="#{db.url}" /> <property name="username" value="#{db.user}" /> <property name="password" value="#{db.pwd}" /> </bean> <!-- 配置SqlSessionFactory --> <bean id="ssfb" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="bs"></property> <property name="mapperLocations" value="classpath:Mapper/*.xml"></property> </bean> <!-- 配置MapperScannerConfigurer --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="DAO"></property> </bean> </beans>
配置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"> <!-- dtd文件导入的作用:决定了xml文件可以使用什么标签 --> <struts> <!-- 与MyBatis整合,登录测试 --> <package name="login" namespace="/login" extends="json-default"> <action name="loginCheck" class="loginController" method="login"> <result name="success" type="json"> <param name="root">result</param><!-- 待加入action属性 --> </result> <result name="error" type="json"> <param name="root">result</param> </result> </action> </package> </struts>
创建DAO持久层
DAO接口
package DAO; import org.springframework.stereotype.Repository; import Entity.User; /** * 登录DAO接口 * @author yangchaolin * */ @Repository public interface userDAO { public int addUser(User user); public User findUser(User user); }
Mapper
<?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="DAO.userDAO"> <!-- id要求唯一,parameterType:填写实体类的完整名字--> <!-- 添加user --> <insert id="addUser" parameterType="Entity.User"> insert into user values(#{id},#{name},#{password}) </insert> <!-- 根据用户名和密码查询用户 --> <select id="findUser" parameterType="Entity.User" resultType="Entity.User"> select * from user where name=#{name} and password=#{password} </select> </mapper>
创建Service层
Service接口和实现类
package Service; import Entity.Result; public interface userService { public Result findUserByNameAndPassword(String name,String password); }
package Service; import javax.annotation.Resource; import org.springframework.stereotype.Service; import DAO.userDAO; import Entity.Result; import Entity.User; /** * 登录service层实现类 * @author yangchaolin * */ @Service("userService") public class userServiceImpl implements userService{ //注入DAO层 @Resource(name="userDAO") userDAO dao; public Result findUserByNameAndPassword(String name, String password) { Result result=new Result(); //登录验证 User user=new User(); user.setName(name); user.setPassword(password); User resultUser=dao.findUser(user); //判断 if(resultUser!=null) { result.setStatus("0"); result.setMessage("登录成功"); result.setData(resultUser); return result; }else { result.setStatus("1"); result.setMessage("用户名或密码错误!"); return result; } } }
User实体类,以及返回json字符串对应的javabean Result
package Entity; import java.io.Serializable; public class User implements Serializable{ private static final long serialVersionUID = 699190475611076064L; private int id; private String name; private String password; public User() { super(); } public User(int id, String name, String password) { super(); this.id = id; this.name = name; this.password = password; } 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 String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; User other = (User) obj; if (id != other.id) return false; return true; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", password=" + password + "]"; } }
package Entity; import java.io.Serializable; public class Result implements Serializable{ private static final long serialVersionUID = -3028245798147541264L; private String status; private String message; private Object data; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public Result(String status, String message, String data) { super(); this.status = status; this.message = message; this.data = data; } public Result() { } @Override public String toString() { return "Result [status=" + status + ", message=" + message + ", data=" + data + "]"; } }
创建Controller层
package Controller; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import Entity.Result; import Entity.User; import Service.userService; /** * 登录控制器 * @author yangchaolin * */ @Controller public class loginController { //属性 private String name; private String password; private Result result;//返回结果为json //get set方法 public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Result getResult() { return result; } public void setResult(Result result) { this.result = result; } //注入service层 @Resource(name="userService") userService service; public String login() { //返回登录结果 Result result=service.findUserByNameAndPassword(name, password); this.result=result; if(result.getStatus().equals("0")) { User user=(User) result.getData(); return "success"; } else { User user=(User) result.getData(); return "error"; } } }
发送action请求测试
密码错误:
密码正确:
结论
Struts2+Spring+MyBatis可以组合使用,导包要注意Struts2和Spring的版本兼容,Spring和MyBatis的版本兼容,以及数据库驱动包和数据库服务器版本的兼容问题等。