龙空技术网

来份干货!新鲜出炉的SSM框架整合「手写代码剖析」

麒麟Java工程师 166

前言:

此刻兄弟们对“整合ssm框架常见的问题”可能比较关切,小伙伴们都需要学习一些“整合ssm框架常见的问题”的相关资讯。那么小编在网络上网罗了一些关于“整合ssm框架常见的问题””的相关内容,希望我们能喜欢,大家快快来学习一下吧!

前言

掌握 SSM 框架之后,最好是自己从零开始写一个项目来感受一下三个框架的整合过程,但在整合过程中需要注意很多的问题,也有一些非常棒的设计思想能够运用到项目。

基本环境搭建1.数据库准备

本文中使用的是sqlserver数据库,创建一个叫test的数据库,然后建立一个account的表,表的字段设计如下图:

2.创建maven工程

为了更方便的管理包,所以我们采用maven来进行包的管理工作,创建好maven管理的web项目(项目名为practice3)后,便是进行包的引入,修改pom.xml文件,修改为:

<?xml version="1.0" encoding="UTF-8"?><project xmlns="; xmlns:xsi=";         xsi:schemaLocation=" ;>  <modelVersion>4.0.0</modelVersion>  <groupId>org.example</groupId>  <artifactId>practice3</artifactId>  <version>1.0-SNAPSHOT</version>  <packaging>war</packaging>  <name>practice3 Maven Webapp</name>  <!-- FIXME change it to the project's website -->  <url>;/url>  <properties>    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>    <maven.compiler.source>11</maven.compiler.source>    <maven.compiler.target>11</maven.compiler.target>    <spring.version>5.0.2.RELEASE</spring.version>    <slf4j.version>1.6.6</slf4j.version>    <log4j.version>1.2.12</log4j.version>    <mysql.version>5.1.6</mysql.version>    <mybatis.version>3.4.5</mybatis.version>    <tomcat.version>9.0.26</tomcat.version>  </properties>  <dependencies>    <!-- 嵌入式Tomcat -->    <dependency>      <groupId>org.apache.tomcat.embed</groupId>      <artifactId>tomcat-embed-core</artifactId>      <version>${tomcat.version}</version>      <scope>provided</scope>    </dependency>    <dependency>      <groupId>org.apache.tomcat.embed</groupId>      <artifactId>tomcat-embed-jasper</artifactId>      <version>${tomcat.version}</version>      <scope>provided</scope>    </dependency>    <!-- jdbc驱动-->    <dependency>      <groupId>com.microsoft.sqlserver</groupId>      <artifactId>mssql-jdbc</artifactId>      <version>8.4.1.jre11</version>      <scope>runtime</scope>    </dependency>    <dependency>      <groupId>org.aspectj</groupId>      <artifactId>aspectjweaver</artifactId>      <version>1.6.8</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-aop</artifactId>      <version>${spring.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-context</artifactId>      <version>${spring.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-web</artifactId>      <version>${spring.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-webmvc</artifactId>      <version>${spring.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-test</artifactId>      <version>${spring.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-tx</artifactId>      <version>${spring.version}</version>    </dependency>    <dependency>      <groupId>org.springframework</groupId>      <artifactId>spring-jdbc</artifactId>      <version>${spring.version}</version>    </dependency>    <dependency>      <groupId>junit</groupId>      <artifactId>junit</artifactId>      <version>4.12</version>      <scope>compile</scope>    </dependency>    <dependency>      <groupId>mysql</groupId>      <artifactId>mysql-connector-java</artifactId>      <version>${mysql.version}</version>    </dependency>    <dependency>      <groupId>javax.servlet</groupId>      <artifactId>servlet-api</artifactId>      <version>2.5</version>      <scope>provided</scope>    </dependency>    <dependency>      <groupId>javax.servlet.jsp</groupId>      <artifactId>jsp-api</artifactId>      <version>2.0</version>      <scope>provided</scope>    </dependency>    <dependency>      <groupId>jstl</groupId>      <artifactId>jstl</artifactId>      <version>1.2</version>    </dependency> <!-- log start -->    <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> <!-- log end -->    <dependency>      <groupId>org.mybatis</groupId>      <artifactId>mybatis</artifactId>      <version>${mybatis.version}</version>    </dependency>    <dependency>      <groupId>org.mybatis</groupId>      <artifactId>mybatis-spring</artifactId>      <version>1.3.0</version>    </dependency>    <dependency>      <groupId>c3p0</groupId>      <artifactId>c3p0</artifactId>      <version>0.9.1.2</version>      <type>jar</type>      <scope>compile</scope>    </dependency>  </dependencies>  <build>    <finalName>practice2</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  -->        <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>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
3.建立实体类

建立一个存取数据的实体类Account(com.gx.domain包中建立),实体类的代码如下:

package com.gx.domain;import java.io.Serializable;public class Account implements Serializable {    private Integer id;    private String name;    private Double money;    public Integer getId() {        return id;    }    public void setId(Integer id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public Double getMoney() {        return money;    }    public void setMoney(Double money) {        this.money = money;    }    @Override    public String toString() {        return "Account{" +                "id=" + id +                ", name='" + name + '\'' +                ", money=" + money +                '}';    }}1234567891011121314151617181920212223242526272829303132333435363738394041424344

实体类的三个属性分别对应了数据库的三个属性列。

4.编写service接口和service实现类

service接口:

package com.gx.service;import com.gx.domain.Account;import java.util.List;public interface AccountService {    // 查询所有账户    public List<Account> findAll();}123456789101112

service实现类:

package com.gx.service.Impl;import com.gx.domain.Account;import com.gx.service.AccountService;import org.springframework.stereotype.Service;import java.util.List;@Service("accountService")public class AccountServiceImpl implements AccountService {    @Override    public List<Account> findAll() {        System.out.println("Service业务层:查询所有账户...");        return null;    }}1234567891011121314151617

到这里基本环境就配置好了,目录结构如下:

2.Spring框架的实现1.编写applicationContext.xml的配置文件

创建applicationContext.xml文件,然后文件内容编写如下:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns=";       xmlns:xsi=";       xmlns:context=";       xmlns:aop=";       xmlns:tx=";       xsi:schemaLocation="							;>    <!--开启注解的扫描,希望处理service和dao,controller不需要Spring框架去处理-->    <context:component-scan base-package="com.gx" >        <!--配置哪些注解不扫描-->        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />    </context:component-scan>    </beans>1234567891011121314151617181920212223
3.SpringMVC的实现1.修改web.xml

对web.xml进行修改,修改后如下:

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "; ><web-app xmlns:xsi=";        xmlns=";        xsi:schemaLocation=" ;        version="3.0">  <display-name>Archetype Created Web Application</display-name>       <!--配置前端控制器-->  <servlet>     <servlet-name>dispatcherServlet</servlet-name>      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>      <!--加载springmvc.xml配置文件-->      <init-param>          <param-name>contextConfigLocation</param-name>          <param-value>classpath:springmvc.xml</param-value>      </init-param>      <!--启动服务器,创建该servlet-->      <load-on-startup>1</load-on-startup>  </servlet>    <servlet-mapping>        <servlet-name>dispatcherServlet</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping>    <!--解决中文乱码的过滤器-->    <filter>        <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping></web-app>123456789101112131415161718192021222324252627282930313233343536373839404142
2.编辑springmvc.xml文件

创建springmvc.xml文件,文件的内容如下:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns=";       xmlns:mvc=";       xmlns:context=";       xmlns:xsi=";       xsi:schemaLocation="                                                ;>    <!--开启注解扫描,只扫描Controller注解-->    <context:component-scan base-package="com.gx">        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>    </context:component-scan>    <!--配置的视图解析器对象-->    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/WEB-INF/pages/"/>        <property name="suffix" value=".jsp"/>    </bean>    <!--开启SpringMVC注解的支持-->    <mvc:annotation-driven/></beans>12345678910111213141516171819202122232425
3.创建jsp页面和控制层代码

修改index.jsp页面(由于建立的是web项目,所以会有一个index.jsp文件,所以直接修改这个文件就可以了),修改后的内容如下:

<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><body><form action="/account/findAll" method="get">    <button type="submit">查询数据库数据</button></form></body></html>12345678

然后创建控制类AccountController,内容如下:

package com.gx.controller;import com.gx.domain.Account;import com.gx.service.AccountService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import java.util.List;@Controllerpublic class AccountController {    @RequestMapping("/account/findAll")    public String findAll(){        System.out.println("Controller表现层:查询所有账户...");        return "list";  //在视图解析器中配置了前缀后缀    }}1234567891011121314151617181920

然后建立跳转后的list页面,在图示目录下建立list.jsp文件,

list.jsp的内容如下:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %><%@ taglib prefix="c" uri="; %><html><head>    <title>Title</title></head><body><h2>查询所有的账户</h2><tr>    <td>ID</td>    <td>名称</td>    <td>余额</td></tr><br><c:forEach items="${list}" var="account">    <tr>        <td>${account.id}</td>        <td>${account.name}</td>        <td>${account.money}</td>    </tr>    <br></c:forEach></body></html>12345678910111213141516171819202122232425
4.部署tomcat进行测试

从前面maven引入的包中可以看出,项目是采用引入tomcat的相应包来启动tomcat服务的,所以只需编写一个Main类负责启动tomcat即可。编写的Main类如下:

package com.gx;import org.apache.catalina.Context;import org.apache.catalina.WebResourceRoot;import org.apache.catalina.startup.Tomcat;import org.apache.catalina.webresources.DirResourceSet;import org.apache.catalina.webresources.StandardRoot;import java.io.File;public class Main {    public static void main(String[] args) throws Exception {        Tomcat tomcat = new Tomcat();        tomcat.setPort(Integer.getInteger("port", 8080));        tomcat.getConnector();        Context ctx = tomcat.addWebapp("", new File("src/main/webapp").getAbsolutePath());        WebResourceRoot resources = new StandardRoot(ctx);        resources.addPreResources(                new DirResourceSet(resources, "/WEB-INF/classes", new File("target/classes").getAbsolutePath(), "/"));        ctx.setResources(resources);        tomcat.start();        tomcat.getServer().await();    }}12345678910111213141516171819202122232425

然后运行main类的main方法,在浏览器输入localhost:8080后,显示主页面,点击按钮,能成功的跳转即为成功。

5.Spring整合SpringMVC1.在web.xml中配置ContextLoaderListener监听器

在web.xml中加入ContextLoaderListener监听器,代码如下:

 <!--配置Spring的监听器,默认只加载WEB-INF目录下的applicationContext.xml配置文件-->    <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener> <!--设置配置文件的路径-->    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>classpath:applicationContext.xml</param-value>    </context-param>12345678910
2.controller中注入service对象,调用service对象方法

修改AccountController.java文件,修改后如下:

package com.gx.controller;import com.gx.domain.Account;import com.gx.service.AccountService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import java.util.List;@Controllerpublic class AccountController {    @Autowired    private AccountService accountService ;    @RequestMapping("/account/findAll")    public String findAll(Model model) {  //存数据, Model对象        System.out.println("Controller表现层:查询所有账户...");        // 调用service的方法        List<Account> list = accountService.findAll();        model.addAttribute("list",list);        return "list";    }}12345678910111213141516171819202122232425262728
6.MyBatis的实现1.创建SqlMapConfig.xml文件

内容如下:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"        ";><configuration>    <environments default="sql-server">        <environment id="sql-server">            <transactionManager type="JDBC"/>            <dataSource type="POOLED">                <property name="driver" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>                <property name="url" value="jdbc:sqlserver://localhost:1433;DatabaseName=test"/>                <property name="username" value="root"/>                <property name="password" value="1234567890"/>            </dataSource>        </environment>    </environments><!--    <!– 使用的是注解 –>--><!--    <mappers>--><!--        <!– <mapper class="com.gx.dao.IAccountdao"/> –> <!– 该包下所有的dao接口都可以使用 –>--><!--        <package name="com.gx.dao"/>--><!--    </mappers>-->    <!-- 配置映射资源文件-->    <mappers>        <mapper resource="userMapper.xml"/>    </mappers></configuration>123456789101112131415161718192021222324
2.建立userMapper.xml

内容如下:

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE mapper        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"        ";><mapper namespace="com.gx.domain.Account">    <!-- 查询全部用户-->    <select id="queryAccounts" resultType="com.gx.domain.Account">        select * from account    </select></mapper>12345678910
3.建立MyBatisutil文件

创建MyBatisutil.java文件,用于获取sqlsession对象,文件内容如下:

7.Spring整合MyBatis1.在applicationContext.xml中配置数据库连接池

配置的代码如下:

<!--Spring整合MyBatis框架-->    <!--配置连接池-->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="driverClass" value="com.mysql.jdbc.Driver"/>        <property name="jdbcUrl" value="jdbc:mysql:///ssm"/>        <property name="user" value="root"/>        <property name="password" value="root"/>    </bean>123456789

最终的applicationContext.xml文件如下:

<?xml version="1.0" encoding="UTF-8"?><beans xmlns=";       xmlns:xsi=";       xmlns:context=";       xmlns:aop=";       xmlns:tx=";       xsi:schemaLocation="							;>    <!--开启注解的扫描,希望处理service和dao,controller不需要Spring框架去处理-->    <context:component-scan base-package="com.gx" >        <!--配置哪些注解不扫描-->        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />    </context:component-scan>    <!--Spring整合MyBatis框架-->    <!--配置连接池-->    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">        <property name="driverClass" value="com.microsoft.sqlserver.jdbc.SQLServerDriver"/>        <property name="jdbcUrl" value="jdbc:sqlserver://localhost:1433;DatabaseName=test"/>        <property name="user" value="root"/>        <property name="password" value="1234567890"/>    </bean></beans>12345678910111213141516171819202122232425262728293031
8.收尾部分

到这里ssm的整合基本完成,接下来就是来编写自己的业务逻辑的部分。

1.完善AccountServiceImpl实现类

代码如下:

package com.gx.service.Impl;import com.gx.domain.Account;import com.gx.service.AccountService;import com.gx.util.MyBatisutil;import org.apache.ibatis.session.SqlSession;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;@Service("accountService")public class AccountServiceImpl implements AccountService {    @Override    public List<Account> findAll() {        System.out.println("Service业务层:查询所有账户...");        // 获取SqlSession对象        SqlSession session = MyBatisutil.getSqlSession();        // 查询全部对象        List<Account> list = session.selectList("com.gx.domain.Account.queryAccounts");        return list;    }}123456789101112131415161718192021222324
2.运行测试

测试成功的页面如下:

点击按钮

这里查到的数据和数据库的数据相同。

原文链接:

欢迎大家一起交流,喜欢我的分享 记得 关注转发哟,感谢支持!

标签: #整合ssm框架常见的问题