SSM整合:Spring、SpringMVC、Mybatis

整合环境:

    Windows、IdeaMavenMySql

1.创建maven项目

maven配置:settings.xml文件设置:

本地仓库地址:

<localRepository>本地repositor路径</localRepository>

阿里maven镜像:

<mirrors>
  <mirror>
    <id>alimaven</id>
    <mirrorOf>*</mirrorOf>
    <name>aliyun maven</name>
    <url>http://maven.aliyun.com/nexus/content/groups/public/</url>
  </mirror>
</mirrors>

指定jdk版本:

<profile>  
	<id>jdk-1.8</id>  
	<activation>  
		<activeByDefault>true</activeByDefault>  
		<jdk>1.8</jdk>  
	</activation>  
	<properties>  
		<maven.compiler.source>1.8</maven.compiler.source>  
		<maven.compiler.target>1.8</maven.compiler.target>  
		<maven.compiler.compilerVersion>1.8</maven.compiler.compilerVersion>  
	</properties>  
</profile>

2.添加所依赖的jar包

(1)spring

            (2)springMVC(SpringMVC版本必须大于3.0.5 不然测试报下标越界)

            (3)MyBatis

            (4)数据库连接池[C3P0],驱动包

            (5)其他(jstl,servlet-api,junit)

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>top.ar13</groupId>
  <artifactId>StudentSSM</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>StudentSSM Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.7</maven.compiler.source>
    <maven.compiler.target>1.7</maven.compiler.target>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.8</version>
    </dependency>
    <!--引入项目所以来的jar包-->
    <!--SpringMVC 版本必须大于3.0.5 不然测试报下标越界-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>5.0.11.RELEASE</version>
    </dependency>
    <!--SpringJDBC-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.0.11.RELEASE</version>
    </dependency>
    <!--Spring面向切面aspects-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>3.0.5.RELEASE</version>
    </dependency>
    <!--mybatis-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>3.5.2</version>
    </dependency>
    <!--mybatis整合spring的适配包-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>2.0.2</version>
    </dependency>
    <!--数据库连接池-->
    <dependency>
      <groupId>com.mchange</groupId>
      <artifactId>c3p0</artifactId>
      <version>0.9.5.2</version>
    </dependency>
    <!--mysql驱动-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.6</version>
    </dependency>
    <!--JSTL-->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!--servlet 服务其中存在,但是不添加本地又报错,所以用scope指定本地使用-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
      <scope>provided</scope>
    </dependency>
  </dependencies>

  <build>
    <finalName>StudentSSM</finalName>
    <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
      <plugins>
        <plugin>
          <artifactId>maven-clean-plugin</artifactId>
          <version>3.1.0</version>
        </plugin>
        <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
        <plugin>
          <artifactId>maven-resources-plugin</artifactId>
          <version>3.0.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.8.0</version>
        </plugin>
        <plugin>
          <artifactId>maven-surefire-plugin</artifactId>
          <version>2.22.1</version>
        </plugin>
        <plugin>
          <artifactId>maven-war-plugin</artifactId>
          <version>3.2.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-install-plugin</artifactId>
          <version>2.5.2</version>
        </plugin>
        <plugin>
          <artifactId>maven-deploy-plugin</artifactId>
          <version>2.8.2</version>
        </plugin>
      </plugins>
    </pluginManagement>
  </build>
</project>

3.编写SSM整合的关键配置文件

(1)web.xml

<!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 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">

  <display-name>Archetype Created Web Application</display-name>
    <welcome-file-list>
        <welcome-file>/WEB-INF/jsp/index.jsp</welcome-file>
    </welcome-file-list>
      <!--1.启动Spring的容器-->
      <context-param>
        <param-name>contextConfigLocation</param-name>
        <!--指定加载spring配置文件-->
        <param-value>classpath:applicationContext.xml</param-value>
      </context-param>
      <!--监听器-->
      <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>
      <!--2.配置SpringMVC前端控制器  拦截所有请求-->
      <servlet>
        <servlet-name>springDispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--指定SpringMVC配置文件的位置-->
        <init-param>
          <param-name>contextConfigLocation</param-name>
          <param-value>classpath:springMVC.xml</param-value>
        </init-param>
        <!--设置启动时加载servlet-->
        <!--
            1)load-on-startup元素标记容器是否在启动的时候就加载这个servlet(实例化并调用其init()方法)。
            2)它的值必须是一个整数,表示servlet应该被载入的顺序
            3)当值为0或者大于0时,表示容器在应用启动时就加载并初始化这个servlet;
            4)当值小于0或者没有指定时,则表示容器在该servlet被选择时才会去加载。
            5)正数的值越小,该servlet的优先级越高,应用启动时就越先加载。
            6)当值相同时,容器就会自己选择顺序来加载。
        -->
        <load-on-startup>1</load-on-startup>
      </servlet>
      <!--设置拦截所有的请求-->
      <servlet-mapping>
        <servlet-name>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
      </servlet-mapping>
      <!--3.字符编码过滤器  一定要放在所有过滤器之前的-->
      <filter>
        <filter-name>Encoding</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>
        <!--设置request的格式-->
        <init-param>
          <param-name>forceRequestEncoding</param-name>
          <param-value>true</param-value>
        </init-param>
        <!--设置response的格式-->
        <init-param>
          <param-name>forceResponseEncoding</param-name>
          <param-value>true</param-value>
        </init-param>
      </filter>
      <!--拦截所有请求进行过滤-->
      <filter-mapping>
        <filter-name>Encoding</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
      <!--4.使用rest风格 将页面普通的post请求转为指定的delete或者put请求-->
      <filter>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
      </filter>
      <!--拦截所有请求-->
      <filter-mapping>
        <filter-name>HiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
      </filter-mapping>
</web-app>

(2)springMVC

<?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:mvc="http://www.springframework.org/schema/mvc"
       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">

    <!--SpringMVC的配置文件  包含网站跳转逻辑的控制   默认扫描所有的   需要禁用掉默认的过滤规则-->
    <context:component-scan base-package="top.ar13" use-default-filters="false">
        <!--只扫描控制器-->
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
    </context:component-scan>
    <!--配置视图解析器  方便页面返回-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!--后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--两个标配-->
    <!--将springMVC不能处理的请求交给tomcat 实现动态静态资源都能访问成功-->
    <mvc:default-servlet-handler/>
    <!--启动注解驱动-->
    <mvc:annotation-driven/>
</beans>

(3)spring配置文件(applicationContext.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" xmlns:tx="http://www.springframework.org/schema/tx"
       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 http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!--Spring的配置文件,这里主要配置和业务逻辑有关的-->
    <context:component-scan base-package="top.ar13">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
    </context:component-scan>
    <!--配置数据源-->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <bean id="db" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="${jdbc.driver}"></property>
        <property name="jdbcUrl" value="${jdbc.url}"></property>
        <property name="user" value="${jdbc.username}"></property>
        <property name="password" value="${jdbc.password}"></property>
    </bean>


    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--配置数据库-->
        <property name="dataSource" ref="db"></property>
        <!--配置实体类在哪里-->
        <property name="typeAliasesPackage" value="top.ar13.entity"></property>
        <!--配置sql语句Mapper文件在哪里-->
        <property name="mapperLocations" value="classpath:/mapper/*.xml"></property>
    </bean>
    <!--配置mapper接口-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--mapper的位置-->
        <property name="basePackage" value="top.ar13.mapper"></property>
        <!--接口与xml文件结合-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactoryBean"></property>
    </bean>
</beans>

(4)mybatis(mybatis-config.xml)

<?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>
    <!--开启自动驼峰命名规则-->
    <settings>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!--类型别名-->
    <typeAliases>
        <package name="top.ar13.entity"/>
    </typeAliases>
</configuration>

4.创建实体,mapper接口,mapper.xml,service,serviceimpl实现

User实体类

/**
 * Created by IntelliJ IDEA.
 * User: AnRan
 * Date: 2019/10/15
 */
@Data
public class User {
    private Integer id;
    private String user_name,password,nick_name;
}

Mapper接口

/**
 * Created by IntelliJ IDEA.
 * User: AnRan
 * Date: 2019/10/15
 */
public interface UserMapper {

    List<User> queryAll();


}

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="top.ar13.mapper.UserMapper">

    <select id="queryAll" resultType="top.ar13.entity.User">
        SELECT * FROM t_user
    </select>

</mapper>

Service

/**
 * Created by IntelliJ IDEA.
 * User: AnRan
 * Date: 2019/10/15
 */
public interface UserService {
    List<User> queryAll();
}

ServiceImpl实现

/**
 * Created by IntelliJ IDEA.
 * User: AnRan
 * Date: 2019/10/15
 */
@Service("UserService")
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Override
    public List<User> queryAll() {
        return userMapper.queryAll();
    }
}

5.测试Service

package top.ar13.service;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import top.ar13.mapper.UserMapper;



/**
 * Created by IntelliJ IDEA.
 * User: AnRan
 * Date: 2019/10/15
 */

public class UserServiceImplTest {
    
    @Test
    public void queryAll() {
        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) context.getBean("UserService");

        System.out.println(userService.queryAll());
    }
}

得到的结果集为:

[User(id=2, user_name=admin, password=123, nick_name=管理员), User(id=7, user_name=userNameC, password=passwordD, nick_name=nickNameC), User(id=8, user_name=user3, password=1212, nick_name=nickname3)]

6.Controller控制器


/**
 * Created by IntelliJ IDEA.
 * User: AnRan
 * Date: 2019/10/15
 */
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "queryAll")
    public String queryAll(Model model){
        model.addAttribute("list",userService.queryAll());
        return "list";
    }


}

7.页面部分

 (1).index.jsp 只进行跳转

<jsp:forward page="/queryAll"></jsp:forward>

(2).list.jsp  列表展示

<%--
  Created by IntelliJ IDEA.
  User: AnRan
  Date: 2019/10/15
  Time: 9:52
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<table align="center" border="1">
    <tr>
        <td>编号</td>
        <td>用户名</td>
        <td>昵称</td>
        <td>密码</td>
    </tr>
    <c:forEach items="${list}" var="item">
        <tr>
            <td>${item.id}</td>
            <td>${item.user_name}</td>
            <td>${item.nick_name}</td>
            <td>${item.password}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>

8.集成tomcat并运行

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇