SpringMVC学习(2):使用@RequestMapping映射请求方式

来源:互联网 发布:sm4算法介绍 编辑:程序博客网 时间:2024/06/01 22:06

在上一篇文章中其实已经使用了@RequestMapping修饰类

@RequestMapping除了可以修饰方法,还可以修饰类,类方法的路径是相对于类的,如果类没有配置路径,那么类方法的路径就是相对于目录的。

这一篇文章讲一下使用@RequestMapping映射请求参数

一、使用@RequestMapping映射请求方法

在@RequestMapping中可以使用method定义请求方法,例如上篇文章讲的HelloWorld中其实就可以将HelloWorld.java写成这样

package springmvc;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;@Controller@RequestMapping("/springmvc")public class HelloWorld {private static final String SUCCESS = "success";@RequestMapping(value="/helloworld", method=RequestMethod.GET)public String helloWorld() {System.out.println("hello world");return SUCCESS;}}
接下来试试POST方法,为了方便起见,我直接修改原有的HelloWorld程序了。

先在index.jsp中添加一个表单

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%><!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=ISO-8859-1"><title>SpringMVC</title></head><body><form action="springmvc/testPostMethod" method="post"><input type="submit" value="submit"/></form></body></html>
将HelloWorld.java写成这样:

package springmvc;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.validation.BindingResult;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;@Controller@RequestMapping("/springmvc")public class HelloWorld {private static final String SUCCESS = "success";@RequestMapping(value="/testPostMethod", method=RequestMethod.POST)public String testPostMethod() {System.out.println("testPostMethod...");return SUCCESS;}}
运行起来效果是这样的:


 

二、使用Ant风格匹配URL

Ant风格资源地址支持3种匹配符:

?:匹配文件名中的一个字符

*:匹配文件名的任意字符

**:匹配多层路径

修改一下HelloWorld.java:

package springmvc;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping("/springmvc")public class HelloWorld {private static final String SUCCESS = "success";@RequestMapping("/testAntPath/*/abc")public String testAntPath() {System.out.println("testAndPath");return SUCCESS;}}
然后改一下jsp测试一下:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%><!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=ISO-8859-1"><title>SpringMVC</title></head><body><a href="springmvc/testAntPath/mnxyz/abc">Test AntPath</a></body></html>
可以发现,把<a>标签的href属性中的mnxyz改成别的字符串也可以成功映射回testAntPath()这个函数




0 0