如何理解spring框架中的MVC模块
- 是mvc设计思想的体现。
- 是对传统mvc应用的封装和简化。
springMVC模块的核心对象
- DispatcherServlet(核心控制器)
- HandlerMapping(映射器处理器)
- Interceptor(拦截器)
- Handler(Controller)后端处理器
- ViewResolve(视图解析器)
spring MVC应用的快速入门?
- 首先创建一个maven web项目(生成web.xml)
- 设置项目的运行时环境(间接添加servlet依赖)
- 添加spring-webmvc依赖,
- 添加spring-configs.xml
- 配置前端控制器(web.xml中)
- 编写后端处理器(Controller)以及视图(jsp)
- 部署项目,然后运行。
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>CGB-SPRING-MVC-01</display-name>
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<!-- Spring MVC的入口 -->
<init-param>
<!-- 与servlet里面的数据对应 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-configs.xml</param-value>
</init-param>
<!-- 配置tomcat启动时加载此servlet,数字越小,优先级越高 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
spring-configs.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans default-lazy-init="true"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-4.3.xsd
http://www.springframework.org/schema/data/jpa
http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd" >
<!-- 配置一个包扫描器,对指定包进行扫描 -->
<context:component-scan base-package="com.db"/>
<!-- 以注解驱动配置MVC 默认的Bean对象 (例如底层提供的类型转换器对象) -->
<mvc:annotation-driven/>
<!-- 用了这个标签后,系统底层会自动给你加一些<bean id="" class=""> -->
<!-- 配置视图解析器对象 -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
hollo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>springMVC测试页面</title>
</head>
<body>
<h1>${msg }</h1>
</body>
</html>
Controller.java
package com.db.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
/**
*
* 这个类要交给spring管理
*
* spring 中,描述bean对象的两种方式
* 1)xml:
* 2)注解: @Controller 要与<context:component-scan base-package="com.db"/>相结合
* 如上两种方式,都是告诉spring这是由spring管理的bean对象
*
*/
//用来告诉spring这是一个bean对象
//<bean id="" class="">
@Controller
@RequestMapping("/")
public class HelloController {
//当这个斜杠不写时要在类上面加
//@RequestMapping("doSayHello")
@RequestMapping("doSayHello")
public ModelAndView doSayHello() {
//可以将modelandview理解为一个值对象
ModelAndView mv = new ModelAndView();
// key value
mv.addObject("msg", "hello spring MVC");
mv.setViewName("hello");
return mv; //此值会返回给调用方法(Dispatch)加一个前缀Prefix的value发送给客户端
}//map.put(url,Method) 把这个方法封装成一个对象 系统底层做
@RequestMapping("doSayWelcome")
public String daSayWelcome(Model model) {
//数据会默认保存道请求作用域
model.addAttribute("msg","1234");
//把数据保存在msg的引用中,发送到hello的jsp界面
return "hello";
}
@RequestMapping("doIndexI")
public String doIndexUI(Model model) {
model.addAttribute("msg","12345");
return "index";
}
}
Spring MVC请求处理
1、请求url映射处理
传统方式:
@RequestMapping(value={"doPath01","path01"})
@ResponseBody
public String doPath01(){
return "request url mapping";
}
Rest风格:(简单)
@RequestMapping("doPath02/{a}")
@ReponseBody
public String doPath02(){
return "request rest url mapping";
}
2请求方式映射处理:
@RequestMapping("doPath01")
@ResponseBody
public String doPath01() {
return "request url mapping";
}
//处理get post请求
@RequestMapping(value="doMethod02",method= {RequestMethod.GET,RequestMethod.POST})
@ResponseBody
public String doMethod02() {
return "request method02";
}
@GetMapping("doMethod03")
@ResponseBody
public String doMethod03() {
return "request method02";
}
@PostMapping("doMethod04")
@ResponseBody
public String doMethod04() {
return "request method02";
}
//请求参数映射处理
@RequestMapping("doParam01")
@ResponseBody
public String doParam01() {
return "request url mapping";
}
@Controller
public class ResponseHandleController {
@RequestMapping("doRespURI01")
public String doRespURI01(){
return "response"; //转发
}
//重定向:返回值前需要添加redirect
@RequestMapping("doRespURI02")
public String doRespURI02(){
return "redirect:doRespURI01.do";
}
/**将响应数据转换为json格式的字符串*/
@RequestMapping("doRespJSON01")
public void doRespJSON01(HttpServletResponse resp)
throws IOException{
String s="{\"id\":1,\"name\":\"cgb1811\"}";
resp.getWriter().write(s);
}
/**
* 系统底层可以将map对象转换为JSON格式的字符串进行输出
* 1)添加jackson依赖(Spring MVC默认支持)
* 2)必须保证配置文件有<mvc:annotation-driven/>
* @return
*/
@RequestMapping("doRespJSON02")
@ResponseBody
public Map<String,Object> doRespJSON02(){
Map<String,Object> map=
new HashMap<>();
map.put("id", 10);
map.put("name","tmooc");
return map;
}
@RequestMapping("doRespJSON02")
@ResponseBody
public Map<String,Object> doRespJSON02(){
Map<String,Object> map=
new HashMap<>();
map.put("id", 10);
map.put("name","tmooc");
return map;
}
@RequestMapping("doRespJSON03")
public void doRespJSON03(
HttpServletResponse resp)
throws IOException{
Map<String,Object> map=
new HashMap<>();
map.put("id", 10);
map.put("name","tmooc");
//自己借助jackson api将map对象转换为json字符串
//1.构建转换器对象
ObjectMapper ow=new ObjectMapper();
//2.将对象转换为json串
String s=ow.writeValueAsString(map);
//3.将串写到客户端.
resp.getWriter().write(s);
}
@RequestMapping("doRespJSON04")
@ResponseBody
public List<Message> doRespJSON04(){
List<Message> list=new ArrayList<>();
Message msg=new Message();
msg.setId(1000);
msg.setTitle("TEDU");
list.add(msg);
msg=new Message();
msg.setId(2000);
msg.setTitle("TMOOC");
list.add(msg);
return list;
}//系统也是要借助response对象将数据输出到客户端