手把手-快速搭建 SSM 项目框架----整合 SSM 基础配置

SpringMVC + Spirng + Mybatis 配置繁杂,新手记录SSM基本配置

文章目录

  • 创建项目
    • 项目结构图(配置好后)
  • 配置文件
    • pom.xml常用坐标
    • web.xml
    • applicationContext.xml
    • springmvc.xml
    • db.properties
    • log4j.properties
  • 测试SSM
    • jsp
    • domain
    • Dao
    • Service
    • controller
    • test
  • 配置Tomcat启动
    • 配置
    • 启动测试

创建项目

创建maven工程,使用maven-archetype-webapp,点击next
手把手-快速搭建 SSM 项目框架----整合 SSM 基础配置_第1张图片
填写项目信息,点击next
手把手-快速搭建 SSM 项目框架----整合 SSM 基础配置_第2张图片
maven信息,next,最后 finish
手把手-快速搭建 SSM 项目框架----整合 SSM 基础配置_第3张图片

项目结构图(配置好后)

手把手-快速搭建 SSM 项目框架----整合 SSM 基础配置_第4张图片

配置文件

pom.xml常用坐标

<properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.8maven.compiler.source>
    <maven.compiler.target>1.8maven.compiler.target>
    <spring.version>5.2.4.RELEASEspring.version>
    <slf4j.version>1.6.6slf4j.version>
    <log4j.version>1.2.12log4j.version>
    <mysql.version>8.0.16mysql.version>
    <mybatis.version>3.4.5mybatis.version>
properties>
<dependencies>
    <dependency>
      <groupId>org.aspectjgroupId>
      <artifactId>aspectjweaverartifactId>
      <version>1.6.8version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-aopartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webmvcartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>${spring.version}version>
    dependency>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.12version>
      <scope>compilescope>
    dependency>
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>${mysql.version}version>
    dependency>
    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>servlet-apiartifactId>
      <version>2.5version>
      <scope>providedscope>
    dependency>
    <dependency>
      <groupId>javax.servlet.jspgroupId>
      <artifactId>jsp-apiartifactId>
      <version>2.0version>
      <scope>providedscope>
    dependency>
    <dependency>
      <groupId>jstlgroupId>
      <artifactId>jstlartifactId>
      <version>1.2version>
    dependency>
    
    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>${log4j.version}version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>${slf4j.version}version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-log4j12artifactId>
      <version>${slf4j.version}version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>${mybatis.version}version>
    dependency>
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.0version>
    dependency>
    <dependency>
      <groupId>com.zaxxergroupId>
      <artifactId>HikariCPartifactId>
      <version>3.4.2version>
    dependency>
  dependencies>

web.xml



<web-app>
  <display-name>Archetype Created Web Applicationdisplay-name>
  <listener>


    <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
  listener>
  <context-param>
    <param-name>contextConfigLocationparam-name>
    <param-value>classpath:applicationContext.xmlparam-value>
  context-param>

  <servlet>
    <servlet-name>Myservletservlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
    <init-param>
      <param-name>contextConfigLocationparam-name>
      <param-value>classpath:springmvc.xmlparam-value>
    init-param>
    <load-on-startup>1load-on-startup>
  servlet>
  <servlet-mapping>
    <servlet-name>Myservletservlet-name>
    <url-pattern>/url-pattern>
  servlet-mapping>

  <filter>
    <filter-name>CharacterEncodingFilterfilter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
    
    <init-param>
      <param-name>encodingparam-name>
      <param-value>UTF-8param-value>
    init-param>
    
    <init-param>
      <param-name>forceEncodingparam-name>
      <param-value>trueparam-value>
    init-param>
  filter>
  
  <filter-mapping>
    <filter-name>CharacterEncodingFilterfilter-name>
    <url-pattern>/*url-pattern>
  filter-mapping>

web-app>

applicationContext.xml


<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.xsd
	http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context.xsd
	http://www.springframework.org/schema/aop
	http://www.springframework.org/schema/aop/spring-aop.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd">
	

    <context:component-scan base-package="com.wcy">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    context:component-scan>



    <context:property-placeholder location="classpath:db.properties"/>
    <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource">
        <property name="driverClassName" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
    bean>

    <bean id="sqlsessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource">property>
    bean>

    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.wcy.dao">property>
    bean>




    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource">property>
    bean>

    <tx:annotation-driven transaction-manager="transactionManager">tx:annotation-driven>

    <aop:aspectj-autoproxy  proxy-target-class="true"/>

beans>

springmvc.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       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">

		
        <context:component-scan base-package="com.wcy.controller">context:component-scan>
		
        <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                <property name="prefix" value="/WEB-INF/pages/">property>
                <property name="suffix" value=".jsp">property>
        bean>
        <mvc:annotation-driven>mvc:annotation-driven>
		
        <mvc:resources location="/js/" mapping="/js/**">mvc:resources>
beans>

db.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm整合复习?serverTimezone=UTC
jdbc.username=
jdbc.password=

log4j.properties

# Set root category priority to INFO and its only appender to CONSOLE.
#log4j.rootCategory=INFO, CONSOLE            debug   info   warn error fatal
log4j.rootCategory=info, CONSOLE, LOGFILE

# Set the enterprise logger category to FATAL and its only appender to CONSOLE.
log4j.logger.org.apache.axis.enterprise=FATAL, CONSOLE

# CONSOLE is set to be a ConsoleAppender using a PatternLayout.
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

# LOGFILE is set to be a File appender using a PatternLayout.
log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=d:\axis.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%d{ISO8601} %-6r [%15.15t] %-5p %30.30c %x - %m\n

测试SSM

手把手-快速搭建 SSM 项目框架----整合 SSM 基础配置_第5张图片

jsp

从请求发起的地方开始

<body>
    <h1>helloh1>
    <a href="account/findAll">findAlla>
    <a href="account/save">savea>
body>
  • findAll请求可以到达如下页面,展示所有数据
  • save请求测试事务的有效性,配置上面直接给出,不在说明
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Titletitle>
head>
<body>
    <h1>successh1>
    <table>
        <tr><td>idtd><td>nametd><td>moneytd>tr>
        <c:forEach items="${accounts}" var="account">
            <tr>
                <td>${account.id}td><td>${account.name}td><td>${account.money}td>
            tr>
        c:forEach>
    table>
body>
html>

domain

public class Account implements Serializable{

    private Integer id;
    private String name;
    private Double money;
    ……

Dao

@Repository
public interface IAccountDao {

    @Select("select * from account")
    List<Account> findAll();

    @Insert("insert into account values(#{id},#{name},#{money})")
    void saveAccount(Account account);
}

Service

IAccountService

public interface IAccountService {

    List<Account> findAll();
    void saveAccount(Account account);
}

AccountService

  • 其中saveAccount用@Transactional修饰,是为了测试事务,用int a=1/0;隔开,保证其原子性。
@Service
public class AccountService implements IAccountService {

    @Autowired
    IAccountDao accountDao;

    @Override
    public List<Account> findAll() {
        List<Account> accounts=accountDao.findAll();
        return accounts;
    }
    @Transactional
    @Override
    public void saveAccount(Account account) {
        accountDao.saveAccount(account);
        int a=1/0;
        Account account2=new Account();
        account2.setId(888);
        account2.setName("888");
        account2.setMoney(888.8);
        accountDao.saveAccount(account2);
    }
}

controller

@Controller
@RequestMapping("account")
public class AccountController {

    @Autowired
    AccountService accountService;
    /**
     * 查询所有账户
     * @return
     */
    @RequestMapping("findAll")
    public ModelAndView findAll(){
        ModelAndView mv =new ModelAndView();
        List<Account> accounts= accountService.findAll();
        mv.addObject("accounts",accounts);
        mv.setViewName("success");
        return mv;
    }
    /**
     * 保存新账户
     * @return
     */
    @RequestMapping("save")
    public String save(){
        Account account=new Account();
        account.setId(666);
        account.setName("myset");
        account.setMoney(123.3);
        accountService.saveAccount(account);
        return "hello";
    }

}

test

测试类配置

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:applicationContext.xml"})
public class test {

    @Autowired
    AccountService accountService;

    @Test
    public void test(){
        //accountService.findAll();
    }
}

配置Tomcat启动

配置

1,添加Tomcat
手把手-快速搭建 SSM 项目框架----整合 SSM 基础配置_第6张图片
2,配置Tomcat
手把手-快速搭建 SSM 项目框架----整合 SSM 基础配置_第7张图片
手把手-快速搭建 SSM 项目框架----整合 SSM 基础配置_第8张图片
点击ok即完成Tomcat配置

启动测试

运行Tomcat服务器

手把手-快速搭建 SSM 项目框架----整合 SSM 基础配置_第9张图片

点击findAll,成功查询到我数据库的内容

手把手-快速搭建 SSM 项目框架----整合 SSM 基础配置_第10张图片

点击save,可以看到保存失败,可以看到事务相关的消息,说明事务回滚,两个账户都没有保存。

手把手-快速搭建 SSM 项目框架----整合 SSM 基础配置_第11张图片

你可能感兴趣的:(框架-SpringMVC)