SSM框架整合demo

  • Post author:
  • Post category:其他




提示

本demo只是对SSM框架进行整合搭建的一个demo,并不包含其他的功能,只供ssm框架整合借鉴。



先对spring和springMVC框架进行整合

  1. 导入pom依赖
<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>
    <junit.version>4.11</junit.version>
    <spring-webmvc.version>5.3.19</spring-webmvc.version>
    <spring-jdbc.version>5.3.16</spring-jdbc.version>
    <jsp.version>2.2</jsp.version>
    <jstl.version>1.2</jstl.version>
    <servlet.version>2.5</servlet.version>
    <log4j.version>1.2.17</log4j.version>
    <slf4j.version>1.6.6</slf4j.version>
    <fastjson.version>1.2.78</fastjson.version>
    <mybatis.version>3.5.6</mybatis.version>
    <mybatis-spring.version>2.0.7</mybatis-spring.version>
    <druid.version>1.2.8</druid.version>
    <mysql-connector.version>8.0.27</mysql-connector.version>
    <jsr303.version>0.0.2</jsr303.version>
    <lombok.version>1.18.22</lombok.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>

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

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

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

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>${jsp.version}</version>
    </dependency>

    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>${jstl.version}</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>${servlet.version}</version>
    </dependency>

    <dependency>
      <groupId>log4j</groupId>
      <artifactId>log4j</artifactId>
      <version>${log4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-api</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
      <version>${slf4j.version}</version>
    </dependency>

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>${fastjson.version}</version>
    </dependency>

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

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

    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>druid</artifactId>
      <version>${druid.version}</version>
    </dependency>

    <dependency>
      <groupId>fun.fengwk.auto-validation</groupId>
      <artifactId>jsr303</artifactId>
      <version>${jsr303.version}</version>
    </dependency>

    <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>${lombok.version}</version>
    </dependency>
  </dependencies>

  <build>
    <finalName>ssm_demo</finalName>
	<!--配置静态资源文件导出-->
    <resources>
      <resource>
        <directory>src/main/java</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
      <resource>
        <directory>src/main/resources</directory>
        <includes>
          <include>**/*.properties</include>
          <include>**/*.xml</include>
        </includes>
        <filtering>false</filtering>
      </resource>
    </resources>
  </build>
  1. web.xml文件配置dispatcherServlet和字符过滤器
<servlet>
    <servlet-name>dispacherServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <!--项目初始化就加载DispatcherServlet-->
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>dispacherServlet</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <!--配置字符过滤器, name只能为encoding-->
  <filter>
    <filter-name>encoding</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>encoding</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!--监听器,在项目启动时,同时启动spring工厂,使得dao和service以及druid连接池启动-->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

  <!--配置spring文件路径-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  1. 建立springmvc.xml文件
<context:component-scan base-package="com.demo.ssm.controller"/>

<mvc:annotation-driven/>

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

<!--过滤静态资源-->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<mvc:resources mapping="/images/**" location="/images/"/>
<mvc:resources mapping="/css/**" location="/css/"/>
<mvc:resources mapping="/js/**" location="/js/"/>
  1. 建立各个package,完整demo结构如图所示

    在这里插入图片描述

  2. 在controller中编写test方法测试springMVC是否能够正常运行

@Controller
@RequestMapping("/admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    @GetMapping("/getOneAdmin")
    public String test(Model model) {
        Admin admin = adminService.getOneAdmin();
        System.out.println(JSON.toJSONString(admin));
        model.addAttribute("admin", admin);
        return "t";
    }
}

index.jsp文件内容

<body>
    <a href="${pageContext.request.contextPath}/admin/getOneAdmin">测试</a>
</body>

t.jsp文件内容

<body>
    这里是测试界面...
</body>

到此为止,部署tomcat之后能够正常从index.jsp页面跳转到t.jsp页面,说明springMVC搭建成功。


如果页面跳转时出现404页面找不到


在Project Structure下Artifacts中选择项目 ->WEB-INF,在这个文件夹下新建lib文件夹,然后点击+号然后选择所有的library文件并保存,重启服务器即可

在这里插入图片描述



整合mybatis

建立applicationContext.xml文件配置mybatis相关的内容

<!--spring接管mybatis-->
<!--dataSource Druid连接池-->
<context:property-placeholder location="classpath:db.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
    <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="minIdle" value="5"/>
    <!--最大连接池数量-->
    <property name="maxActive" value="20"/>
    <!--获取连接的最大等待时间,单位毫秒-->
    <property name="maxWait" value="60000"/>
</bean>

<!--SqlSessionFactory 要dataSource支持-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <!--注入连接池-->
    <property name="dataSource" ref="dataSource"/>
    <!--使得实体类中用类名作为别名-->
    <property name="typeAliasesPackage" value="com.demo.ssm.pojo"></property>
    <!--配置mapper文件所在的位置-->
    <property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>

<!--Dao 需要MapperScannerConfigurer支持-->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.demo.ssm.dao"/>
    <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>

<!--告知spring注解位置,保证注解有效性,不扫描controller注解-->
<context:component-scan base-package="com.demo.ssm">
    <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</context:component-scan>

<!--引入事务管理器-->
<bean id="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSource"/>
</bean>

<!--告知spring定制事务是基于DataSourceTransactionManager-->
<tx:annotation-driven transaction-manager="tx"/>

接下来在service和dao层分别编写一个getOneAdmin方法测试是否能够成功从数据库查询到数据

AdminMapper内容

public interface AdminMapper {
    Admin getOneAdmin();
}

AdminMapper.xml内容

<mapper namespace="com.demo.ssm.dao.AdminMapper">
    <select id="getOneAdmin" resultType="com.demo.ssm.pojo.Admin">
        SELECT * FROM admin LIMIT 1;
    </select>
</mapper>

AdminService内容

public interface AdminService {
    Admin getOneAdmin();
}

AdminServiceImpl内容

@Service("adminService")
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Admin getOneAdmin() {
        System.out.println("test......");
        return adminMapper.getOneAdmin();
    }
}

db_library.sql文件内容

Navicat MySQL Data Transfer

Source Server         : localhost
Source Server Version : 50729
Source Host           : localhost:3306
Source Database       : db_library

Target Server Type    : MYSQL
Target Server Version : 50729
File Encoding         : 65001

Date: 2022-04-23 23:05:43
*/

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `admin`
-- ----------------------------
DROP TABLE IF EXISTS `admin`;
CREATE TABLE `admin` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `username` varchar(20) DEFAULT NULL COMMENT '用户名',
  `password` varchar(20) DEFAULT NULL COMMENT '密码',
  `adminType` int(11) DEFAULT NULL COMMENT '管理员类型',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='管理员';

-- ----------------------------
-- Records of admin
-- ----------------------------
INSERT INTO `admin` VALUES ('1', 'admin', '12345', '1');
INSERT INTO `admin` VALUES ('2', 'test', '12345', '0');

到这里SSM框架整合就完成啦,运行服务器即可测试是否整合成功,后续的功能代码可以在此demo的基础上进行编写。


自己学习的ssm整合的操作,实操了一遍能够正常运行,若小伙伴发现了其他的问题也可以留言交流,共同进步!



版权声明:本文为W31003原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。