Spring框架——SpringMVC

SpringMVC

介绍

SpringMVC是基于请求驱动,围绕一个核心Servlet 转发请求到对应的Controller而设计的

  1. 客户端发出请求,交给DispatcherServlet处理
  2. DispatcherServlet根据请求信息及HandlerMapping的配置找到处理请求的处理器(Handler)
  3. DispatcherServlet通过HandlerAdapter对Handler进行封装,再以统一的适配器接口调用Handler
  4. 处理器完成业务逻辑,返回一个ModelAndVIewDispatcherServletModelAndView包含视图逻辑名和模型数据信息
  5. DispatcherServlet借由ViewResolver完成逻辑视图名到真实视图的解析工作
  6. 得到View真实视图后,DispatcherServlet就使用这个View对象对ModelAndView中的模型数据进行渲染
  7. 最终客户得到响应

SpringMVC使用

WEB-INF/web.xml配置文件

为了使结构划分,代码清晰。将配置分为两个xml

习惯性用法

  • applicationContext.xml 其他配置
  • (springname)-servlet.xml WEB(MVC)修改配置
  • listener 监听
	<!-- 上下文参数 -->
      <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                  classpath*:/applicationContext.xml
            </param-value>
      </context-param>
      <!--监听器-->
      <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
      </listener>

	<!-- 配置servlet -->
	<!-- 默认<servlet-name>-servlet.xml -->
      <servlet>
            <servlet-name>springmvc</servlet-name>      
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>                  
            <init-param>
                  <param-name>contextConfigLocation</param-name>
                  <param-value>/WEB-INF/spring-mvc.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
      </servlet>
      <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
      </servlet-mapping>

spring-mvc.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:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc 
	http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd 
	http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context-4.0.xsd">
	<!-- 自动扫描且只扫描@Controller -->
	<context:component-scan	base-package="com.cakeonline">
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

        <!--视图解析器-->
	<!-- 定义JSP文件的位置 -->
	<bean
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/" />
		<property name="suffix" value=".jsp" />
	</bean>
</beans>

视图解析器

软编码,实现类字符串到页面的映射。

前缀+返回值+后缀

applicationContext.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:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:jee="http://www.springframework.org/schema/jee"
	xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task"
	xmlns:p="http://www.springframework.org/schema/p"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
		http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.0.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">
	<description>Spring公共配置 </description>

	<!-- 配置Spring上下文的注解 -->
	<context:annotation-config />
	<!-- 自动扫描且只扫描@Controller以外的 -->
	<!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
	<context:component-scan base-package="com.cakeonline">
		<context:exclude-filter type="annotation"
			expression="org.springframework.stereotype.Controller" />
	</context:component-scan>
	
</beans>

Controller文件

@Controller

表示该类是个控制器
return 返回的是ViewResolver可解析前缀+后缀的页面

return "redirect:name";:跳转到另一个方法RequestMapping("/name")

@RestController

表示该类是个控制器
return "x" 返回的是json数据

@ResponseBody

用在方法上,表示直接将返回数据写在Http响应体里
RestController功能一致

@RequestMapping("/hello")

  • 在类上表该控制器中所有方法都是相对于该路径的,两级、多级路径**

    • @RequestMapping("/a");
    • @RequestMapping("/b");
    • 访问方式:a/b
  • 限制请求类型

    • @RequestMapping(value="/b",method=Request.GET);
    • 只能处理/b路径,且是Request.GET发来的请求
  • URI模板模式,获取请求参数的值

    • @RequestMapping(value="method/{id}")
    • method(@PathVariable int id){}
    • 传参变量
  • 路径模式

    • /a/b 精确
    • /a/*/c 一个模糊
    • /a/**/d 多个模糊 (可以没有)
    • /a/b? 精确模糊
  • 路径模式和URI混用

    • /a/*/

@RequestParam

请求参数绑定到方法参数
method(@RequestParam("a") int b)

  1. a:文本、超链接的字
  2. b:拿到的变量

@RequestParam(value="",required=true defaultValue="1")

  • required请求参数必须传
  • defaultValue 默认值

区别

  • @PathVariable
    • 页面请求路径的参数
  • @RequstParam
    • 传统传参方式?name=xx

@MatrixVariable

  • 矩阵变量
    -servlet.xml配置
  • 开启矩阵变量
    <mvc:annotation-driven enable-matrix-variables="true"/>
  • 使用

a/b/32;c=1;d=2
默认变量名字相同
@RequestMapping(value="/a/b/{id}",method=RequestMethod.GET)

(@PathVariable String id,@MatrixVariable int c,@MatrixVariable int d)

/a/40,m=1/b/20,m=2
自定义变量
@RequestMapping(value="/a/{id}/b/{pd}",method=RequestMethod.GET)

@MatrixVariable(value="m",pathVar="id") int id1,

@MatrixVariable(value="m",pathVar="pd") int id2

@CookieValue

在方法参数里写 @CookieValue("JSESSIONID")String id

@Controller

//@RestController
@RequestMapping("/cake")
public class CakeController {
	
	@RequestMapping("/list")
	@ResponseBody
	public String list(Model model, HttpServletRequest request) {
		List<Cake> list = new ArrayList<Cake>();
		Cake c1=new Cake();
		c1.setId(1);c1.setName("巧克力");
		Cake c2=new Cake();
		c2.setId(2);c2.setName("水果");
		list.add(c1);list.add(c2);
		
		model.addAttribute("cakes", list);
		
		return "list";
	}
	
	@RequestMapping(value="add", method=RequestMethod.GET)
	public String toAdd() {
		//数据库查询,查蛋糕类型,存入到request
		return "cake";
	}
	
	@RequestMapping(value="add", method=RequestMethod.POST)
	public String add() {
		//获取蛋糕的相关参数,插入数据库
		return "list";
	}
	
	@RequestMapping(value="edit", method=RequestMethod.GET)
	public String toEdit(@RequestParam("cakeid") int cakeId) {
		//根据蛋糕id,查询数据库,得到Cake
		return "cake";
	}
	
	@RequestMapping(value="edit", method=RequestMethod.POST)
	public String edit(Cake cake) {
		//把新的蛋糕数据存入数据库
		return "list";
	}
	
	@RequestMapping("/delete/{cakeId}")
	public String delete(@PathVariable int cakeId) {
		//删除
		return "list";
	}

}

每日英语

Dispatcher 调度员
Resolver 解决者
prefix 前缀
suffix 后缀

posted @ 2020-08-27 21:28  不爱学习的小策  阅读(206)  评论(0编辑  收藏  举报