《SpringMVC视频教程》(p5)

p5 Rest风格

b.表单

    <form action="handler/testRest/1234" method="post">
        <input type="hidden"  name="_method" value="DELETE"/>
        <input type="submit" value="删">
    </form>
i:必须是post方式
ii:通过隐藏域 的value值 设置实际的请求方式 DELETE|PUT

c.控制器
    @RequestMapping(value="testRest/{id}",method=RequestMethod.DELETE)
        public String  testDelete(@PathVariable("id") Integer id) {
            System.out.println("delete:删 " +id);
            //Service层实现 真正的增
            return "success" ;//  views/success.jsp,默认使用了 请求转发的 跳转方式
        }
通过    method=RequestMethod.DELETE    匹配具体的请求方式

此外,可以发现 ,当映射名相同时@RequestMapping(value="testRest),可以通过method处理不同的请求。


过滤器中 处理put|delete请求的部分源码:
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        HttpServletRequest requestToUse = request;

        if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
            String paramValue = request.getParameter(this.methodParam);
            if (StringUtils.hasLength(paramValue)) {
                requestToUse = new HttpMethodRequestWrapper(request, paramValue);
            }
        }

        filterChain.doFilter(requestToUse, response);
    }
原始请求:request,改请求默认只支持get post  header
但是如果 是"POST"  并且有隐藏域        <input type="hidden"  name="_method" value="DELETE"/>
则,过滤器 将原始的请求 request加入新的请求方式DELETE,并将原始请求 转为 requestToUse 请求(request+Delete请求)
最后将requestToUse 放入 请求链中, 后续再事情request时  实际就使用改造后的 requestToUse

 

 

 

@RequestParam("uname") String name,@RequestParam(value="uage",required=false,defaultValue="23")

@RequestParam("uname"):接受前台传递的值,等价于request.getParameter("uname");

required=false:该属性 不是必须的。
defaultValue="23":默认值23

 

 

获取请求头信息 @RequestHeader
public String  testRequestHeader(@RequestHeader("Accept-Language")  String al  ) {
        
通过@RequestHeader("Accept-Language")  String al   获取请求头中的Accept-Language值,并将值保存再al变量中 

通过mvc获取cookie值(JSESSIONID)
@CookieValue 
(前置知识: 服务端在接受客户端第一次请求时,会给该客户端分配一个session (该session包含一个sessionId)),并且服务端会在第一次响应客户端时 ,请该sessionId赋值给JSESSIONID 并传递给客户端的cookie中

 

 

小结:
SpringMVC处理各种参数的流程/逻辑:
请求:  前端发请求a-> @RequestMappting("a") 
处理请求中的参数xyz:
    @RequestMappting("a") 
    public String  aa(@Xxx注解("xyz")  xyz)
    {

    }

使用对象(实体类Student)接受请求参数

在SpringMVC中使用原生态的Servlet API  :HttpServletRequest :直接将 servlet-api中的类、接口等 写在springMVC所映射的方法参数中即可:
        @RequestMapping(value="testServletAPI")
        public String testServletAPI(HttpServletRequest  request,HttpServletResponse response) {
//            request.getParameter("uname") ;
            System.out.println(request);
            return "success" ;
        }

Address.java

package org.lanqiao.entity;

public class Address {
	private String homeAddress ; 
	private String schoolAddress ;
	public String getHomeAddress() {
		return homeAddress;
	}
	public void setHomeAddress(String homeAddress) {
		this.homeAddress = homeAddress;
	}
	public String getSchoolAddress() {
		return schoolAddress;
	}
	public void setSchoolAddress(String schoolAddress) {
		this.schoolAddress = schoolAddress;
	}
	
}

Student.java

package org.lanqiao.entity;

public class Student {
	private int id;
	private String name;
	private Address address ;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	
}	

SpringMVCHandler.java

package org.lanqiao.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.lanqiao.entity.Address;
import org.lanqiao.entity.Student;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

//接口/类    注解   配置
@Controller
@RequestMapping(value="handler") //映射
public class SpringMVCHandler {
		@RequestMapping(value="welcome",method=RequestMethod.POST,params= {"name=zs","age!=23","!height"})//映射
		public String  welcome() {
			return "success" ;//  views/success.jsp,默认使用了 请求转发的 跳转方式
		}
		
		
		@RequestMapping(value="welcome2",headers= {"Accept=text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8","Accept-Encoding=gzip, deflate"})
		public String  welcome2() {
			return "success" ;//  views/success.jsp,默认使用了 请求转发的 跳转方式
		}
		
		
		@RequestMapping(value="welcome3/**/test")
		public String  welcome3() {
			return "success" ;//  views/success.jsp,默认使用了 请求转发的 跳转方式
		}
		@RequestMapping(value="welcome4/a?c/test")
		public String  welcome4() {
			return "success" ;//  views/success.jsp,默认使用了 请求转发的 跳转方式
		}
		@RequestMapping(value="welcome5/{name}")
		public String  welcome5(@PathVariable("name") String name ) {
			System.out.println(name);
			return "success" ;//  views/success.jsp,默认使用了 请求转发的 跳转方式
		}
		
		@RequestMapping(value="testRest/{id}",method=RequestMethod.POST)
		public String  testPost(@PathVariable("id") Integer id) {
			System.out.println("post:增 " +id);
			//Service层实现 真正的增
			return "success" ;//  views/success.jsp,默认使用了 请求转发的 跳转方式
		}
		
		@RequestMapping(value="testRest/{id}",method=RequestMethod.GET)
		public String  testGet(@PathVariable("id") Integer id) {
			System.out.println("get:查 " +id);
			//Service层实现 真正的增
			return "success" ;//  views/success.jsp,默认使用了 请求转发的 跳转方式
		}
		
		@RequestMapping(value="testRest/{id}",method=RequestMethod.DELETE)
		public String  testDelete(@PathVariable("id") Integer id) {
			System.out.println("delete:删 " +id);
			//Service层实现 真正的增
			return "success" ;//  views/success.jsp,默认使用了 请求转发的 跳转方式
		}
		
		@RequestMapping(value="testRest/{id}",method=RequestMethod.PUT)
		public String  testPut(@PathVariable("id") Integer id) {
			System.out.println("put:改 " +id);
			//Service层实现 真正的增
			return "success" ;//  views/success.jsp,默认使用了 请求转发的 跳转方式
		}
		
		@RequestMapping(value="testParam")
		public String  testParam(@RequestParam("uname") String name,@RequestParam(value="uage",required=false,defaultValue="23") Integer age) {
//			String name = request.getParameter("uname");
			
			System.out.println(name);
			System.out.println(age);
			return "success" ;//  views/success.jsp,默认使用了 请求转发的 跳转方式
		}
		
		@RequestMapping(value="testRequestHeader")
		public String  testRequestHeader(@RequestHeader("Accept-Language")  String al  ) {
			System.out.println( al);
			return "success" ;//  views/success.jsp,默认使用了 请求转发的 跳转方式
		}
		
	
		@RequestMapping(value="testCookieValue")
		public String  testCookieValue(@CookieValue("JSESSIONID") String jsessionId) {
			System.out.println( jsessionId);
			return "success" ;//  views/success.jsp,默认使用了 请求转发的 跳转方式
		}
		
		@RequestMapping(value="testObjectProperties")
		public String  testObjectProperties(Student student) {//student属性 必须 和 form表单中的属性Name值一致(支持级联属性)
		/*
			String name = 	request.getParameter("name");
		int age= Integer.parseInt(request.getParameter("age")s)	;
		String haddrss = 	request.getParameter("homeaddress");
		String saddress = 	request.getParameter("schooladdress");
		Address address = new Address();
		address.setHomeAddress(haddrss);
		address.setSchoolAddress(saddress);
		
			Student student = new Student();
			student.setName(name);
			student.setAddress(address);
		*/	
			System.out.println(student.getId()+","+student.getName()+","+student.getAddress().getHomeAddress()+","+student.getAddress().getSchoolAddress());
			return "success" ;
		}
		@RequestMapping(value="testServletAPI")
		public String testServletAPI(HttpServletRequest  request,HttpServletResponse response) {
//			request.getParameter("uname") ;
			System.out.println(request);
			return "success" ;
		}
		
		
		
		
}

springmvc.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:aop="http://www.springframework.org/schema/aop"
	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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
		http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

	<!-- 扫描 有注解的包 -->
	<context:component-scan base-package="org.lanqiao.handler"></context:component-scan>
	
	<!--配置视图解析器(InternalResourceViewResolver)  -->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/views/"></property>
		<property name="suffix" value=".jsp"></property>
	
	</bean>
	
	

</beans>

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isErrorPage="true"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
 	welcome to spring mvc
</body>
</html>

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" id="WebApp_ID" version="2.5">
  <display-name>SpringMVCProject</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
	<servlet>
	<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<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>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
  
  	<!-- 增加HiddenHttpMethodFilte过滤器:目的是给普通浏览器 增加 put|delete请求方式 -->
	<filter>
			<filter-name>HiddenHttpMethodFilte</filter-name>
			<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	
	<filter-mapping>
			<filter-name>HiddenHttpMethodFilte</filter-name>
			<url-pattern>/*</url-pattern>
	</filter-mapping>
  	
  	
  	
</web-app>

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

<!-- 如果web.xml中的配置是
	  <servlet-mapping>
  			<servlet-name>springDispatcherServlet</servlet-name>
  			<url-pattern>.action</url-pattern>
 	 </servlet-mapping>

	<a href="user/welcome.action">first springmvc - welcome</a>	交由springmvc处理 找 @RuestMapping映射
	<a href="user/welcome.action">first springmvc - welcome</a>交由springmvc处理  找 @RuestMapping映射
	<a href="xxx/welcome">first springmvc - welcome</a>			交由servlet处理  找url-parttern /@WebServlet()
 -->
	<a href="handler/welcome3/xyz/abcz/asb/test">33333333get - welcome</a>
	<br/>
	<a href="handler/welcome4/abc/test">4444444get - welcome</a>
		<br/>
	<a href="handler/welcome5/zs">555welcome</a>
	
	<form action="handler/welcome" method="post">
		name:<input name="name"  ><br/>
		age:<input name="age"  >
		height:<input name="height"  >
		<input type="submit" value="post">
	</form>
	
	<br/>======<br/>

	<form action="handler/testRest/1234" method="post">
		<input type="submit" value="增">
	</form>
	
	<form action="handler/testRest/1234" method="post">
		<input type="hidden"  name="_method" value="DELETE"/>
		<input type="submit" value="删">
	</form>
	
		<form action="handler/testRest/1234" method="post">
			<input type="hidden"  name="_method" value="PUT"/>
		<input type="submit" value="改">
	</form>
	
	<form action="handler/testRest/1234" method="get">
		<input type="submit" value="查">
	</form>
	------------<br/>
	<form action="handler/testParam" method="get">
		name:<input name="uname" type="text" />
		<input type="submit" value="查">
	</form>
	<br/>
	<a href="handler/testRequestHeader">testRequestHeader</a>
	<br/>
	<br/>
	<a href="handler/testCookieValue">testCookieValue</a><br/>
	<a href="handler/testServletAPI">testServletAPI</a>
	<br/>
	<form action="handler/testObjectProperties" method="post">
		id:<input name="id" type="text" />
		name:<input name="name" type="text" />
		家庭地址:<input name="address.homeAddress" type="text" />
		学校地址:<input name="address.schoolAddress" type="text" />
		<input type="submit" value="查">
	</form>
	
	
	
	
</body>
</html>

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值