Spring企业级程序设计 • 【第5章 Spring MVC快速入门】

全部章节   >>>>


本章目录

5.1 Spring MVC设计概述及其框架结构

5.1.1 Spring MVC介绍

5.1.1 Spring MVC优势

5.1.2  Spring MVC工作原理

5.1.3 手动搭建Spring MVC环境

5.1.4 实践练习

5.2 处理器映射器和适配器

5.2.1 配置处理器映射器和适配器

5.2.2   注解驱动

5.2.3   @RequestMapping注解

5.2.3 注解驱动

5.2.4 实践练习

5.3  Spring MVC简单类型数据绑定

5.3.1 基本数据类型绑定

5.3.2  POJO类型数据绑定

5.3.3 Json类型数据交互

5.3.4 实践练习

5.4 Spring MVC复杂类型数据绑定

5.4.1  List集合类型数据绑定

5.4.2  Set集合类型数据绑定

5.4.3  Map集合类型数据绑定

5.4.4 实践练习

总结


5.1 Spring MVC设计概述及其框架结构

5.1.1 Spring MVC介绍

 Spring MVC是目前最好的实现MVC设计模式的框架,是Spring框架的一个分支产品,以Spring IoC容器为基础,并利用容器的特性来简化它的配置。

Spring MVC相当于Spring的一个子模块,可以很好地和Spring结合起来进行开发,是Java Web开发者应该要掌握的框架。

5.1.1 Spring MVC优势

  • 清晰的角色划分
  • 分工明确
  • 无需继承框架特定API,可以使用命令对象直接作为业务对象。
  • 和Spring其他框架无缝集成
  • 可适配,通过HandlerAdapter可以支持任意的类作为处理器。
  • 可定制性,HandlerMapping、ViewResolver等能够非常简单的定制。
  • 功能强大的数据验证、格式化和绑定机制。
  • 利用Spring提供的Mock对象能够非常简单的进行Web层单元测试。
  • 本地化和主题的解析的支持,使我们更容易进行国际化和主题的切换。
  • 强大的JSP标签库,使JSP编写更容易。

5.1.2  Spring MVC工作原理

Spring MVC的设计是围绕DispatcherServlet展开的,DispatcherServlet负责将请求派发到特定的处理器。

5.1.3 手动搭建Spring MVC环境

示例:搭建SpringMVC开发环境 创建WEB工程。

添加相关jar。

在src目录下创建Spring MVC的核心配置文件springmvc.xml。

在web.xml配置文件中配置Spring MVC的DispatcherServlet前端控制器。

在WebContent目录下创建index.jsp文件。

发布程序启动WEB服务器访问。

<?xml version="1.0" encoding="UTF-8"?>
<beans  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
		xmlns="http://www.springframework.org/schema/beans" 
		xmlns:context="http://www.springframework.org/schema/context" 
		xmlns:aop="http://www.springframework.org/schema/aop" 
		xmlns:tx="http://www.springframework.org/schema/tx" 
		xmlns:mvc="http://www.springframework.org/schema/mvc" 
		xsi:schemaLocation="http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-4.2.xsd 
		http://www.springframework.org/schema/context 
		http://www.springframework.org/schema/context/spring-context-4.2.xsd 
		http://www.springframework.org/schema/aop 
		http://www.springframework.org/schema/aop/spring-aop-4.2.xsd 
		http://www.springframework.org/schema/tx 
		http://www.springframework.org/schema/tx/spring-tx-4.2.xsd 
		http://www.springframework.org/schema/mvc 
		http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd ">
	<!-- 此处输入内容 -->
</beans>
<!-- 配置前端控制器 -->
<servlet>
	<servlet-name>springmvc</servlet-name>
	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	<!-- 指定Spring MVC的核心配置文件 -->
	<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>
	<!-- 拦截所有以do结尾的请求 -->
	<url-pattern>*.do</url-pattern>
</servlet-mapping>

5.1.4 实践练习

 

5.2 处理器映射器和适配器

在Spring MVC中,处理器映射器和适配器这两个组件在Spring MVC整个的运行流程之中扮演一个很重要的角色。

映射器和适配器两个组件的功能:

  • 映射器主要是跟在浏览器上输入的URL来映射对应的Handle,具体的映射规则需要根据使用哪一个映射器来决定
  • 适配器主要是决定调用哪个Handler来实现具体的业务逻辑。

5.2.1 配置处理器映射器和适配器

示例:配置官方推荐的处理器映射器和适配器,在页面中输出结果。

<!-- 开启注解扫描功能 -->
<context:component-scan base-package="com.mhys.demo"></context:component-scan>
<!-- 配置处理器映射器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"></bean>
<!-- 配置处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"></bean>

@RequestMapping注解将url请求与业务方法进行映射。

ModelAndView对象的作用:设置转向地址和传递处理器中方法处理结果数据到结果页面。

5.2.2   <mvc:annotation-driven />注解驱动

手动配置处理器映射器和适配器比较麻烦,也不便于记忆。为了简化配置,官方提供了<mvc:annotation-driven />注解驱动标签来简化配置

此标签会自动注册RequestMappingHandlerMapping和RequestMappingHandlerAdapter两个Bean,当然还简化了其他的一些配置信息。

示例: 通过<mvc:annotation-driven />注解驱动标签来简化处理器映射器和适配器的配置。

5.2.3   @RequestMapping注解

Spring MVC通过@RequestMapping注解将url请求与业务方法进行映射。在Spring MVC框架中,@RequestMapping注解的使用频率很高,它可以添加在处理器类上以及方法上,在类定义处添加@RequestMapping注解,相当于多了一层访问路径。

@RequestMapping注解有三个常用的属性:

  • value:指定url请求的实际地址,是@RequestMapping的默认值,可省略不写。
  • method:指定请求的类型,get、post、put和delete等,常用get和post类型请求。
  • params:指定请求中必须包含某些参数值,否则无法调用该方法。

5.2.3 <mvc:annotation-driven />注解驱动

 示例:通过@RequestMapping完成GET和POST请求处理。

@Controller
@RequestMapping("/first")
public class RequestMappingController {
	@RequestMapping(value="/postTest",method=RequestMethod.GET)
	public ModelAndView testMethod(){
		ModelAndView model= new ModelAndView();
		model.addObject("method", "get请求成功!");
		model.setViewName("/WEB-INF/jsp/test.jsp");
		return model;
	}
}

@Controller
@RequestMapping("/first")
public class RequestMappingController {
	@RequestMapping(value="/postTest",method=RequestMethod.POST)
	public ModelAndView testMethod(){
		ModelAndView model= new ModelAndView();
		model.addObject("method", "get请求成功!");
		model.setViewName("/WEB-INF/jsp/test.jsp");
		return model;
	}
}

5.2.4 实践练习

 

5.3  Spring MVC简单类型数据绑定

在开发中,经常需要用到的是在业务方法中获取url中的参数和前端页面中的参数。这个时候需要了解Spring MVC的数据绑定。数据绑定就是在后台业务方法中,直接获取前端HTTP请求中的参数。

HTTP请求传输的参数都是String类型,但是Hanlder业务方法中的参数都是指定的数据类型,如int、Object等,所以需要处理参数的类型转换。

此项工作不需要开发人员去完成,Spring MVC的HandlerAdapter组件会在执行Handler业务方法之前完成参数的绑定。

5.3.1 基本数据类型绑定

示例:使用@RequestParam来接收基本数据类型参数。

@Controller
@RequestMapping("/method")
public class MethodController {
	@RequestMapping("/items")
	public String getParams(@RequestParam("ownerName") String ownerName,
		 @RequestParam("itemName") String itemName, @RequestParam("itemPrice")  String itemPrice){
		
		System.out.println("ownerName:" + ownerName);
		System.out.println("itemName:" + itemName);
		System.out.println("itemPrice:" + itemPrice);
		return "index.jsp";
	}
}
<body>
	<hr />
	<h1>添加古董信息</h1><br/>
	<form action="method/items.do" method="post">
		宝贝任务:<input type="text" name="ownerName"><br/><br/>
		宝贝名:<input type="text" name="itemName"><br/><br/>
		宝贝价格:<input type="text" name="itemPrice"><br/><br/>
		<input type="submit" value="添加">
	</form>
</body>

5.3.2  POJO类型数据绑定

示例:接收页面提交的参数实现对入参数据的封装。

//地址实体类
public class Address {
		private String addressId;
		private String addressName;
		// set()方法和get()方法省略
		@Override
		public String toString() {
			return "Address [addressId=" + addressId + ", addressName="
				+ addressName + "]";
		}
}
//用户实体类
public class User {
	private String username;
	private int age;
	private Address address;
	// set()方法和get()方法省略
		
	@Override
	public String toString() {
		return "User [username=" + username + ", age=" + age + ", address="
				+ address + "]";
	}
}
@Controller
@RequestMapping("/user")
public class UserController {
	@RequestMapping("/user")
		// 进入用户注册页面
	public ModelAndView intouser(User user){
		ModelAndView model = new ModelAndView();
		model.setViewName("/WEB-INF/jsp/user.jsp");
		return model;
	}
	@RequestMapping("/info")
	public String userInfo(User user){
		System.out.println(user);
		return null;
	}
}
<body>
	<form action="info.do" method="post">
		姓名:<input type="text" name="username"/><br/><br/>
		年龄:<input type="text" name="age"/><br/><br/>
		地址编号:<input type="text" name="address.addressId"/><br/><br/>
		地址:<input type="text" name="address.addressName"/><br/><br/>
	<input type="submit" value="提交"/>
	</form>
</body>

5.3.3 Json类型数据交互

在前后端交互中,经常碰见Ajax请求后端业务方法并将Json格式的参数传到后端的情况。如果需要Spring MVC支持Json,必须加入Json的处理jar包。添加jar包。

示例:将客户的账号和金额传到后端,然后将金额加100返回客户信息到前端。这里将使用@RequestBody注解和@ResponseBody注解来接收Json格式数据和返回Json格式数据。

@Controller
@RequestMapping("/customer")
public class CustomerController {
	@RequestMapping(value="/jsontest",method=RequestMethod.POST )
	@ResponseBody
	public Customer jsonTest(@RequestBody Customer customer ){
		System.out.println(customer.getCustomerId()+"------"+customer.getMoney());
		int money = customer.getMoney() + 100;
		customer.setMoney(money);
		return customer;
	}
	@RequestMapping("/json")
	@ResponseBody
		// 进入页面
	public ModelAndView intoJson(){
		ModelAndView model = new ModelAndView();
		model.setViewName("/WEB-INF/jsp/customer.jsp");
		return model;
	}
}
<script type="text/javascript" language="javascript">
	$(document).ready(function(){
		var customer = {"customerId":"584135","money":105};
		$("#json").click(function () {
			$.ajax({
				url:"<%=request.getContextPath() %>/customer/jsontest.do",
		        data:JSON.stringify(customer), // 将Json对象转换成Json字符串
		        contentType: "application/json;charset=UTF-8",
		        type:"post",
		        dataType:"json",
		        success:function(data){
		            alert(data.customerId+"---"+data.money);
		        }
			})
		}); 
	});
</script>

5.3.4 实践练习

 

5.4 Spring MVC复杂类型数据绑定

5.4.1  List集合类型数据绑定

示例:在前台页面注册多个员工的信息,后台通过List集合数据绑定来获取员工集合信息。

public class Employee {
	private String id;
	private String name;
	
	@Override
	public String toString() {
		return "Employee [id=" + id + ", name=" + name + "]";
	}
// set()方法和get()方法省略
}
@Controller
public class EmployeeController {
	@RequestMapping("/employeeList")
	@ResponseBody
	public String getEmployeeList(EmployeeList employeeList){
		StringBuffer sbf = new StringBuffer();
		for(Employee employee : employeeList.getEmployees()){
			sbf.append(employee);
		}
		return "员工:" + sbf.toString();
	}
}
<body>
	<form action="employeeList.do" method="post">
		员工1编号:<input type="text" name="employees[0].id"/>
		员工1姓名:<input type="text" name="employees[0].name"/><br/><br/>
		员工2编号:<input type="text" name="employees[1].id"/>
		员工2姓名:<input type="text" name="employees[1].name"/><br/><br/>
		员工3编号:<input type="text" name="employees[2].id"/>
		员工3姓名:<input type="text" name="employees[2].name"/><br/><br/>
		<input type="submit" value="List提交"/>
	</form>
</body>

5.4.2  Set集合类型数据绑定

示例:通过Set集合来完成员工信息集合的数据绑定。

public class EmployeeSet {
		private Set<Employee> employees = new HashSet<Employee>();

		public EmployeeSet() {
			employees.add(new Employee());
			employees.add(new Employee());
			employees.add(new Employee());
		}
		// set()方法和get()方法省略
}
@Controller
public class EmployeeController {
	// 原有代码省略
	@RequestMapping("/employeeSet")
	@ResponseBody
	public String getEmployeeSet(EmployeeSet employeeSet){
		StringBuffer sbf = new StringBuffer();
		for(Employee employee : employeeSet.getEmployees()){
			sbf.append(employee);
		}
		return "员工:" + sbf.toString();
	}
}
<body>
	<form action="employeeList.do" method="post">
		员工1编号:<input type="text" name="employees[0].id"/>
		员工1姓名:<input type="text" name="employees[0].name"/><br/><br/>
		员工2编号:<input type="text" name="employees[1].id"/>
		员工2姓名:<input type="text" name="employees[1].name"/><br/><br/>
		员工3编号:<input type="text" name="employees[2].id"/>
		员工3姓名:<input type="text" name="employees[2].name"/><br/><br/>
		<input type="submit" value="List提交"/>
	</form>
</body>

5.4.3  Map集合类型数据绑定

示例:通过Map集合来完成员工信息集合的数据绑定。

@Controller
public class EmployeeController {
	// 原有代码省略

	@RequestMapping("/employeeMap")
	@ResponseBody
	public String getEmployeeMap(EmployeeMap employeeMap){
		StringBuffer sbf = new StringBuffer();
		for(String key:employeeMap.getEmployees().keySet()){
	        		Employee employee = employeeMap.getEmployees().get(key);
	     		 sbf.append(employee);
	    	}
		return "员工:" + sbf.toString();
	}
}
<body>
	<form action="employeeMap.do" method="post">
		员工1编号:<input type="text" name="employees['a'].id"/>
		员工1姓名:<input type="text" name="employees['a'].name"/><br/><br/>
		员工2编号:<input type="text" name="employees['b'].id"/>
		员工2姓名:<input type="text" name="employees['b'].name"/><br/><br/>
		员工3编号:<input type="text" name="employees['c'].id"/>
		员工3姓名:<input type="text" name="employees['c'].name"/><br/><br/> 
		// 原有代码省略
		&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" value="Map提交"/>
	</form>
</body>

5.4.4 实践练习

 

总结

Spring MVC的主要组件:

  • DispatcherServlet前端控制器:作为前端控制器,整个流程控制的中心。
  • HandlerMapping处理器映射器:通过扩展处理器映射器实现不同的映射方式。
  • HandlAdapter处理器适配器:通过扩展处理器适配器,支持更多类型的处理器。
  • ViewResolver视图解析器:通过扩展视图解析器,支持更多类型的视图解析。

@RequestMapping:用于处理请求URL映射的注解,可用于类或方法上。

@RequestBody:注解实现接收HTTP请求的Json数据,将Json转换为java对象。

@ResponseBody:注解实现将Conreoller处理器类中方法返回对象转化为Json对象响应给客户。

posted @ 2021-05-25 11:20  明金同学  阅读(32)  评论(0编辑  收藏  举报