SSM整合

作者: thebigsilly | 来源:发表于2018-04-05 10:00 被阅读0次

项目结构

项目结构

基本配置

  1. 配置Jar包
    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/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.fyh.blog</groupId>
    <artifactId>manager</artifactId>
    <packaging>war</packaging>
    <version>1.0-SNAPSHOT</version>
    <name>manager Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project-encode>utf-8</project-encode>
        <jdk-version>1.8</jdk-version>
        <maven-compailer-version>3.7.0</maven-compailer-version>
        <spring-version>4.3.14.RELEASE</spring-version>
        <junit-version>4.12</junit-version>
        <mybatis-version>3.4.6</mybatis-version>
        <mybatis-spring-version>1.3.2</mybatis-spring-version>
        <mysql-connector-version>5.1.38</mysql-connector-version>
        <dbcp-version>2.2.0</dbcp-version>
        <servlet-version>3.1.0</servlet-version>
        <jsp-version>2.3.1</jsp-version>
        <jstl-version>1.2</jstl-version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-framework-bom</artifactId>
                <version>${spring-version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit-version}</version>
            <scope>test</scope>
        </dependency>
        <!-- Spring依赖 -->
        <!-- 配置SpringMVC 其他依赖会自动下载 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
        </dependency>
        <!-- Spring测试 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
        </dependency>
        <!-- Spring事务 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
        </dependency>
        <!-- Spring数据源 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
        </dependency>
        <!-- Spring AspectJ的支持 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
        </dependency>
        <!-- 数据库连接池 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-dbcp2</artifactId>
            <version>${dbcp-version}</version>
        </dependency>
        <!-- mybatis依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>${mybatis-version}</version>
        </dependency>
        <!-- mybatis和spring整合依赖 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>${mybatis-spring-version}</version>
        </dependency>
        <!-- mysql驱动 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql-connector-version}</version>
        </dependency>
        <!-- Servlet -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>${servlet-version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>${jstl-version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>${jsp-version}</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>manager</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>${maven-compailer-version}</version>
                <configuration>
                    <encoding>${project-encode}</encoding>
                    <source>${jdk-version}</source>
                    <target>${jdk-version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

  1. 配置日志
    log4j.properties
log4j.rootLogger=DEBUG,CONSOLE,file
#log4j.rootLogger=ERROR,ROLLING_FILE
log4j.logger.com.wu.dao=debug
log4j.logger.com.ibatis=debug 
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug 
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug 
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug 
log4j.logger.java.sql.Connection=debug 
log4j.logger.java.sql.Statement=debug 
log4j.logger.java.sql.PreparedStatement=debug 
log4j.logger.java.sql.ResultSet=debug 
log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug
######################################################################################
# Console Appender  \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=error
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n
######################################################################################
# DailyRolling File  \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\u540d\u683c\u5f0f:log2009-09-11
######################################################################################
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=error
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n
log4j.logger.com.opensymphony.xwork2=error  
  1. 配置数据库
    resources/database/jdbc.properties
mysql.driverClass=com.mysql.jdbc.Driver
mysql.url=地址
mysql.user=用户名
mysql.password=密码

SSM整合

  1. Spring数据源配置
    resources/spring/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:mybatis="http://mybatis.org/schema/mybatis-spring"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    <!-- 获取配置文件 -->
    <bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:/database/jdbc.properties"/>
    </bean>
    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
        <property name="driverClassName" value="${mysql.driverClass}"/>
        <property name="username" value="${mysql.user}"/>
        <property name="password" value="${mysql.password}"/>
        <property name="url" value="${mysql.url}"/>
    </bean>
</beans>

1 测试数据库连通性
test/java/common/TestDataBase.java

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/spring/spring-mybatis.xml")
public class TestDataBase {
    @Autowired
    @Qualifier("dataSource")
    private BasicDataSource dataSource;
  //测试数据库连通性
    @Test
    public void testDataBase() throws SQLException {
        //返回的是java.sql.Connection
        Connection connection = dataSource.getConnection();
        PreparedStatement preparedStatement = connection.prepareStatement("SELECT * from category");
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()){
            System.out.println(resultSet.getInt("id"));
            System.out.println(resultSet.getString("kind"));
        }
    }
}

整合Spring和MyBatis

  1. Dao,Mappper,Domain
    com/fyh/blog/manager/login/dao/AccountDao.java
public interface AccountDao {
    Account selectByAccount(String account);
    int insertAccount(Account account);
}

com/fyh/blog/manager/login/domain/Account

@Alias("account") 
public class Account {
    private String account;
    private String password;

    public String getAccount() {
        return account;
    }

    public void setAccount(String account) {
        this.account = account;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

/resources/mapper/AccountMapper.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.fyh.blog.manager.login.dao.AccountDao">
    <select id="selectByAccount" resultType="account">
        SELECT * FROM account WHERE account=#{account}
    </select>
    <insert id="insertAccount">
        INSERT INTO account (account,password) VALUES (#{account},#{password})
    </insert>
</mapper>
  1. 整合配置
    resources/spring/spring-mybatis.xml
  <!-- SessionFactory -->
  <bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:/mapper/*"/>
        <property name="typeAliases">
            <array>
                <value>com.fyh.blog.manager.login.domain.Account</value>
            </array>
        </property>
    </bean>
     <!-- 扫描Dao接口 -->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sessionFactory"/>
        <property name="basePackage" value="com.fyh.blog.manager.*.dao"/>
    </bean>
  1. 测试MyBatis
    /test/com/fyh/blog/manager/login/dao/TestAccountDao.java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/spring/spring-mybatis.xml")
public class TestAccountDao {
    @Autowired
    private AccountDao accountDao;

    @Test
    public void testMyBatis(){
        Account account =  accountDao.selectByAccount("admin");
        System.out.println(account.getAccount() + "," + account.getPassword());
    }
}

事务配置

  1. Spring配置文件
    resources/spring/spring-mybatis.xml
   <!-- 配置事务管理器 -->
  <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
   <!-- 扫描Service -->
     <context:component-scan base-package="com.fyh.blog.manager.*.service"/>
   <!-- 声名式配置事务-->
    <tx:advice id="transactionInterceptor" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="get*" read-only="true" propagation="NEVER"/>
            <tx:method name="list*" read-only="true" propagation="NEVER"/>
            <tx:method name="insert*" propagation="REQUIRES_NEW" rollback-for="java.lang.Exception"/>
        </tx:attributes>
    </tx:advice>
    <aop:config>
        <aop:pointcut id="transactionPoint" expression="execution(* com.fyh.blog.manager..service..*(..))"/>
        <aop:advisor advice-ref="transactionInterceptor" pointcut-ref="transactionPoint"/>
    </aop:config>
  1. service
    com/fyh/blog/manager/login/service/impl/LoginServiceImpl .java
@Service
public class LoginServiceImpl implements LoginService{

    @Autowired
    private AccountDao accountDao;

    public void insertAccount() throws Exception {
        Account account = new Account();
        account.setPassword("23");
        account.setAccount("123");
        accountDao.insertAccount(account);
        throw new Exception("出错");
    }
}
  1. 测试事务
    /test/com/fyh/blog/manager/login/service/TestLoginService.java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:/spring/spring-mybatis.xml")
public class TestLoginService {
    @Autowired
    private LoginService loginService;
    @Test
    public void insertAccount() throws Exception {
        loginService.insertAccount();
    }
}

spring-mvc配置

  1. 配置文件
    resources/spring-mvc/spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- 开启注解 -->
    <mvc:annotation-driven/>
    <!-- 配置视图解析器 -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!-- 前缀 -->
        <property name="prefix" value="WEB-INF/jsp/"/>
        <!-- 后缀 -->
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- 配置请求映射 -->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>

    <!-- 配置静态资源 -->
    <mvc:resources location="/img/" mapping="/img/**"/>
    <!-- 扫描Controller -->
    <context:component-scan base-package="com.fyh.blog.manager" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>
  1. controller
    /com/fyh/blog/manager/login/action/LoginAction.java
@Controller
public class LoginAction {
    @RequestMapping("dd")
    public String dd(Model model) {
        model.addAttribute("1", "2");
        return "dd";
    }
}
  1. 测试
    /test/com/fyh/blog/manager/login/action/TestLoginService.java
@RunWith(SpringJUnit4ClassRunner.class) //表示使用什么测试环境进行测试
@WebAppConfiguration
@ContextConfiguration(locations = {"classpath:/spring/spring-mybatis.xml", "classpath:/spring-mvc/spring-mvc.xml"})
public class TestLoginService {
    @Autowired
    WebApplicationContext webApplicationContext;
    //虚拟MVC请求,获取得到处理结果
    MockMvc mockMvc;

    @Before
    public void initMockMvc() {
        mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
    }

    @Test
    public void testPage() throws Exception {
       MvcResult mvcResult = mockMvc.perform(MockMvcRequestBuilders.get("/dd")).andReturn();
        MockHttpServletRequest request = mvcResult.getRequest();
        String s = (String) request.getAttribute("1");
        assert s.equals("2");
    }
}

配置web.xml

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app 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"
         version="3.0">
    <!-- 配置Spring -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/spring-mybatis.xml</param-value>
    </context-param>
    <!-- Spring容器启动 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 编码过滤器 -->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- SpringMVC启动 -->
    <servlet>
        <servlet-name>tt</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc/spring-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>tt</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
首页
跳转成功

相关文章

网友评论

      本文标题:SSM整合

      本文链接:https://www.haomeiwen.com/subject/kyjfhftx.html