SSM框架+slf4j 以Gradle实现

Posted 假想丿殇

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSM框架+slf4j 以Gradle实现相关的知识,希望对你有一定的参考价值。

环境:win10+jdk8+tomcat9+Intellij IDEA

 

首先,作为一个喜欢偷懒的人,管理jar之类的的事情太累,所以用了Gradle项目管理器

第一步:

  新建一个gradle-web项目,目录结构为

  

 

  在build.gradle中添加

group \'com.pigge\'
version \'1.0-SNAPSHOT\'

apply plugin: \'java\'
apply plugin: \'war\'
apply plugin: \'idea\'

sourceCompatibility = 1.8

repositories {
    mavenLocal()
    mavenCentral()
}
//让resource文件自动加载到class路径下
idea{
    module{
        inheritOutputDirs=true;
    }
}

dependencies {
    def springVersion = "4.3.8.RELEASE"
    testCompile group: \'junit\', name: \'junit\', version: \'4.11\'
    testCompile group: \'junit\', name: \'junit\', version: \'4.12\'
    compile("org.springframework:spring-aop:$springVersion",
            "org.springframework:spring-orm:$springVersion",
            "org.springframework:spring-jdbc:$springVersion",
            "org.springframework:spring-core:$springVersion",
            "org.springframework:spring-context:$springVersion",
            "org.springframework:spring-beans:$springVersion",
            "org.springframework:spring-tx:$springVersion",
            "org.springframework:spring-web:$springVersion",
            "org.springframework:spring-webmvc:$springVersion",)
    compile group: \'mysql\', name: \'mysql-connector-java\', version: \'5.1.40\'
    compile(group: \'org.mybatis\', name: \'mybatis\', version: \'3.4.5\',)
    compile group: \'org.mybatis\', name: \'mybatis-spring\', version: \'1.3.1\'
    compile group: \'javax\', name: \'javaee-api\', version: \'7.0\'
    compile group: \'org.apache.logging.log4j\', name: \'log4j-api\', version: \'2.2\'
    compile group: \'org.apache.logging.log4j\', name: \'log4j-core\', version: \'2.2\'
    compile group: \'org.apache.logging.log4j\', name: \'log4j-slf4j-impl\', version: \'2.2\'
    compile group: \'org.apache.logging.log4j\', name: \'log4j-jcl\', version: \'2.2\'
    compile group: \'org.slf4j\', name: \'slf4j-api\', version: \'1.7.10\'
    compile group: \'org.apache.logging.log4j\', name: \'log4j-web\', version: \'2.2\'
}

 在resource下新建database.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/StudentMS?characterEncoding=utf8&useSSL=true
jdbc.username=root
jdbc.password=123456

再新建spring-config.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:context="http://www.springframework.org/schema/context"
       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/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">
    <!--配置Spring的扫描路径-->
    <context:component-scan base-package="com.pigge.controller"/>
    <context:component-scan base-package="com.pigge.service"/>
    <!--加载配置文件-->
    <context:property-placeholder location="classpath:database.properties"/>
    <!--配置springmvc解析式-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>
    <!--配置mybatis的sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:com/pigge/mapper/*.xml"/>
    </bean>
    <!--使用spring自动装配mapper类-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.pigge.mapper"/>
    </bean>
</beans>

在修改web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <!--配置log4j2,是它可以识别${web:rootDir}-->
    <context-param>
        <param-name>log4jContextName</param-name>
        <param-value>star</param-value>
    </context-param>
    <!--加载spring-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param><!--加载配置文件-->
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-config.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

再在resource下新建log4j2.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="off" monitorInterval="1800">
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
        </Console>
        <RollingFile name="RollingFileInfo" fileName="${web:rootDir}/WEB-INF/logs/info.log"
                     filePattern="${web:rootDir}/WEB-INF/logs/$${date:yyyy-MM}/info-%d{yyyy-MM-dd}-%i.log">
            <!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
            <ThresholdFilter level="info" onMatch="ACCEPT" onMismatch="DENY"/>
            <PatternLayout pattern="[%d{HH:mm:ss:SSS}] [%p] - %l - %m%n"/>
            <Policies>
                <TimeBasedTriggeringPolicy/>
                <SizeBasedTriggeringPolicy size="10MB"/>
            </Policies>
        </RollingFile>
    </Appenders>
    <Loggers>
        <root level="info" includeLocation="true">
            <appender-ref ref="Console"/>
            <appender-ref ref="RollingFileInfo"/>
        </root>
    </Loggers>
</Configuration>

然后,在entity包下建立实体类

public class Student {
    private Integer id;
    private String name;
    private String sex;
    private LocalDate birthday;

    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 String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public LocalDate getBirthday() {
        return birthday;
    }

    public void setBirthday(LocalDate birthday) {
        this.birthday = birthday;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name=\'" + name + \'\\\'\' +
                ", sex=\'" + sex + \'\\\'\' +
                ", birthday=" + birthday +
                \'}\';
    }
}

在mapper包下建立StudentMapper.java(dao层,有的喜欢取名为**Dao类)

public interface StudentMapper {
    @Select("select * from student where id = #{id}")
    Student selectOne(Integer id);
}

在resource文件夹下建立与mapper包相同的路径,再新建StudentMapper.xml(否则StudentMapper.java与StudentMapper.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.pigge.mapper.StudentMapper">

</mapper>

空的什么方法也没有,测试时只调用StudentMapper.java的抽象方法

在service下新建StudentService

public interface StudentService {
    Student selectOne(Integer id);
}

再在service下的impl包新建StudentServiceImpl

@Service
public class StudentServiceImpl implements StudentService {

    private StudentMapper studentMapper;


    public StudentMapper getStudentMapper() {
        return studentMapper;
    }

    @Autowired
    public void setStudentMapper(StudentMapper studentMapper) {
        this.studentMapper = studentMapper;
    }

    @Override
    public Student selectOne(Integer id) {
        return studentMapper.selectOne(1);
    }
}

在controller下建立StudentController.java

@Controller
public class StudentController {
    private StudentService studentService;

    @RequestMapping("show")
    public String show(ModelMap map,HttpServletRequest request){
        map.put("student",studentService.selectOne(1));
        return "success";
    }

    public StudentService getStudentService() {
        return studentService;
    }

    @Autowired
    public void setStudentService(StudentService studentService) {
        this.studentService = studentService;
    }
}

在新建一个success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    ${requestScope.student}
</body>
</html>

将项目加载到Tomcat,执行

好了,测试已经成功了

最后在附上码云地址:https://gitee.com/hjm0928/SSM

以上是关于SSM框架+slf4j 以Gradle实现的主要内容,如果未能解决你的问题,请参考以下文章

SSM框架下结合 log4jslf4j打印日志

SSM框架——以注解形式实现事务管理

SSM框架以json格式传给前端页面

基于ssm框架没有pom.xml正常吗

SSM框架整合spring框架的搭建

ssm+maven(模块化)框架搭建(下)---ssm整合