说明:本文章的内容转载至:https://my.oschina.net/happyBKs/blog/420271 如有侵权的地方,请联系本人,本人将会立即删除!
MVC 的 Handler 方法可以接受哪些 ServletAPI 类型的参数?
HttpServletRequest HttpServletResponse HttpSession java.security.Principal Locale InputStream OutputStream Reader Writer这些参数类型就不解释来了,请不知道的小白白们去查一下JSP&Servlet文档吧。
SpringMVC的强大之处在于,它的AnnotationMethodHandlerAdapter能够将方法参数依次与各个上述类型进行比较,映射相应的类型参数。所以,我们可以在编写处理器方法的参数列表时自己定义,springMVC会请求的相应参数对象赋给它们。
这里的例子:
package com.happyBKs.springmvc.handlers; import java.io.IOException; import java.io.Writer; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @RequestMapping("/servlet") @Controller public class NativeServletHandler { @RequestMapping("/handle1") String handle1(HttpServletRequest request, HttpServletResponse response) { System.out.println("request:"+request+", response:"+response); return "successrm"; } @RequestMapping("/handle2") void handle2(HttpServletRequest request, Writer writer) throws IOException { writer.write("hello! happyBKs!"); } }请求页面:
<%@ 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>Insert title here</title> </head> <body> <a href="servlet/handle1">/servlet/handle1</a> <br/> <a href="servlet/handle2">/servlet/handle2</a> </body> </html>过程运行:
第一个请求:
控制台输出: request:org.apache.catalina.connector.RequestFacade@16aa1e07, response:org.apache.catalina.connector.ResponseFacade@7a996930第二个请求: