其實開發Spring MVC流程並不困難。開發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
運行結果