SSM整合-(spring+spring mvc+Mybatis)

目录

一、什么是SSM框架

二、系统架构图

三、搭建步骤

四、SSM框架示例

五、总结


介绍SSM框架<原理>
一、什么是SSM框架?
SSM框架是spring、spring MVC 、和mybatis框架的整合,是标准的MVC模式。SSM框架即是将SpringMVC框架、Spring框架、MyBatis框架整合使用。以简化在web开发中繁琐、重复的操作,让开发人员的精力专注于业务处理的开发上。标准的SSM框架有四层,分别是dao层(mapper),service层,controller层和View层。使用spring实现业务对象管理,使用spring MVC负责请求的转发和视图管理,mybatis作为数据对象的持久化引擎。

二、系统架构图

三、搭建步骤

SSM框架搭建实现步骤

(1)创建Web项目

创建项目包结构

引入相关jar文件

(2)修改web.xml文件

配置Spring MVC的前端控制器,指定Spring MVC配置文件位置(如下参考)

 <servlet>
    <servlet-name>springmvc</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>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

配置Spring框架的ContextLoaderListener(如下参考)

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:application.xml</param-value>
  </context-param>

配置字符编码过滤器(如下参考)

<!--乱码过滤-->
  <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.xml完整代码(如下参考)

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
  <description>Archetype Created Web Application</description>

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:application.xml</param-value>
  </context-param>


  <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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</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>
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>

</web-app>

(3)编写配置文件

database.properties(如下参考)

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/bian_li_dian?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT-8
user=root
pwd=123456

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

    <!-- 加载属性文件 -->
    <context:property-placeholder location="classpath:database.properties"></context:property-placeholder>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${driver}"></property>
        <property name="url" value="${url}"></property>
        <property name="username" value="${user}"></property>
        <property name="password" value="${pwd}"></property>
    </bean>
    <!-- 整合sqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"></property>
        <property name="configLocation" value="classpath:mybatis.xml"></property>
        <property name="mapperLocations" value="classpath:mapper/*.xml"></property>
    </bean>

    <!-- 专门扫描mapper接口 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.xinxi2.mapper"></property>
    </bean>

    <!-- 扫描@component的 -->
    <context:component-scan base-package="com.xinxi2"></context:component-scan>

    <!-- 数据源事务管理器 ioc,指定管理的数据源 -->
    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
        <property name="dataSource" ref="dataSource"></property>
    </bean>

    <!-- 事务管理器增强,配置方法的事务传播机制 -->
    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="del*" propagation="REQUIRED"/>
            <tx:method name="get*" propagation="REQUIRED" read-only="true"/>
        </tx:attributes>
    </tx:advice>

    <aop:config>
        <aop:pointcut id="servicePointcut" expression="execution(* com.xinxi2.service..*.*(..))"/>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"></aop:advisor>
    </aop:config>

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

    <!-- 全局设置 -->
    <settings>
        <setting name="logImpl" value="LOG4J"/>
    </settings>

</configuration>

typeAliases

typeAliases是MyBatis中的别名处理器类,翻译过来就是别名的意思,自动扫描cn.com.hello.pojo下的类型(如下参考)


<typeAliases>
    <package name="cn.com.hello.pojo"/>
</typeAliases>

全局性懒加载

懒加载的目的是减少内存的浪费和减轻系统的负担

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

    <context:component-scan base-package="com.xinxi2.controller,com.xinxi2.service"></context:component-scan>
    <!--Ajax 从controller到视图-->
    <mvc:annotation-driven>
        <mvc:message-converters>
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json;charset=UTF-8</value>
                        <value>text/html;charset=UTF-8</value>
                    </list>
                </property>
            </bean>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <property name="supportedMediaTypes">
                    <list>
                        <value>text/html;charset=UTF-8</value>
                        <value>application/json</value>
                    </list>
                </property>
                <property name="features">
                    <list>
                        <!-- Date的日期转换器 -->
                        <value>WriteDateUseDateFormat</value>
                    </list>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- 配置多视图解析器 -->
    <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean">
        <!-- 是否启用参数支持,默认为true(支持),即xxx?format=json、xml等形式。 -->
        <property name="favorParameter" value="true" />
        <!-- favorPathExtension:是否支持扩展名,默认为true(支持),扩展名指xxx.json、xxx.xml等形式 -->
        <property name="favorPathExtension" value="true" />
        <!-- 默认ContentType -->
        <property name="defaultContentType" value="application/json" />
        <!-- 配置映射关系 -->
        <!--扩展名到MIME的映射;favorPathExtension, favorParameter是true时起作用  -->
        <property name= "mediaTypes">
            <value>
                json=application/json
                xml=application/xml
                html=text/html
            </value>
        </property>
    </bean>
    <!-- VIEW解析定义。内容协商视图解析器;根据contentNegotiationManager使用的不同mediaTypes决定不同的 view进行响应  默认使用json-->
    <bean class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">

        <!-- 内容协商管理器 用于决定media type -->
        <property name="contentNegotiationManager" ref="contentNegotiationManager"/>
        <!-- 默认视图 解析 -->
        <property name="defaultViews">
            <list>
                <bean class="com.alibaba.fastjson.support.spring.FastJsonJsonView">
                    <property name="charset" value="UTF-8"/>
                </bean>
            </list>
        </property>
        <property name="viewResolvers">
            <list>
                <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
                    <property name="prefix" value="/WEB-INF/jsp/"/>
                    <property name="suffix" value=""/>
                </bean>
            </list>
        </property>
    </bean>

    <!-- 一般视图解析器 -->
<!--    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">-->
<!--        <property name="prefix" value="/WEB-INF/jsp/"></property>-->
<!--        <property name="suffix" value=""></property>-->
<!--    </bean>-->

    <!-- 解决静态资源的加载问题 -->
    <mvc:resources mapping="/staticabc/**" location="/static/"></mvc:resources>


    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <prop key="java.lang.RuntimeException">error.jsp</prop>
            </props>
        </property>
    </bean>

    <!-- 配置MultipartResolver,用于上传文件,使用spring的CommonsMultipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="5000000"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

<!--    <mvc:interceptors>-->
<!--        <mvc:interceptor>-->
<!--            <mvc:mapping path="/hello/**"/>-->
<!--            <mvc:exclude-mapping path="/hello/hello04"/>-->
<!--            <bean class="com.interceptor.LoginInterceptor"></bean>-->
<!--        </mvc:interceptor>-->
<!--    </mvc:interceptors>-->


</beans>

log4j.properties(如下参考)

log4j.rootLogger=DEBUG,CONSOLE,file
#log4j.rootLogger=ERROR,ROLLING_FILE
log4j.logger.cn.smbms.dao=debug
log4j.logger.com.ibatis=debug 
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=debug 
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=debug 
log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=debug 
log4j.logger.java.sql.Connection=debug 
log4j.logger.java.sql.Statement=debug 
log4j.logger.java.sql.PreparedStatement=debug 
log4j.logger.java.sql.ResultSet=debug 
log4j.logger.org.tuckey.web.filters.urlrewrite.UrlRewriteFilter=debug

######################################################################################
# Console Appender  \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=error
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= [%p] %d %c - %m%n


######################################################################################
# DailyRolling File  \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\u540d\u683c\u5f0f:log2009-09-11
######################################################################################
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=error
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n


log4j.logger.com.opensymphony.xwork2=error  

(4)创建详细包结构

四、SSM框架示例

以下是一个简单的SSM框架代码示例,包括了Spring、SpringMVC和MyBatis的集成:

  1. Spring配置文件(spring-context.xml)
<!-- 数据库连接配置 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${jdbc.driver}" />
    <property name="url" value="${jdbc.url}" />
    <property name="username" value="${jdbc.username}" />
    <property name="password" value="${jdbc.password}" />
</bean>

<!-- MyBatis配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="mapperLocations" value="classpath*:mapper/*.xml" />
</bean>

<!-- 扫描Mapper接口 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    <property name="basePackage" value="com.example.mapper" />
</bean>

<!-- Service组件扫描 -->
<context:component-scan base-package="com.example.service" />

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

<!-- 启用事务管理 -->
<tx:annotation-driven transaction-manager="transactionManager" />

<!-- 加载外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
  1. SpringMVC配置文件(spring-mvc.xml)
<!-- 开启SpringMVC注解处理器 -->
<mvc:annotation-driven />

<!-- 静态资源映射 -->
<mvc:resources mapping="/resources/**" location="/resources/" />

<!-- 设置视图解析器 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/views/" />
    <property name="suffix" value=".jsp" />
</bean>

<!-- Controller组件扫描 -->
<context:component-scan base-package="com.example.controller" />
  1. MyBatis Mapper接口示例(UserMapper.java)
@Repository
public interface UserMapper {
    @Select("SELECT * FROM users WHERE id = #{id}")
    User getUserById(Long id);

    @Insert("INSERT INTO users(username, password) VALUES(#{username}, #{password})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insertUser(User user);
}
  1. Spring Service组件示例(UserService.java)
@Service
@Transactional
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public User getUserById(Long id) {
        return userMapper.getUserById(id);
    }

    public int insertUser(User user) {
        return userMapper.insertUser(user);
    }
}
  1. SpringMVC Controller示例(UserController.java)
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/{id}")
    public String getUserById(@PathVariable("id") Long id, Model model) {
        User user = userService.getUserById(id);
        model.addAttribute("user", user);
        return "user";
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addUser(@ModelAttribute("user") User user) {
        userService.insertUser(user);
        return "redirect:/user/" + user.getId();
    }
}

五、总结

  • 1
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Java EE互联网轻量级框架整合开发的其中一种方式是使用SSM框架(Spring MVCSpringMyBatis)和Redis。 首先,SSM框架是一种非常流行的互联网开发框架,它结合了Spring MVCSpringMyBatis的优势。Spring MVC提供了MVC模式的实现,可以帮助我们构建灵活、可扩展的Web应用程序;Spring是一个轻量级的IOC(Inversion of Control)容器,并提供了丰富的企业级功能,如事务管理、安全性等;而MyBatis是一个简单易用的持久层框架,提供了ORM(Object Relational Mapping)和数据库访问的功能。 其次,Redis是一种开源的内存数据库,也是一种缓存数据库。它支持多种数据结构,如字符串、列表、哈希、集合等,以及一些高级功能,如发布/订阅、事务等。Redis的高速读写能力和丰富的功能使其成为互联网应用中常用的缓存数据库。在SSM框架中,我们可以使用Redis来缓存数据库查询结果、session数据等,以提高系统的读写性能和响应速度。 在整合开发中,SSM框架通常会负责处理用户请求和返回响应,通过Spring的IOC容器来管理和注入依赖的对象,而MyBatis则负责与数据库进行交互。我们可以通过配置文件来整合SSM框架和Redis,让它们协同工作。例如,我们可以在Spring的配置文件中配置MyBatis的数据源和Mapper接口,以及Redis的连接池和缓存配置;在Spring MVC的配置文件中配置控制器、视图解析器和拦截器等;同时,我们还可以使用Redis的API来进行缓存数据的读写操作。 总之,通过整合SSM框架和Redis,我们可以充分发挥它们各自的优势,构建高性能、可扩展的互联网应用程序。这种整合开发方式可以帮助我们简化开发流程、提高开发效率,并提供更好的用户体验。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值