当前位置: 首页>后端>正文

java web ssm 整合- note

运行效果

java web ssm 整合- note,第1张

目录结构

java web ssm 整合- note,第2张

java web ssm 整合- note,第3张
.
├── pom.xml
├── src
│   └── main
│       ├── java
│       │   └── com
│       │       └── robert
│       │           ├── controller
│       │           │   └── SsmController.java
│       │           ├── dao
│       │           │   └── UserMapper.java
│       │           ├── pojo
│       │           │   └── User.java
│       │           └── service
│       │               ├── UserService.java
│       │               └── impl
│       │                   └── UserServiceImpl.java
│       ├── resources
│       │   ├── jdbc.properties
│       │   ├── mybatis
│       │   │   ├── mapper
│       │   │   │   └── UserMapper.xml
│       │   │   └── mybatis-config.xml
│       │   └── spring
│       │       ├── spring.xml
│       │       └── springmvc-config.xml
│       └── webapp
│           ├── WEB-INF
│           │   └── web.xml
│           ├── index.jsp
│           └── ssm.jsp
├── ssm_in_one.iml

新建一个java maven web 工程

pom.xml

<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>com.company</groupId>
  <artifactId>ssm_in_one</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>ssm_in_one</name>

  <!-- 集中定义依赖版本号 -->
  <properties>
    <junit.version>4.10</junit.version>
    <spring.version>4.1.3.RELEASE</spring.version>
    <mybatis.version>3.2.8</mybatis.version>
    <mybatis.spring.version>1.2.2</mybatis.spring.version>
    <mysql.version>5.1.32</mysql.version>
    <druid.version>1.1.6</druid.version>
    <slf4j.version>1.6.4</slf4j.version>
    <jstl.version>1.2</jstl.version>
    <servlet-api.version>2.5</servlet-api.version>
    <jsp-api.version>2.0</jsp-api.version>
    <jackson.version>2.4.2</jackson.version>
  </properties>

  <dependencies>
    <!-- 单元测试 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

    <!-- 整合spring框架(包含springmvc) 这个jar文件包含springmvc开发时的核心类, 同时也会将依赖的相关jar文件引入进来(spring的核心jar文件也包含在内) -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!--这个jar文件包含对Spring对JDBC数据访问进行封装的所有类 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!-- 整合mybatis框架 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>${mybatis.spring.version}</version>
    </dependency>
    <!-- mysql驱动 -->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>${mysql.version}</version>
    </dependency>
    <!-- druid连接池 -->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>${druid.version}</version>
    </dependency>
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>


  </dependencies>


  <build>
    <finalName>ssm_in_one</finalName>
  </build>

</project>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<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_2_5.xsd"
         id="WebApp_ID" version="2.5">

  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>

  </welcome-file-list>
  <!-- 配置springmvc, 将所有请求交给springmvc来处理 -->
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 配置springmvc核心配置文件的位置,默认Springmvc的配置文件是在WEB-INF目录下,默认的名字为springmvc-servlet.xml,如果要放在其他目录,则需要指定如下配置: -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring/*.xml</param-value>
    </init-param>
  </servlet>
  <!-- 其中的斜杠(/)表示拦截所有请求(除JSP以外), 所有请求都要经过springmvc前端控制器 -->
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!-- 乱码处理过滤器 -->
  <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>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <!-- 指定拦截方式为截所有请求 -->
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

spring.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop" 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-4.0.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

    <!-- 1.加载jdbc.properties文件的位置 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 2.配置druid连接池 ,id是固定值,class是druid连接池类的全路径 -->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <!-- 配置连接数据库的基本信息 -->
        <property name="driverClassName" value="${db.driverClassName}"></property>
        <property name="url" value="${db.url}"></property>
        <property name="username" value="${db.username}"></property>
        <property name="password" value="${db.password}"></property>
    </bean>

    <!-- 3.整合spring和mybatis框架
        将SqlSession等对象的创建交给Spring容器
        id值(sqlSessionFactory)是固定值
     -->
    <bean id="sqlSessionFactory"
          class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 3.1.指定mybatis核心配置文件的位置 -->
        <property name="configLocation"
                  value="classpath:mybatis/mybatis-config.xml"></property>
        <!-- 3.2.配置连接池(数据源) ref指向连接池bean对象的id值 -->
        <property name="dataSource" ref="dataSource"></property>
        <!-- 3.3、扫描所有的 XxxMapper.xml映射文件,读取其中配置的SQL语句 -->
        <property name="mapperLocations" value="classpath:mybatis/mapper/*.xml"/>
    </bean>

    <!-- 4、定义mapper接口扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 扫描所有XxxMapper接口,将接口实例的创建交给spring容器 -->
        <property name="basePackage" value="com.robert.dao"/>
    </bean>

    <!-- 5.配置需要扫描的包(service层):spring自动去扫描 base-package下的类,
        如果扫描到的类上有 @Controller、@Service、@Component等注解,
        将会自动将类注册为bean(即由spring创建实例)
     -->
    <context:component-scan base-package="com.robert.service">
    </context:component-scan>

</beans>

springmvc-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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
                        http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!-- 1.配置前端控制器放行静态资源(html/css/js等,否则静态资源将无法访问) -->
    <mvc:default-servlet-handler/>

    <!-- 2.配置注解驱动,用于识别注解(比如@Controller) -->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!-- 3.配置需要扫描的包:spring自动去扫描 base-package 下的类,
        如果扫描到的类上有 @Controller、@Service、@Component等注解,
        将会自动将类注册为bean
     -->
    <context:component-scan base-package="com.robert.controller">
    </context:component-scan>

    <!-- 4.配置内部资源视图解析器
        prefix:配置路径前缀
        suffix:配置文件后缀
     -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>


</beans>

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">

<!-- MyBatis的全局配置文件 -->
<configuration >

</configuration>

jdbc.properties

db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql:///java?characterEncoding=utf-8
db.username=root
db.password=root

sql

use java;
create table user(
username varchar(30),
pwd varchar(10)
);

insert into user values("zhangsan","123456");
insert into user values("lisi","12345");

UserMapper.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.robert.dao.UserMapper">

    <!-- 1.查询所有用户信息,id值为对应接口中方法的名字
        resultType指定将查询的结果封装到哪个pojo对象中
     -->
    <select id="findAll" resultType="com.robert.pojo.User">
        select * from User;
    </select>
</mapper>

SsmController.java

package com.robert.controller;

import com.robert.pojo.User;
import com.robert.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class SsmController {

    @Autowired
    UserService userService;

    @RequestMapping("/ssm")
    public ModelAndView holleMVC() {
        //1.调用findAll方法查询所有门店信息
        List<User> list = userService.findAll();
        ModelAndView mav = new ModelAndView("ssm");
        // must match the jsp page name which is being requested.
        mav.addObject("users", list);
        mav.addObject("greeting", "GeeksForGeeks Welcomes you to Spring!");

        return mav;
    }

}

UserService.java

package com.robert.service;

import com.robert.pojo.User;

import java.util.List;

public interface UserService {
    public List<User> findAll();
}

UserServiceImpl.java

package com.robert.service.impl;

import com.robert.dao.UserMapper;
import com.robert.pojo.User;
import com.robert.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service("userService")
public class UserServiceImpl implements UserService {

    @Autowired
    UserMapper usermapper;

    public List<User> findAll() {
        System.out.println("UserServiceImpl findAll");
        //1.调用findAll方法查询所有门店信息
        List<User> list = usermapper.findAll();
        //2.遍历所有门店信息
        for (User user : list) {
            System.out.println(user);
        }
        return list;
    }
}

User.java

package com.robert.pojo;

public class User {
    private String username;
    private String pwd;
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    @Override
    public String toString() {
        return "User [username=" + username + ", pwd=" + pwd + "]";
    }
}

UserMapper.java

package com.robert.dao;

import com.robert.pojo.User;

import java.util.List;

public interface UserMapper {
    /**
     * 1.查询所有用户信息
     */
    public List<User> findAll();
}

ssm.jsp

    <%@page language="java" contentType="text/html; charset=utf-8"
            pageEncoding="utf-8" isELIgnored="false" %>
        <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
        <html>
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
        </head>
        <body>
        <h2>Hello ssm!</h2>
        <h1>Start here</h1>
        ${greeting}
        <h3>list </h3>
        <c:forEach items="${requestScope.users}" var="u">
            ${u.username }-${u.pwd }<br/>
        </c:forEach>
        </body>
        </html>

总结

  • spring 通过IOC 和 DI ,整合spring mvc 和 mybatis,负责管理spring mvc和mybatis相关对象的创建和依赖注入
  • spring mvc 来处理客户端和应用通讯,路由、view 解析等,负责实现MVC设计模式
  • mybatis 负责数据持久化

ref

  • https://blog.csdn.net/Yo_Macro/article/details/90548895
  • https://infinitescript.com/2015/05/spring-mvc-mybatis-integration-tutorial/
  • https://www.geeksforgeeks.org/spring-mvc-with-jsp-view/
  • https://blog.csdn.net/qq_34638225/article/details/81261392
  • https://www.bilibili.com/video/BV1hE411F77L/

https://www.xamrdz.com/backend/3rt1942605.html

相关文章: