Spring MVC扩展与SSM框架整合

发布于:2025-06-13 ⋅ 阅读:(21) ⋅ 点赞:(0)

Spring MVC是一种基于Java的Web框架,用于构建企业级应用程序。SSM(Spring + Spring MVC + MyBatis)框架将Spring、Spring MVC和MyBatis整合在一起,为开发者提供了一个高度灵活和强大的开发环境。本文将详细介绍如何扩展Spring MVC和整合SSM框架,步骤清晰易懂,并附有必要的代码示例和解释。

一、Spring MVC扩展

步骤1:配置Spring MVC

首先,需要在项目中配置Spring MVC,这通常包括web.xml文件中的配置和Spring MVC的核心配置文件。

web.xml:

<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_3_1.xsd" 
         version="3.1">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-config.xml</param-value>
    </context-param>

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

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring-mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>
​

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

    <context:component-scan base-package="com.example.controller"/>
    <mvc:annotation-driven/>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>
​

解释:
在 web.xml中配置了Spring的上下文和Spring MVC的DispatcherServlet。在 spring-mvc-config.xml中,设置了扫描控制器包、启用注解驱动和配置视图解析器。

步骤2:创建控制器

创建一个简单的控制器来处理请求。

package com.example.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloWorldController {

    @RequestMapping(value = "/hello", method = RequestMethod.GET)
    @ResponseBody
    public String sayHello() {
        return "Hello, Spring MVC!";
    }
}
​

解释:
HelloWorldController是一个简单的Spring MVC控制器,处理 /hello请求并返回一个字符串响应。

二、整合SSM框架

步骤1:配置Spring

首先配置Spring的核心配置文件(spring-config.xml)。

spring-config.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: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">

    <context:component-scan base-package="com.example"/>
    <context:property-placeholder location="classpath:database.properties"/>
    <bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="jdbcUrl" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="typeAliasesPackage" value="com.example.model"/>
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.example.mapper"/>
    </bean>

    <tx:annotation-driven/>
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>
​

解释:
在 spring-config.xml中,配置了数据源、MyBatis的SQL会话工厂和Mapper扫描器,并启用了事务管理。

步骤2:配置MyBatis

创建MyBatis的Mapper接口和映射文件。

UserMapper.java:

package com.example.mapper;

import com.example.model.User;
import org.apache.ibatis.annotations.Select;

public interface UserMapper {

    @Select("SELECT * FROM users WHERE id = #{id}")
    User getUserById(int id);
}
​

UserMapper.xml:

<mapper namespace="com.example.mapper.UserMapper">
    <select id="getUserById" parameterType="int" resultType="com.example.model.User">
        SELECT * FROM users WHERE id = #{id}
    </select>
</mapper>
​

解释:
UserMapper接口定义了一个查询方法,UserMapper.xml映射文件定义了对应的SQL查询。

步骤3:创建服务层

创建服务层以处理业务逻辑。

UserService.java:

package com.example.service;

import com.example.model.User;

public interface UserService {
    User getUserById(int id);
}
​

UserServiceImpl.java:

package com.example.service.impl;

import com.example.mapper.UserMapper;
import com.example.model.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    @Transactional
    public User getUserById(int id) {
        return userMapper.getUserById(id);
    }
}
​

解释:
UserService接口定义了业务方法,UserServiceImpl实现类使用 UserMapper执行数据库操作,并添加了事务支持。

步骤4:整合控制器

修改控制器以使用服务层。

package com.example.controller;

import com.example.model.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user", method = RequestMethod.GET)
    @ResponseBody
    public User getUser(int id) {
        return userService.getUserById(id);
    }
}
​

解释:
UserController使用 UserService获取用户信息,并返回给客户端。