ssm环境集成

103 阅读1分钟

导包

首先创建一个java普通web项目,导入所需的jar包,这里不做赘述


创建项目基本架构


配置Spring核心xml配置文件

创建jdbc.properties与applicationContext.xml文件

jdbc.properties

jdbc.username=root
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///ssm?createDatabaseIfNotExist=true
jdbc.password=123456

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       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/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">
    <!--加载jdbc.properties文件-->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!--扫描service-->
    <context:component-scan base-package="com.abiao.service"/>

    <!--配置连接池对象-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
    </bean>

    <!--创建SessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <!--加载所有mapper.xml文件-->
        <property name="mapperLocations" value="classpath:com/abiao/mapper/*.xml"/>
        <!--定义公共的基础包,相当于取别名-->
        <property name="typeAliasesPackage">
            <value>
                com.abiao.domain
            </value>
        </property>
    </bean>
    <!--mapper扫描器的配置-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--只要扫描到该包下所有的接口,我都使用代理模式进行实现-->
        <property name="basePackage" value="com.abiao.mapper"/>
    </bean>

    <!--配置事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 开启事务注解的支持-->
    <tx:annotation-driven/>

</beans>

配置log4j日志打印

日志配置文件名必须为 log4j.properties

这里配置并不是死的,按照自己的需要进行配置

###全局 配置根
##log4j常见的日志等级: trace<debug<info<warn<error
log4j.rootLogger = ERROR,console 
##输出局部的日志信息    打印的日志等级要大于或者等于trace等级
log4j.logger.com.abiao=trace
##打印的日志规则    日志信息打印在控制台里面
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
##你打印的日志是有一定格式的
log4j.appender.console.layout = org.apache.log4j.PatternLayout
##讲解详细布局规则
log4j.appender.console.layout.ConversionPattern=%d %p [%c] - %m%n

applicationContext-mvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/context http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
">
    <!--扫描controller层-->
    <context:component-scan base-package="com.abiao.controller"/>

    <!--开启mvc注解支持-->
    <mvc:annotation-driven/>

    <!--静态资源放行-->
    <mvc:default-servlet-handler/>

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前置匹配-->
        <property name="prefix" value="/WEB-INF/views/"/>
        <!--后置匹配-->
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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_1.xsd"
         version="3.1">
    <!--在指定的位置加装applicationContext.xml文件-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <!--启动springMvc容器-->
        <servlet-name>springMvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext-mvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springMvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <!--解决post提交乱码问题-->
        <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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

</web-app>

测试

创建员工实体类、mapper、service、controller

Employee员工类

public class Employee {
    private Long id;
    private String name;
    private Integer age;
    
    //getter、setter、toString
}

mapper接口

public interface EmployeeMapper {

    List<Employee> selectAll();

    void save(Employee employee);
}

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="com.abiao.mapper.EmployeeMapper">

    <insert id="save" useGeneratedKeys="true" keyProperty="id" keyColumn="id">
        INSERT INTO t_employee (name,age) VALUES (#{name},#{age})
    </insert>

    <select id="selectAll" resultType="Employee">
      SELECT * FROM t_employee
    </select>
    
</mapper>

service接口

public interface IEmployeeService {
    List<Employee> selctAll();

    void save(Employee employee);
}

serviceImpl实现类

@Service
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl implements IEmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    public List<Employee> selctAll() {
        return employeeMapper.selectAll();
    }

    @Override
    @Transactional
    public void save(Employee employee) {
        employeeMapper.save(employee);
    }
}

controller层

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    @RequestMapping("/index")
    public String index(Model model){
        model.addAttribute("employees",employeeService.selctAll());
        return "employee/employee";
    }

}

jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%--获取查询的员工信息--%>
    ${employees}
</body>
</html>

配置并启动tomcat,访问localhost:8080/employee/index,这里根据自己本地tomcat配置访问