SSM整合——父子容器

环境搭建

SSM整合——父子容器_第1张图片

导入依赖

 <dependencies>
        
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
            <version>5.1.47version>
        dependency>
        
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>druidartifactId>
            <version>1.1.21version>
        dependency>

        
        <dependency>
            <groupId>javax.servlet.jspgroupId>
            <artifactId>jsp-apiartifactId>
            <version>2.1version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>servlet-apiartifactId>
            <version>2.5version>
        dependency>
        <dependency>
            <groupId>javax.servletgroupId>
            <artifactId>jstlartifactId>
            <version>1.2version>
        dependency>

        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.4.6version>
        dependency>

        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatis-springartifactId>
            <version>2.0.4version>
        dependency>
	    
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
        dependency>
        
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-webmvcartifactId>
            <version>5.2.0.RELEASEversion>
        dependency>
        <dependency>
            <groupId>org.springframeworkgroupId>
            <artifactId>spring-jdbcartifactId>
            <version>5.2.5.RELEASEversion>
        dependency>
         
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <version>1.18.10version>
        dependency>
    dependencies>
    
    <build>
        <resources>
            <resource>
                <directory>src/main/resourcesdirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>truefiltering>
            resource>
            <resource>
                <directory>src/main/javadirectory>
                <includes>
                    <include>**/*.propertiesinclude>
                    <include>**/*.xmlinclude>
                includes>
                <filtering>truefiltering>
            resource>
        resources>
    build>

web.xml

    
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
    listener>
    <context-param>
        <param-name>contextConfigLocationparam-name>
        <param-value>classpath:applicationContext.xmlparam-value>
    context-param>

    
    <servlet>
        <servlet-name>DispatcherServletservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:springmvc-servlet.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>DispatcherServletservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>


    
    <filter>
        <filter-name>CharacterEncodingFilterfilter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
        <init-param>
            <param-name>encodingparam-name>
            <param-value>utf-8param-value>
        init-param>
        <init-param>
            <param-name>forceEncodingparam-name>
            <param-value>trueparam-value>
        init-param>
    filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilterfilter-name>
        <url-pattern>/*url-pattern>
    filter-mapping>

目录结构

SSM整合——父子容器_第2张图片

Mybatis

POJO

@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
    private Integer id;
    private String username;
    private Date birthday;
    private String sex;
    private String address;
}

Mapper接口

public interface UserMapper {
    //增加一个用户
    int addUser(User user);
    //删除一个用户
    int deleteUserById(int id);
    //更新一个用户
    int updateUser(User user);
    //查询一个用户
    User queryUserById(int id);
    //查询所有用户
    List<User> queryAllUser();
}

Mapper配置文件



<mapper namespace="com.shang.Mapper.UserMapper">

    <insert id="addUser" parameterType="com.shang.pojo.User">
        insert into mybatis.user (username,birthday,sex,address)
        values (#{username},#{birthday},#{sex},#{address});
    insert>

    <delete id="deleteUserById" parameterType="int">
        delete from mybatis.user where id = #{id}
    delete>

    <update id="updateUser" parameterType="com.shang.pojo.User">
        update mybatis.user
        set username = #{username},birthday=#{birthday},sex=#{sex},address=#{address}
        where id=#{id};
    update>

    <select id="queryUserById" parameterType="int" resultType="com.shang.pojo.User">
        select * from mybatis.user where id=#{id};
    select>


    <select id="queryAllUser" resultType="com.shang.pojo.User">
        select * from mybatis.user;
    select>
mapper>

mybatis-config



<configuration>

    
    
    

    <mappers>
        <mapper class="com.shang.Mapper.UserMapper"/>
    mappers>
configuration>

Spring

db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123456

#datasource的properties引入文件,el表达式前必须加jdbc,没有配置就会报以下错误:
# Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: 
# Failed to obtain JDBC Connection; nested exception is java.sql.SQLException: 
# Access denied for user 'lenovo'@'localhost' (using password: YES)

applicationContext.xml


<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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    
    <context:property-placeholder location="classpath:db.properties"/>

    
    <bean id="userServiceImpl" class="com.shang.Service.UserServiceImpl">
        <property name="userMapper" ref="userMapper"/>
    bean>

    
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        
        <property name="initialSize" value="5"/>
        <property name="maxWait" value="60000"/>
        <property name="maxActive" value="15"/>
    bean>

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

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        
        <property name="basePackage" value="com.shang.Mapper"/>
    bean>

    
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    bean>

    

beans>

service

public interface UserService {
    //增加一个用户
    int addUser(User user);

    //删除一个用户
    int deleteUserById(int id);

    //更新一个用户
    int updateUser(User user);

    //查询一个用户
    User queryUserById(int id);

    //查询所有用户
    List<User> queryAllUser();
}

service的实现类

public class UserServiceImpl implements UserService {
    //service层调dao层,组合dao
    private UserMapper userMapper;

    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public int addUser(User user) {
        return userMapper.addUser(user);
    }

    @Override
    public int deleteUserById(int id) {
        return userMapper.deleteUserById(id);
    }

    @Override
    public int updateUser(User user) {
        return userMapper.updateUser(user);
    }

    @Override
    public User queryUserById(int id) {
        return userMapper.queryUserById(id);
    }

    @Override
    public List<User> queryAllUser() {
        return userMapper.queryAllUser();
    }
}

SpringMVC

springmvc-servlet.xml


<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
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        https://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    
    <context:component-scan base-package="com.shang.Controller"/>

    
    <mvc:default-servlet-handler/>
    
    <mvc:annotation-driven/>

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

beans>

Controller

@Controller
public class UserController {
    //调用Service层,组合service
    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;

    @RequestMapping("/allUser")
    public String list(Model model){
        List<User> users = userService.queryAllUser();
        model.addAttribute("users", users);
        return "allUser";
    }
}

index.jsp

使用${pageContext.request.contextPath}是很好的选择.

  <a href="${pageContext.request.contextPath}/allUser">进入用户界面a>

allUser.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <meta charset="utf-8">
    <title>Bootstrap 实例 - 基本的表格title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js">script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/js/bootstrap.min.js">script>
head>
<body>
<table class="table">
    <caption>基本的表格布局caption>
    <thead>
    <tr>
        <th>编号th>
        <th>用户名th>
        <th>生日th>
        <th>性别th>
        <th>地址th>
    tr>
    thead>
    <tbody>
    <c:forEach var="user" items="${users}">
    <tr>
            <td>${user.id}td>
            <td>${user.username}td>
            <td>${user.birthday}td>
            <td>${user.sex}td>
            <td>${user.address}td>
    tr>
    c:forEach>
    tbody>
table>
body>
html>

结果图
在这里插入图片描述

最终的目录结构

SSM整合——父子容器_第3张图片
当然,还有一种简单的整合方式,请看看下一篇。

你可能感兴趣的:(SpringMVC)