欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

一步一步完成SSM框架整合(Spring+Spring MVC + Mybatis)

程序员文章站 2022-05-06 21:26:37
...

新建maven工程

eclipse中选择new Maven Project项,制定archetype为webapp,填写好groupId之类的,然后finish,这时可能工程有一些错误,通过修改Java Build Path,修复错误:
一步一步完成SSM框架整合(Spring+Spring MVC + Mybatis)一步一步完成SSM框架整合(Spring+Spring MVC + Mybatis)一步一步完成SSM框架整合(Spring+Spring MVC + Mybatis)

然后new一个server,将这个项目添加进去,修改server的context path为“/”,http端口设置为“80”,然后打开浏览器,访问“127.0.0.1”,出现“Hello world”即为成功:
一步一步完成SSM框架整合(Spring+Spring MVC + Mybatis)一步一步完成SSM框架整合(Spring+Spring MVC + Mybatis)

加入Spring

首先在pom.xml文件中dependency节点下添加下列依赖:

<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-context</artifactId>  
    <version>${spring.version}</version>
</dependency>

版本在properties节点下自己控制,这里只用引入一个spring-context,相关依赖的jar maven会帮我们自动引入,不用重复累赘再写一次。

为了测试spring集成的效果,我们需要一个bean来测试,新建一个User测试类:

package com.cjt.ssm.model;

public class User {

    private String name;

    private int age;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

同时在resources目录下新建一个spring的入口配置文件spring.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="  
            http://www.springframework.org/schema/beans  
            http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
            http://www.springframework.org/schema/aop  
            http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

    <bean id="user" class="com.cjt.ssm.model.User" />
</beans>

然后新建main方法测试类Test,测试spring是否集成成功:

package com.cjt.ssm;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.cjt.ssm.model.User;

public class Test {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
        User user = context.getBean("user", User.class);
        System.out.println(user);
    }
}

运行Test类,若是spring集成成功,日志台会打印相关spring加载日志,并且user也能够正常获取,打印user:

一步一步完成SSM框架整合(Spring+Spring MVC + Mybatis)

加入Mybatis

涉及到数据持久化方面,首先得有数据来源,在本地mysql数据库ssm下新建一张user表:
一步一步完成SSM框架整合(Spring+Spring MVC + Mybatis)

然后随便添加一条记录,{“name”:”ssm”,”age”:18},方便待会测试之用;

然后同样在pom.xml添加MyBatis的依赖:

<dependency>
    <groupId>org.mybatis</groupId>  
    <artifactId>mybatis</artifactId>  
    <version>${mybatis.version}</version>  
</dependency>

<dependency>
    <groupId>mysql</groupId>  
    <artifactId>mysql-connector-java</artifactId>  
    <version>${mysql.version}</version>  
</dependency>

指定版本为mybatis版本为3.2.0,mysql版本是5.1.33;

在resources目录下新建mybatis.xml,作为mybatis的配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC" />
            <!-- 配置数据库连接信息 -->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver" />
                <property name="url" value="jdbc:mysql://localhost:3306/ssm" />
                <property name="username" value="root" />
                <property name="password" value="xxx" />
            </dataSource>
        </environment>
    </environments>

    <!-- resource需要写成路径的形式 -->    
    <mappers>
        <!-- <mapper resource="userMapper.xml"/> -->
    </mappers>
</configuration>

然后同目录新建测试的userMapper.xml,主要用于编写sql:

<?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">
<!-- namespace用作标识mapper的唯一,通常包名+文件名 -->
<mapper namespace="user">
    <select id="findAll" resultType="com.cjt.ssm.model.User">
        select * from user
    </select>
</mapper>

记得在上面mybatis.xml配置文件的mappers节点下添加这个作为测试的userMapper,这样mybatis的准备工作也做完了,修改Test内容,验证MyBatis是否正常:

package com.cjt.ssm;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import com.cjt.ssm.model.User;

public class Test {

    public static void main(String[] args) throws IOException {
        String resource = "mybatis.xml";
        InputStream is = Resources.getResourceAsStream(resource);
        // build接受不同的参数,可采取其他方法创建SqlSessionFactory
        SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession session = sessionFactory.openSession();
        String statement = "user.findAll";
        // session拥有多个方法,可以自行研究
        List<User> users = session.selectList(statement);
        for (User user : users) {
            System.out.println(user);
        }
    }
}

修改User类增加toString()方法,运行程序,若是能正常打印我们user表中的数据,则MyBatis配置成功:
一步一步完成SSM框架整合(Spring+Spring MVC + Mybatis)

整合Spring与MyBatis

首先新建一个dao包,在下面编写User对应的借口UserDao:

package com.cjt.ssm.dao;

import java.util.List;

import com.cjt.ssm.model.User;

public interface UserDao {

    List<User> findAll();
}

然后修改spring.xml配置文件,将数据库配置和dao所对应的bean都添加进去:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="  
            http://www.springframework.org/schema/beans  
            http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
            http://www.springframework.org/schema/aop  
            http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName">
            <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="username">
            <value>root</value>
        </property>
        <property name="password">
            <value>Cjt00382114.</value>
        </property>
        <property name="url">
            <value>jdbc:mysql://localhost:3306/ssm</value>
        </property>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis.xml" />
    </bean>

    <!-- DAO接口所在包名,Spring会自动查找其下的类(不用写注解) -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.cjt.ssm.dao" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
    </bean> 
</beans>

记得修改userMapper.xml的namespace为该Dao的全路径,这样保证了spring绑定的bean能够执行对应的sql语句,然后去掉mybatis.xml配置文件中的数据源配置节点environments ;

这一步就要添整合相关的依赖jar包了:

<dependency>  
    <groupId>org.mybatis</groupId>  
    <artifactId>mybatis-spring</artifactId>  
    <version>${commons-dbcp.version}</version>
</dependency>

<dependency>  
   <groupId>commons-dbcp</groupId>  
   <artifactId>commons-dbcp</artifactId>  
   <version>${commons-dbcp.version}</version>  
</dependency>

<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-jdbc</artifactId>  
    <version>${spring.version}</version>  
</dependency>

修改Test文件,准备测试:

package com.cjt.ssm;

import java.io.IOException;
import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.cjt.ssm.dao.UserDao;
import com.cjt.ssm.model.User;

public class Test {

    public static void main(String[] args) throws IOException {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring.xml");
        UserDao userDao = ctx.getBean("userDao", UserDao.class);
        List<User> users = userDao.findAll();
        for (User user : users) {
            System.out.println(user);
        }
    }
}

观察控制台输出,正常输出user表中的数据则说明spring与mybatis集成成功:
一步一步完成SSM框架整合(Spring+Spring MVC + Mybatis)

集成Spring MVC

首先引入Spring MVC所需要的jar包:

<dependency>  
    <groupId>org.springframework</groupId>  
    <artifactId>spring-webmvc</artifactId>  
    <version>${spring.version}</version>  
</dependency>

<dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>${jackson.version}</version>
</dependency>

修改spring.xml,添加springmvc相关配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://www.springframework.org/schema/beans" 
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="  
            http://www.springframework.org/schema/beans  
            http://www.springframework.org/schema/beans/spring-beans-3.2.xsd  
            http://www.springframework.org/schema/aop  
            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-3.2.xsd
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

    <mvc:annotation-driven />

    <context:component-scan base-package="com.cjt.ssm" />


    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName">
            <value>com.mysql.jdbc.Driver</value>
        </property>
        <property name="username">
            <value>root</value>
        </property>
        <property name="password">
            <value>Cjt00382114.</value>
        </property>
        <property name="url">
            <value>jdbc:mysql://localhost:3306/ssm</value>
        </property>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation" value="classpath:mybatis.xml" />
    </bean>

    <!-- DAO接口所在包名,Spring会自动查找其下的类(不用写注解) -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
        <property name="basePackage" value="com.cjt.ssm.dao" />  
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>  
    </bean>
</beans>

然后修改web.xml,配置springmvc servlet分发器,并设置request/response的编码格式:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >
 <web-app>
  <!-- 编码过滤器 -->  
  <filter>  
      <filter-name>encodingFilter</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>encodingFilter</filter-name>  
      <url-pattern>/*</url-pattern>
  </filter-mapping>

  <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.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>
</web-app>

新建controller,作为springmvc的测试之用:

package com.cjt.ssm.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cjt.ssm.dao.UserDao;
import com.cjt.ssm.model.User;

@Controller
@RequestMapping(value="/")
public class TestController {

    @Resource
    private UserDao userDao;

    @RequestMapping(value="/test")
    @ResponseBody
    public List<User> test(){
        List<User> users = userDao.findAll();
        return users;
    }
}

此时就可以启动server,测试了:
一步一步完成SSM框架整合(Spring+Spring MVC + Mybatis)

此时,还没算作大功告成。。。

解决乱码

乱码的问题,归根结底就是编码不一致导致的。例如,你的文件是utf-8的,你却硬要用gbk的编码方式展示,那么就会显示一长串的乱码。既然这样,那么简单来说,解决办法即为统一编码。为了字符编码兼容,统一设置为“UTF-8”。

首先设置filter过滤器,设置request和response的编码方式,在web.xml中添加过滤器:

<!-- 编码过滤器 -->  
<filter>  
   <filter-name>encodingFilter</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>encodingFilter</filter-name>  
   <url-pattern>/*</url-pattern>
</filter-mapping>

这个对应解决post表单的参数后天接受时,和response往页面输出内容时出现的乱码情况,但记得使用response的时候设置response.setContentType("text/html;charset=UTF-8")

使用jsp页面渲染的要注意头部添加<%@ page contentType="text/html; charset=UTF-8" %>,并且同时设置当前html<meta charset="UTF-8">,其他页面渲染(freemaker、vm等)自行研究配置,这里不深入讨论。这适用于解决一些原本存在页面中的中文乱码,即controller返回的页面原本的中文内容乱码。

springmvc、tomcat、eclipse默认都是ISO-8859-1,所以都需要手动设置编码为UTF-8

因此,若是controller注解了@Responsebody直接返回的String内容,没有经过response输出,这种也会乱码,所以还要修改spring.xml,配置springmvc的编码,将<mvc:annotation-driven />修改为:

<mvc:annotation-driven>
    <!-- 消息转换器 -->
    <mvc:message-converters register-defaults="true">
        <bean class="org.springframework.http.converter.StringHttpMessageConverter">
            <property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
        </bean>
    </mvc:message-converters>
</mvc:annotation-driven>

到这里可以算作,SSM框架集成成功!!