ssm基本整合

首先是依赖:

  <dependencies>
    <!-- spring --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.9.5</version></dependency>
    <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> </dependency>
    <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency>
    <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>${spring.version}</version> </dependency>
    <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency>
    <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency>
    <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version></dependency>
    <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency>
    <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.13</version><scope>compile</scope> </dependency>

    <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency>
    <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency>
    <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency>
    <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency>
    <!-- log start -->
    <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency>
    <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency>
    <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- log end -->
    <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency>
    <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency>
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
      <type>jar</type>
      <scope>compile</scope>
    </dependency>
  </dependencies>

配置文件:
配置spring和mybatis的文件:applicationContext.xml:

<!--这是spring的配置文件-->
<!--开启注解的扫描,希望处理service和dao,不需要spring框架去处理-->
<context:component-scan base-package="com.lbl" >
        <!--配置哪些注解不扫描-->
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!--spring整合Mybatis框架-->
<!--配置连接池注入容器-->
        <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
                <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
                <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/ssm"></property>
                <property name="user" value="root"></property>
                <property name="password" value="root"></property>
        </bean>
<!--配置SQLSessionFactory工厂注入容器-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
    </bean>

<!--配置AccountDao接口所在包-->
    <bean id="mapperScanner" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="basePackage" value="com.lbl.dao"></property>
    </bean>

    <!--配置spring框架声明是事务管理-->
    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
   <property name="dataSource" ref="dataSource"/>
    </bean>
<!--事务通知-->
    <tx:advice id="txAdvice" transaction-manager="transactionManager">

        <tx:attributes>
            <tx:method name="find" read-only="true"/>
            <tx:method name="*" isolation="DEFAULT"/>
        </tx:attributes>
    </tx:advice>
    <!--配置aop增强-->
    <aop:config>
        <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.lbl.service.impl.AccountServiceImpl.*(..))"></aop:advisor>
    </aop:config>
</beans>

配置web.xml文件:

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <!--配置监听器,默认加载WEB-INF目录下的applicationContext.xml配置文件-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!--设置配置文件的路径-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <servlet>
    <servlet-name>dispatcherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--加载springmvc.xml配置文件-->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--启动服务器,创建servlet-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>dispatcherServlet</servlet-name>
    <url-pattern>/mvc</url-pattern>
  </servlet-mapping>
 
  <!--解决中文乱码的问题-->
  <filter>
    <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

springmvc.xml:

<!--开启注解扫描,只扫描Controller-->
    <context:component-scan base-package="com.lbl">
            <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
<!--配置视图解析器-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/pages/"/>
             <property name="suffix" value=".jsp"/>
    </bean>
<!--过滤静态资源-->
    <mvc:resources location="/css/" mapping="/css/**"/>
    <mvc:resources location="/js/" mapping="/js/**"/>
    <mvc:resources location="/images/" mapping="/images/**"/>
    <!--开启springmvc注解的支持-->

    <mvc:annotation-driven/>

日志配置:
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=debug, 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

然后是实体类:
Account类:

package com.lbl.bean;

import java.io.Serializable;

/**
 * @author lbl
 * @creat 2020-09-23-14:39
 */
public class Account implements Serializable {

    private Integer id;
    private String name;
    private Double money;
    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getMoney() {
        return money;
    }
    public void setMoney(double money) {
        this.money = money;
    }
}

Dao层:AccountDao接口:

@Repository
public interface AccountDao {
    @Select("select *from account")
    public List<Account> findAll();
    @Insert("insert into account (id,name,money) values(#{id},#{name},#{money})")
    public void saveAccount(Account account);
}

AccountDao接口的实现类:

@Service("accountService")
public class AccountServiceImpl implements AccountService {

     @Autowired
     AccountDao accountDao;

    @Override
    public List<Account> findAll() {
        System.out.println("业务层,查询所有账户");
        List<Account> accounts = accountDao.findAll();
        return accounts;
    }
    @Override
    public void saveAccount(Account account) {
        System.out.println("业务层,保存账户");
        accountDao.saveAccount(account);
    }
}

Service层:
AccountService接口:

public interface AccountService {
    public List<Account> findAll();
    public void saveAccount(Account account);
}

Web层:
AccountController类:

public class AccountController {

    @Autowired
    private AccountService accountService;
    
        @RequestMapping("/findAll")
      public String findAll(Model model){
            System.out.println("表现层执行");
            //调用service方法
            List<Account> accounts = accountService.findAll();
          model.addAttribute("accounts",accounts);
            return "list";
      }
    }

webapp/WEB-IN/pages下list.jsp页面:

<%@ 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>Title</title>
</head>
<body>
3213213
<c:forEach items="${accounts}" var="account">
        ${account.name}
</c:forEach>
</body>
</html>

webapp下:

<body>
<a href="findAll">测试</a>
<form action="save" method="post">
    姓名:<input type="text" name="name"><br/>
    金额:<input type="text" name="money">
    <input type="submit" value="保存">
</form>
</body>
基本整合完成。```

©️2020 CSDN 皮肤主题: 1024 设计师:上身试试 返回首页