SpringMVC第一篇----RequestMapping映射及各个属性

项目准备
  • 创建普通web项目,具体文档结构如下
    在这里插入图片描述
  • JAR准备

commons-logging.jar
spring-aop.jar
spring-beans.jar
spring-context.jar
spring-core.jar
spring-expression.jar
spring-web.jar
spring-webmvc.jar

  • 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>dome01</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.jsp</welcome-file>
    <welcome-file>default.htm</welcome-file>
  </welcome-file-list>
  
  <!-- The front controller of this Spring Web application, responsible for handling all application requests -->
  <!-- 配置servlet,利用DispatcherServlet将普通servlet交给springmvc处理 -->
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<!-- 利用DispatcherServlet类中的contextConfigLocation属性指定mvc.xml文件在类路径中的位置 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:springmvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map all requests to the DispatcherServlet for handling -->
	<!-- 配置servlet-mapping,选择拦截相应请求,"/"表示拦截所有请求 -->
	<servlet-mapping>
		<servlet-name>springDispatcherServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<!-- 配置过滤器,拦截请求并处理,将非GET,POST请求处理成相对性的请求,而GET,POST请求正常返回 -->
	<filter>
	   <filter-name>hiddenHttpMethodFilter</filter-name>
	   <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>
	<!-- 配置过滤器的拦截方式 -->
	<filter-mapping>
		<filter-name>hiddenHttpMethodFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>
  • 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="indi.dsl.controller"></context:component-scan>
  
  <!-- 配置视图解析器,拦截Controller层中要跳转的页面,进行简单的前缀和后缀处理 -->
  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     <property name="prefix" value="/views/"></property>
     <property name="suffix" value=".jsp"></property>
  </bean>
</beans>
  • 特别注意:
    1.mvc.xml配置文件位置可以利用springmvc提供的DispatcherServlet类中的contextConfigLocation属性,在类路径中进行指定;如果不指定就要配置contextConfigLocation属性,并且要将mvc.xml配置文件放在WEB_INF文件夹下,并且名字必须为xxx-servlet.xml。
    2.JDK的版本必须和tomcat的版本相互匹配,否则启动项目时会报load加载错误或者其他问题,本次是使用JDK-1.8和tomcat-8.5配合使用。
  • 创建Controller层:
package indi.dsl.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping(value = "handle")
public class SpringMVCController {
	// 指定请求方式,params指定参数传输的方式
	@RequestMapping(value = "welcome", method = RequestMethod.POST, params = { "name=zs", "age!=23", "!height" })
	public String name() {

		return "success";

	}

	// 锁定请求头中的某项信息,如果不是该请求头的内容是访问不成功的
	@RequestMapping(value = "welcome2", headers = {
			"Accept=text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8" })
	public String name2() {

		return "success";

	}

	// ant风格请求路径:单个*号,表示任意多个字符
	@RequestMapping(value = "welcome3/*/test")
	public String name3() {

		return "success";

	}

	// ant风格请求路径:两个*号,表示任意多个目录
	@RequestMapping(value = "welcome4/**/test")
	public String name4() {

		return "success";

	}

	// ant风格请求路径:问号?,表示单个字符
	@RequestMapping(value = "welcome5/a?c/test")
	public String name5() {

		return "success";

	}

	// ant风格请求路径:问号?,表示单个字符
	@RequestMapping(value = "welcome6/{name}")
	public String name6(@PathVariable("name") String name) {
		System.out.println(name);
		return "success";

	}
}

  • 创建index.jsp调用页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
     <a href="handle/welcome2">test02</a><br>
     <a href="handle/welcome3/adsf/test">test03</a><br>
     <a href="handle/welcome4/a/b/c/test">test04</a><br>
     <a href="handle/welcome5/adc/test">test05</a><br>
     <a href="handle/welcome6/zs">test06</a><br>
     <br>
     <form action="handle/welcome" method="post">
        name:<input name="name">
        age:<input name="age">
     	<input type="submit" value = "post">
     
     </form>
</body>
</html>

  • 创建success.jsp跳转页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isErrorPage="true" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
     hahaha!!!
</body>
</html>
RequestMapping用法
  • 在类前面配置@RequestMapping(value = “XXX”)属性,可以配置请求的主路径,此处为可选配置,如果配置,则请求需要有相应的主路径,例如: <a href="handle/XXXXX">test02</a>
  • 在方法前配置@RequestMapping(value = “XXX”)属性,可以配置请求中要调用的方法。
RequestMapping其他属性
  • 指定请求类型(GET、POST)
    例如:@RequestMapping(value = “welcome”, method = RequestMethod.POST),利用method 属性指定请求类型。

  • 配置请求参数
    例如:@RequestMapping(value = “welcome”, params = { “name=zs”, “age!=23”, “!height” }),利用params属性来配置参数或者参数的其他限定。

params = { “name=zs” },指定前端的的返回参数中必须带有“name”参数,并且name=zs;
params = { “age!=23” },指定前端的的返回参数中必须带有“age”参数,并且age的值不能等于23;
params = {"!height" },指定前端的的返回参数中不能包含height参数;
headers = {“XXXX” },指定请求的头信息必须为XXXX才可以进行调用。

ant风格的RequestMapping配置
  • 双星号表示任意多个目录,例如:@RequestMapping(value = “welcome4/**/test”)
  • 单个星号表示,表示任意多个字符,例如:@RequestMapping(value = “welcome3/*/test”)
  • 问号?,表示单个字符,例如:@RequestMapping(value = “welcome5/a?c/test”)
Restfule风格传参

前端请求中必须带有相应参数,Controller中配置RequestMapping属性时,需要将相应的参数接收,然后利用@PathVariable(“xxx”)在方法的参数位置接收相应参数,最后将参数赋给新建的变量值。

@RequestMapping(value = "welcome6/{name}")
	public String name6(@PathVariable("name") String name) {
		System.out.println(name);
		return "success";

	}
GET,POST,DELETE,PUT请求
  • 正常浏览器只是针对于GET和POST请求,对于DELETE,PUT请求会直接报出405错误,主要原因是tomcat-8.5以上的版本只允许发送GET和POST请求引起的,解决方法是在需要跳转到的页面头中加入isErrorPage="true"即可,例如:

<%@ page language=“java” contentType=“text/html; charset=UTF-8”
pageEncoding=“UTF-8” isErrorPage=“true” %>

  • 请求方式相对于数据库的相应操作,get–查找数据、post–增加数据、put–修改数据、delete–删除数据
  • 利用Restfule风格实现请求的发送与接收:
    1.针对于get和post请求正常处理即可,但是delete和put的请求必须在请求的页面中相应位置添加隐藏属性,并且外层method的发送方式依然为post,例如参照:
    <form action="handle/testResult/zs" method="post">
     	<input type="submit" value="">
     </form>
     <form action="handle/testResult/zs" method="post">
     	<input type="hidden" name="_method" value="DELETE">
     	<input type="submit" value="">
     </form>
     <form action="handle/testResult/zs" method="post">
     	<input type="hidden" name="_method" value="PUT">
     	<input type="submit" value="">
     </form>
     <form action="handle/testResult/zs" method="get">
     	<input type="submit" value="">
     </form>

2.过滤器HiddenHttpMethodFilter类中针对于delete和put的请求处理前提,必须为post请求,value属性为delete和put的请求中的一种,然后将请求重新转换为对应的delete和put的请求,具体源码如下:

@Override
	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);
	}

3.发送delete和put的请求的条件为:存在隐藏域type=“hidden”、存在name="_method"、存在value=“DELETE或者PUT”

<input type="hidden" name="_method" value="PUT">
使用RequestParam接收请求参数
  • 与Restfule风格接收请求参数类似,可以利用@RequestParam来接收参数,需要注意如果在@RequestParam中接收多个参数时,前端页面中必须存在相应参数,否则会报错,如果某个参数非必要存在可以利用required = false属性,关闭该参数的必传性,并且可以利用defaultValue赋上默认值,具体示例如下所示:
	@RequestMapping(value = "welcome7")
	public String name11(@RequestParam(value = "name") String name,
			@RequestParam(value = "age", required = false, defaultValue = "23") Integer age) {
		System.out.println("name:" + name + "-----age:" + age);
		return "success";

	}
<!-- 测试RequestParam属性 -->
     <form action="handle/welcome7">
     	name:<input name="name"><br>
     	<input type="submit" value="RequestParam">
     </form>
请求参数为对象处理方式
  • 当请求参数为对象时,在前端页面name的参数值名称必须为对象的实体类中的属性值名称,例如存在Studentt实体类中有属性StudentName,那么在前端页面处的name必须为name=“StudentName”,否则参数传输不通,如下所示:
<input name="StudentName" type="text">
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值