长亭百川云 - 文章详情

记录一次SSM搭建过程(方便日后复制粘贴) - admin-神风

博客园 - admin-神风

40

2024-07-19

一、配置Spring所需依赖

pom.xml项目中添加如下依赖


<?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\>org.spring</groupId\>
  <artifactId\>SpringAPITest</artifactId\>
  <version\>1.0-SNAPSHOT</version\>
  <packaging\>war</packaging\>

  <name\>SpringAPITest 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\>
    <spring.version\>4.3.25.RELEASE</spring.version\>
    <mybatis.version\>3.5.0</mybatis.version\>
  </properties\>

  <dependencies\>
    <dependency\>
      <groupId\>junit</groupId\>
      <artifactId\>junit</artifactId\>
      <version\>4.11</version\>
      <scope\>test</scope\>
    </dependency\>

    <!-- 核心包 \-->
    <dependency\>
      <groupId\>org.springframework</groupId\>
      <artifactId\>spring-core</artifactId\>
      <version\>${spring.version}</version\>
    </dependency\>
    <!-- bean管理所需要的jar包 \-->
    <dependency\>
      <groupId\>org.springframework</groupId\>
      <artifactId\>spring-beans</artifactId\>
      <version\>${spring.version}</version\>
    </dependency\>
    <!-- 上下文支持jar包 \-->
    <dependency\>
      <groupId\>org.springframework</groupId\>
      <artifactId\>spring-context</artifactId\>
      <version\>${spring.version}</version\>
    </dependency\>
    <!-- 数据库访问层需要的jar包 \-->
    <dependency\>
      <groupId\>org.springframework</groupId\>
      <artifactId\>spring-jdbc</artifactId\>
      <version\>${spring.version}</version\>
    </dependency\>
    <dependency\>
      <groupId\>org.springframework</groupId\>
      <artifactId\>spring-tx</artifactId\>
      <version\>${spring.version}</version\>
    </dependency\>
    <!-- spring 提供的测试插件 \-->
    <dependency\>
      <groupId\>org.springframework</groupId\>
      <artifactId\>spring-test</artifactId\>
      <version\>${spring.version}</version\>
    </dependency\>
    <!-- 网络支持jar包,可以使用Spring框架的支持开发Servlet代码. \-->
    <dependency\>
      <groupId\>org.springframework</groupId\>
      <artifactId\>spring-web</artifactId\>
      <version\>${spring.version}</version\>
    </dependency\>
    <!-- spring mvc所需包 \-->
    <dependency\>
      <groupId\>org.springframework</groupId\>
      <artifactId\>spring-webmvc</artifactId\>
      <version\>${spring.version}</version\>
    </dependency\>
    <!-- mybatis所需包 \-->
    <dependency\>
      <groupId\>org.mybatis</groupId\>
      <artifactId\>mybatis</artifactId\>
      <version\>${mybatis.version}</version\>
    </dependency\>
    <!-- Mybatis和Spring关联包 \-->
    <dependency\>
      <groupId\>org.mybatis</groupId\>
      <artifactId\>mybatis-spring</artifactId\>
      <version\>1.3.1</version\>
    </dependency\>
    <!-- 数据库连接 \-->
    <dependency\>
      <groupId\>mysql</groupId\>
      <artifactId\>mysql-connector-java</artifactId\>
      <version\>8.0.19</version\>
      <scope\>runtime</scope\>
    </dependency\>
    <!-- 数据库连接池 \-->
    <dependency\>
      <groupId\>com.mchange</groupId\>
      <artifactId\>c3p0</artifactId\>
      <version\>0.9.5.2</version\>
    </dependency\>
  </dependencies\>

  <build\>
    <plugins\>
      <plugin\>
        <groupId\>org.apache.maven.plugins</groupId\>
        <artifactId\>maven-compiler-plugin</artifactId\>
        <version\>3.8.0</version\>
        <configuration\>
          <!-- 指定source和target的版本 \-->
          <source\>1.8</source\>
          <target\>1.8</target\>
        </configuration\>
      </plugin\>
    </plugins\>
  </build\>
</project\>

点击此处查看pom.xml文件

 添加完依赖之后就是配置web.xml文件,使其关联起来我们的applicationContext.xml和Spring-mvc.xml配置


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

  <!-- 配置applicationContext \-->
  <context-param\>
    <param-name\>contextConfigLocation</param-name\>
    <param-value\>classpath:applicationContext.xml</param-value\>
  </context-param\>
  <!-- 启动spring的容器 \-->
  <listener\>
    <listener-class\>
      org.springframework.web.context.ContextLoaderListener
    </listener-class\>
  </listener\>

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

  <servlet\>
    <servlet-name\>SpringMVC</servlet-name\>
    <servlet-class\>org.springframework.web.servlet.DispatcherServlet</servlet-class\>
    <!-- 配置springMVC需要加载的配置文件\-->
    <init-param\>
      <param-name\>contextConfigLocation</param-name\>
      <param-value\>classpath:spring-\*.xml</param-value\>
    </init-param\>
    <load-on-startup\>1</load-on-startup\>
    <async-supported\>true</async-supported\>
  </servlet\>
  <servlet-mapping\>
    <servlet-name\>SpringMVC</servlet-name\>
    <!-- 匹配所有请求 \-->
    <url-pattern\>/</url-pattern\>
  </servlet-mapping\>

</web-app\>

点击此处查看web.xml文件

二、创建相关类

然后就是在项目中创建几个包类,大致结构如下

 在pojo中创建一个User类


package org.spring.apitest.pojo;

public class User {
    int id;
    String username;
    String password;
    String address;

    public int getId() {
        return id;
    }

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

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

User类

再到dao里面

package org.spring.apitest.dao;

import org.spring.apitest.pojo.User;

public interface UserDao {
    User findUserById(int id);
}

和service里建立对应类

package org.spring.apitest.service;

import org.spring.apitest.pojo.User;

public interface UserService {
    public User findUserById(int id);
}

以及新建一个Impl接口实现类

package org.spring.apitest.service.impl;

import org.spring.apitest.dao.UserDao;
import org.spring.apitest.pojo.User;
import org.spring.apitest.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;

public class UserServiceImpl implements UserService {

    @Autowired
    UserDao userDao;

    @Override
    public User findUserById(int id) {
        return userDao.findUserById(id);
    }
}

建立完成之后就可以配置数据库相关了


jdbc.driver=com.mysql.cj.jdbc.Driver
#数据库地址
jdbc.url=jdbc:mysql://localhost:3306/ssm?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=UTC&allowPublicKeyRetrieval=true
#用户名
jdbc.username=root
#密码
jdbc.password=root

#最大连接数
c3p0.maxPoolSize=30
#最小连接数
c3p0.minPoolSize=10
#关闭连接后不自动commit
c3p0.autoCommitOnClose=false
#获取连接超时时间
c3p0.checkoutTimeout=10000
#当获取连接失败重试次数
c3p0.acquireRetryAttempts=2

jdbc.properties

以及Mapping的配置文件


<?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\="org.spring.apitest.dao.UserDao"\>
    <select id\="selectUserByUname" resultType\="org.spring.apitest.pojo.User"
            parameterType\="java.lang.String"\>
        select \* from user where id = #{uname}
    </select\>
</mapper\>

Mapping文件

最后就是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: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/tx http://www.springframework.org/schema/tx/spring-tx.xsd"\>

    <!-- 扫描apitest包下所有使用注解的类型 \-->
    <context:component-scan base-package\="org.spring.apitest"/>

    <!-- 配置数据库相关参数properties的属性:${url} \-->
    <context:property-placeholder location\="classpath:jdbc.properties"/>

    <!-- 数据库连接池 \-->
    <bean id\="dataSource" class\="com.mchange.v2.c3p0.ComboPooledDataSource"\>
        <property name\="driverClass" value\="${jdbc.driver}"/>
        <property name\="jdbcUrl" value\="${jdbc.url}"/>
        <property name\="user" value\="${jdbc.username}"/>
        <property name\="password" value\="${jdbc.password}"/>
        <property name\="maxPoolSize" value\="${c3p0.maxPoolSize}"/>
        <property name\="minPoolSize" value\="${c3p0.minPoolSize}"/>
        <property name\="autoCommitOnClose" value\="${c3p0.autoCommitOnClose}"/>
        <property name\="checkoutTimeout" value\="${c3p0.checkoutTimeout}"/>
        <property name\="acquireRetryAttempts" value\="${c3p0.acquireRetryAttempts}"/>
    </bean\>

    <!-- 配置SqlSessionFactory对象 \-->
    <bean id\="sqlSessionFactory" class\="org.mybatis.spring.SqlSessionFactoryBean"\>
        <!-- 注入数据库连接池 \-->
        <property name\="dataSource" ref\="dataSource"/>
        <!-- 扫描entity包 使用别名 \-->
        <property name\="typeAliasesPackage" value\="org.spring.apitest.pojo"/>
        <!-- 扫描sql配置文件:mapper需要的xml文件 \-->
        <property name\="mapperLocations" value\="classpath:Mapping/\*.xml"/>
    </bean\>

    <!-- 配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 \-->
    <bean class\="org.mybatis.spring.mapper.MapperScannerConfigurer"\>
        <!-- 注入sqlSessionFactory \-->
        <property name\="sqlSessionFactoryBeanName" value\="sqlSessionFactory"/>
        <!-- 给出需要扫描Dao接口包 \-->
        <property name\="basePackage" value\="org.spring.apitest.dao"/>
    </bean\>

    <!-- 配置事务管理器 \-->
    <bean id\="transactionManager" class\="org.springframework.jdbc.datasource.DataSourceTransactionManager"\>
        <!-- 注入数据库连接池 \-->
        <property name\="dataSource" ref\="dataSource"/>
    </bean\>

    <!-- 配置基于注解的声明式事务 \-->
    <tx:annotation-driven transaction-manager\="transactionManager"/>
</beans\>

和Sprin-mvc.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:p\="http://www.springframework.org/schema/p"
       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-3.1.xsd
                        http://www.springframework.org/schema/context
                        http://www.springframework.org/schema/context/spring-context-3.1.xsd
                        http://www.springframework.org/schema/mvc
                        http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"\>

    <!-- 配置springMVC \-->
    <!-- 1.开启springMVC注解模式 \-->
    <!--DispatcherServlet启用基于annotation的HandlerMapping \-->
    <!-- a.自动注册DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter
         b.默认提供一系列的功能:数据绑定,数字和日期的format@NumberFormat,@DateTimeFormat
         c:xml,json的默认读写支持
     \-->
    <mvc:annotation-driven />

    <!--2.静态资源默认servlet配置\-->
    <!--1).加入对静态资源处理:js,gif,png
        2).允许使用 "/" 做整体映射
    \-->
    <mvc:default-servlet-handler/>

    <!-- 定义视图文件解析 \-->
    <bean
            class\="org.springframework.web.servlet.view.InternalResourceViewResolver"\>
        <property name\="prefix" value\="/WEB-INF/view/" />
        <property name\="suffix" value\=".jsp" />
    </bean\>

    <!-- 自动扫描该包,使SpringMVC认为包下用了@controller注解的类是控制器 \-->
    <context:component-scan base-package\="org.spring.apitest.controller"/>
</beans\>

之后创建Controller处理器


package org.spring.apitest.controller;

import org.spring.apitest.dao.UserDao;
import org.spring.apitest.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HttpTestController {

    @Autowired
    UserDao userDao;

    @RequestMapping("/select")
    public String select(int id, Model model) {
        User list \= userDao.findUserById(id);
        model.addAttribute("userInfo", list);
        return "user";
    }
}

Controller处理器代码

以及视图层的user.jsp文件


<%--
  Created by IntelliJ IDEA.
  User: peco
  Date: 2021/3/1
  Time: 14:00
  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>
用户信息
    <br>
        ${userInfo.id }&nbsp;&nbsp;&nbsp;&nbsp;
        ${userInfo.username }&nbsp;&nbsp;&nbsp;&nbsp;
        ${userInfo.password }&nbsp;&nbsp;&nbsp;&nbsp;
        ${userInfo.address }
    <br>
</body>
</html>

JSP代码

最终架构如下图所示:

相关推荐
关注或联系我们
添加百川云公众号,移动管理云安全产品
咨询热线:
4000-327-707
百川公众号
百川公众号
百川云客服
百川云客服

Copyright ©2024 北京长亭科技有限公司
icon
京ICP备 2024055124号-2