其实开发Spring MVC流程并不困难。开发Spring MVC程序,需要掌握Spring MVC的组件和流程,所以在开发过程中也会贯穿着Spring MVC的运行流程。
如果不清楚Spring MVC的运行流程,
在目前的开发过程中,大部分都会采用注解的开发方式,主要是以一个注解@Controller标注,一般只需要通过扫描配置,就能够将其扫描出来,只是往往还要结合注解@RequestMapping去配置它。@RequestMapping可以配置在类和方法之上,它的作用是指定URI和哪个类(或者方法)作为一个处理请求的处理器,为了更加灵活,Spring MVC还定义了处理器的拦截器,当启动Spring MVC的时候,Spring MVC就会去解析@Controller中的@RequestMapping的配置,再结合所配置的拦截器,这样它就会组成多个拦截器和一个控制器得形式,存放到一个HandlerMapping中去。当请求来到服务器,首先是通过请求信息找到对应的HandlerMapping,进而可以找到对应的拦截器和处理器,这样就能够运行对应的控制器和拦截器。
配置@RequestMapping
@RequestMapping(value = "/getRole",method= RequestMethod.GET)
public ModelAndView getRole(@RequestParam("id") Long id){
Role role=roleService.getRole(id);
ModelAndView mv=new ModelAndView();
mv.addObject("role",role);
//指定视图类型
mv.setViewName("roleDetails");
return mv;
}
一般配置@RequestMapping最常用到的是请求路径和请求类型,其他的大部分作为限定项,根据需要进行配置。
控制器的开发
控制器开发是Spring MVC的核心内容,其步骤一般分为三步:
- 获取请求参数。
- 处理业务逻辑。
- 绑定模型和视图。
获取请求参数:
在Spring MVC中接收参数的方法很多,比如如果要获取一个HTTP请求的参数——id,它是一个长整型,那么可以使用注解@RequestParam来获取它。
public ModelAndView getRole(@RequestParam("id") Long id)
通过@RequestParam注解,Spring MVC 就知道从HTTP请求中获取参数,即使用类似于如下的逻辑进行转换:
String idStr=request.getParameter("id");
Long id=Long.parseLong(idStr);
下面我用一个简单的实例来展示一下Spring MVC开发流程以及参数的获取。
实例文件框架:
RoleController.java
package com.ssm.example1.controller;
import com.ssm.example1.pojo.Role;
import com.ssm.example1.service.RoleService;
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.RequestParam;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/role")
public class RoleController {
//注入角色服务类
@Autowired
private RoleService roleService=null;
@RequestMapping(value = "/getRole",method= RequestMethod.GET)
public ModelAndView getRole(@RequestParam("id") Long id){
Role role=roleService.getRole(id);
ModelAndView mv=new ModelAndView();
mv.addObject("role",role);
//指定视图类型
mv.setViewName("roleDetails");
return mv;
}
}
RoleMapper.java
package com.ssm.example1.mapper;
import com.ssm.example1.pojo.Role;
import org.springframework.stereotype.Repository;
@Repository
public interface RoleMapper {
public int insertRole(Role role);
public Role getRole(Long id);
}
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>
<mappers>
<mapper resource="com/ssm/example1/sqlMapper/RoleMapper.xml" />
</mappers>
</configuration>
Role.java
package com.ssm.example1.pojo;
public class Role {
private Long id;
private String roleName;
private String note;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getRoleName() {
return roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public Role(){}
}
RoleService.java
package com.ssm.example1.service;
import com.ssm.example1.pojo.Role;
public interface RoleService {
public int insertRole(Role role);
public Role getRole(Long id);
}
RoleServiceImpl.java
package com.ssm.example1.service.impl;
import com.ssm.example1.mapper.RoleMapper;
import com.ssm.example1.pojo.Role;
import com.ssm.example1.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
@Service
public class RoleServiceImpl implements RoleService {
@Autowired
private RoleMapper roleMapper=null;
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW,isolation = Isolation.READ_COMMITTED)
public int insertRole(Role role) {
return roleMapper.insertRole(role);
}
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW,isolation = Isolation.READ_COMMITTED)
public Role getRole(Long id) {
return roleMapper.getRole(id);
}
}
RoleMapper.xml
<?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="com.ssm.example1.mapper.RoleMapper">
<resultMap id="roleMap" type="com.ssm.example1.pojo.Role">
<id property="id" column="id" />
<result property="roleName" column="role_name" />
<result property="note" column="note" />
</resultMap>
<insert id="insertRole" parameterType="com.ssm.example1.pojo.Role">
insert into role(role_name,note) values (#{roleName},#{note})
</insert>
<select id="getRole" resultMap="roleMap">
select id,role_name,note from role where id=#{id}
</select>
</mapper>
roleDetails.jsp
<%--
Created by IntelliJ IDEA.
User: win
Date: 2020/4/26
Time: 14:52
To change this template use File | Settings | File Templates.
--%>
<%@ page pageEncoding="gbk" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>out标签的使用</title>
</head>
<body>
</body>
<center>
<table border="1">
<tr>
<td>
标签
</td>
<td>
值
</td>
</tr>
<tr>
<td>
角色编号
</td>
<td>
<c:out value="${role.id}"></c:out>
</td>
</tr>
<tr>
<td>
角色名称
</td>
<td>
<c:out value="${role.roleName}"></c:out>
</td>
</tr>
<tr>
<td>
角色备注
</td>
<td>
<c:out value="${role.note}"></c:out>
</td>
</tr>
</table>
</center>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<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">
<!-- 配置Spring IoC配置文件路径-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<!-- 配置ContextLoaderListener用以初始化Spring IoC容器-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--配置DispatcherServlet -->
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<!-- Servlet 拦截配置-->
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
applicationContext
<?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"
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">
<!-- 使用注解驱动-->
<context:annotation-config />
<!-- 数据库连接池-->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/ssm" />
<property name="username" value="root" />
<property name="password" value="123456" />
<property name="maxActive" value="255" />
<property name="minIdle" value="5" />
<property name="maxIdle" value="10000" />
</bean>
<!--集成mybaties -->
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:com/ssm/example1/mybatis/mybatis-config.xml" />
</bean>
<!-- 配置数据源事务管理器-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 采用自动扫描方式创建mapper bean-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.example1" />
<property name="sqlSessionFactory" ref="SqlSessionFactory" />
<property name="annotationClass" value="org.springframework.stereotype.Repository" />
</bean>
</beans>
dispatcher-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:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.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">
<!-- 使用注解驱动-->
<mvc:annotation-driven />
<!-- 定义扫描装载的包-->
<context:component-scan base-package="com.*" />
<!-- 定义视图解析器-->
<!-- 找到Web工程/WEB-INF/JSP文件夹,且文件结尾为jsp的文件作为映射-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
</beans>
然后通过tomcat运行,输入网址:http://localhost:8080/role/getRole.do?id=1
运行结果