搭建ssm

搭建流程

  • 环境准备:jdk,maven,mysql
  • 新建maven项目,选择webapp结构
  • 按照需要的依赖包,配置pom文件(spring,mybatis,Junit,logback,连接池,数据库,json转换等)
  • 数据库建表
  • db.properties,mybatis-configuration.xml
  • spring-dao.xml,spring-service.xml,spring-transation.xml
  • springmvc.xml
  • 配置web.xml
  • 编写mapper接口和mapper.xml
  • 对mapper进行单元测试
  • 编写service接口和实现类
  • 编写controller
  • 视图文件编写(直接使用接口测试)
  • 部署,测试

项目结构

image.png

这里mapper.xml文件没有和mapper放在接口一起,而是和其他配置文件一样,放在resources文件夹下

pom.xml

依赖项主要包含spring,mybatis,数据库驱动,连接池(commons-dbcp),json转换器,slf4j+logback,Junit,插件中包含tomcat7-maven-plugin,如果使用maven部署项目就需要,直接使用tomcat8则不需要,因为maven部署项目默认使用tomcat6,但是tomcat6下会报错,因为相关的servlet-api已经变了




  4.0.0

  com.ilovestudy
  ssm
  1.0-SNAPSHOT
  war

  ssm Maven Webapp
  
  http://www.example.com

  
    UTF-8
    1.8
    1.8
    5.1.4.RELEASE
    3.5.0
    1.7.25
    1.2.3
    4.11
    2.9.7
  

  
    
    
      org.springframework
      spring-core
      ${spring-version}
    

    
      org.springframework
      spring-beans
      ${spring-version}
    

    
      org.springframework
      spring-context
      ${spring-version}
    

    
      org.springframework
      spring-context-support
      ${spring-version}
    

    
      org.springframework
      spring-aop
      ${spring-version}
    

    
      org.springframework
      spring-tx
      ${spring-version}
    

    
      org.springframework
      spring-jdbc
      ${spring-version}
    

    
      org.springframework
      spring-orm
      ${spring-version}
    

    
      org.springframework
      spring-web
      ${spring-version}
    

    
      org.springframework
      spring-webmvc
      ${spring-version}
    

    
      org.springframework
      spring-aspects
      ${spring-version}
    

    
      org.springframework
      spring-test
      ${spring-version}
    
    

    
    
      org.mybatis
      mybatis
      ${mybatis-version}
    

    
    
      org.mybatis
      mybatis-spring
      1.3.2
    

    
    
      mysql
      mysql-connector-java
      5.1.39
    

    
    
      commons-pool
      commons-pool
      1.6
    

    
    
      commons-dbcp
      commons-dbcp
      1.4
    

    
      commons-beanutils
      commons-beanutils
      1.9.3
    
    

    
    
      org.slf4j
      slf4j-api
      ${slf4j-version}
    

    
    
      ch.qos.logback
      logback-core
      ${logback-version}
    

    
      ch.qos.logback
      logback-classic
      ${logback-version}
    

    
      ch.qos.logback
      logback-access
      ${logback-version}
    

    
    
      com.fasterxml.jackson.core
      jackson-core
      ${jackson.version}
    

    
      com.fasterxml.jackson.core
      jackson-annotations
      ${jackson.version}
    

    
      com.fasterxml.jackson.core
      jackson-databind
      ${jackson.version}
    

    
    
      junit
      junit
      ${junit-version}
      test
    
  

  
    ssm
    
      
        
        
          org.apache.tomcat.maven
          tomcat7-maven-plugin
          2.2
        
        
          maven-clean-plugin
          3.1.0
        
        
        
          maven-resources-plugin
          3.0.2
        
        
          maven-compiler-plugin
          3.8.0
        
        
          maven-surefire-plugin
          2.22.1
        
        
          maven-war-plugin
          3.2.2
        
        
          maven-install-plugin
          2.5.2
        
        
          maven-deploy-plugin
          2.8.2
        
      
    
  

建表

DROP TABLE IF EXISTS `student`;
CREATE TABLE `student` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `number` char(8) DEFAULT NULL,
  `name` varchar(12) DEFAULT NULL,
  `age` int(3) DEFAULT NULL,
  PRIMARY KEY (`id`)
)

db.properties

这里选择的是apache commons中的dbcp,不同的数据库连接池(c3p0,druid)配置有所不同

jdbc.driver = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
jdbc.username = luckee
jdbc.password = 123
#初始连接数
jdbc.initialSize = 0
#最大连接数
jdbc.maxActive = 20
#最大空闲连接数
jdbc.maxIdle = 20
#最小空闲连接数
jdbc.minIdle = 1
#最大等待时间
jdbc.maxWait = 60000

mybatis-config.xml




    
    
        
    

    
    
        
    

logback.xml



    
        
            %d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
        
    
    
        
    

Student.java

package com.ilovestudy.entity;

import java.util.Objects;

/**
 * @author : Luckee
 * @date : 2019/2/22 20:55
 * @description :
 */
public class Student {
    private Integer id;
    private String number;
    private String name;
    private Integer age;

    public Student() {

    }

    public Student(Integer id, String number, String name, Integer age) {
        this.id = id;
        this.number = number;
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        Student student = (Student) o;
        return Objects.equals(id, student.id) &&
                Objects.equals(number, student.number) &&
                Objects.equals(name, student.name) &&
                Objects.equals(age, student.age);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, number, name, age);
    }

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

dao层

  • StudentMapper接口
package com.ilovestudy.dao;

import com.ilovestudy.entity.Student;

import java.util.List;

public interface StudentMapper {
    void insertStudent(Student student) throws Exception;
    List selectAll()throws Exception;
    List select(Student student)throws Exception;
}
  • StudentMapper.xml




    
        
            select LAST_INSERT_ID()
        
        insert into student(number,name,age) values(#{number},#{name},#{age})
    

    

    


  • spring-dao.xml



    
    

    
    
        
        
        
        
        
        
        
        
        
    

    
    
        
        
        
    

    
    
        
        
    


  • 测试StudentMapper
package com.ilovestudy.dao;

import com.ilovestudy.entity.Student;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import static org.junit.Assert.*;

public class StudentMapperTest {

    private ClassPathXmlApplicationContext context = null;
    @Before
    public void setUp() throws Exception {
        context = new ClassPathXmlApplicationContext("classpath:spring/spring-dao.xml");
    }

    @Test
    public void testInsertStudent() throws Exception {
        StudentMapper mapper = context.getBean(StudentMapper.class);
        Student student = new Student();
        student.setNumber("13108313");
        student.setName("hpp");
        student.setAge(24);
        mapper.insertStudent(student);
    }

    @After
    public void tearDown() throws Exception {
        context.close();
    }
}

service层

  • StudentService接口
package com.ilovestudy.service;

import com.ilovestudy.entity.Student;

import java.util.List;

public interface StudentService {

    void addStudent(Student student) throws Exception;

    List queryAll()throws Exception;

    List query(Student student)throws Exception;
}
  • 实现类StudentServiceImpl
package com.ilovestudy.service.serviceImpl;

import com.ilovestudy.dao.StudentMapper;
import com.ilovestudy.entity.Student;
import com.ilovestudy.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author : Luckee
 * @date : 2019/2/22 21:14
 * @description :
 */

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper mapper;

    @Override
    public void addStudent(Student student) throws Exception {
        mapper.insertStudent(student);
    }

    @Override
    public List queryAll() throws Exception {
        return mapper.selectAll();
    }

    @Override
    public List query(Student student) throws Exception {
        return mapper.select(student);
    }
}
  • spring-service.xml



    
    
    

事务管理spring-transaction.xml




    
    

    
    
        
    

    
    
        
            
        
    

    
    
        
        
    


controller层

  • StudentController
package com.ilovestudy.controller;

import com.ilovestudy.entity.Student;
import com.ilovestudy.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * @author : Luckee
 * @date : 2019/2/22 22:56
 * @description :
 */

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/addStudent")
    @ResponseBody
    public String addStudent(Student student) throws Exception{
        studentService.addStudent(student);
        return "add student successfully";
    }

    @RequestMapping("/queryAll")
    @ResponseBody
    public List queryAll()throws Exception {
        return studentService.queryAll();
    }

    @RequestMapping("/query")
    @ResponseBody
    public List query(Student student)throws Exception {
        return studentService.query(student);
    }
}
  • springmvc.xml



    
    

    
    
        
            
            
        
    

    
    

    
    
        
        
    


web.xml




  ssm demo

  
  
    contextConfigLocation
    classpath:spring/spring-*.xml
  

  
  
    org.springframework.web.context.ContextLoaderListener
  

  
  
    encodingFilter
    org.springframework.web.filter.CharacterEncodingFilter
    
      encoding
      utf-8
    
  

  
    encodingFilter
    /*
  

  
  
    springmvc
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath:spring/springmvc.xml
    
    1
  

  
    springmvc
    /
  

  
    /index.jsp
  

  
    404
    /404.html
  

部署

Run--Edit Configurations--Templates点击+按钮

  • maven


    image.png

    由于maven默认使用tomcat6,后面会报错,所以这里使用tomcat7,因此需要在pom文件里添加tomcat7插件依赖(详细见前面的pom.xml文件)

  • tomcat


    image.png

    我两种部署方式都试了,觉得还是tomcat的方式更好用点,因为maven方式出了好几个问题(比如乱码),而我对maven使用和配置也不熟悉,tomcat方式就没那么多幺蛾子。

接口测试

如浏览器输入http://localhost:8080/ssm/queryAll

遇到的问题(注意的地方)

  • 由于有多个配置文件,所以如果想引用另一个配置文件中的bean,需要使用导入对应的配置文件
  • 乱码问题
    尽量在使用到编码方式的地方都设置为utf-8,主要在前端页面,项目编码,服务器编码,数据库编码几个地方
  • 由于配置文件较多,所以建议使用idea的文件模板功能
  • xml的命名空间的写法和含义
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd

xsd文件可以不用写版本号,在依赖的jar包中有xsd文件,spring解析的时候回在本地的jar包中找

代码地址

代码github地址

总结

本次虽然经过一波三折搭建好了ssm框架,起码可以运行起来,但只是实现了最简单的功能,熟悉ssm的使用还有很长的路要走。

更新-添加aop

  1. 在common包中新建aspect包
package com.ilovestudy.common.aspect;

import org.aspectj.lang.JoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author : Luckee
 * @date : 2019/2/26 14:43
 * @description :
 */
public class MyAspect {

    private final Logger logger = LoggerFactory.getLogger(MyAspect.class);

    public void beforeExecution(JoinPoint joinPoint){
        System.out.println("@Before advice");
        logger.info("before executing " + joinPoint.getSignature().getName());
    }
}
  1. 添加配置文件spring-aspect.xml



    

    
    
        
            
            
        
    

这里需要注意的是,你要选择对谁进行aop,如果是对controller进行aop,就应该在springmvc的配置文件中配置,如果是要对service层进行aop,则应该在spring的配置文件中配置,因为controller是由springmvc容器管理的,service层是由spring容器管理的,spring容器是springmvc的父容器,子容器可以访问父容器的东西,反之则不行,如果觉得不理解,参考这篇博文

你可能感兴趣的:(搭建ssm)