1.获取Request response对象
在SpringMVC的注解开发中,可以选择性的接收Request和Response对象来使用
2.获取request对象请求参数
a.通过request对象获取
通过request对象获取请求参数时,类型不一致时需要手动转换。int age = Integer.parseInt(request.getParameter("age"));
/** * 获取request 和 response */ @RequestMapping("/hello3.action") public String hello3(HttpServletRequest request, HttpServletResponse response, Model model){ String username = request.getParameter("username"); int age = Integer.parseInt(request.getParameter("age")); // 获取某个请求头信息 String al = request.getHeader("Accept-Language"); System.out.println(al); System.out.println(username + "~~" + age); model.addAttribute("msg","hello springmvc~"); return "hello"; }
访问:http://localhost/SpringMVC2/hello3.action?username=cjj&age=18
b.直接接收请求参数
可以在Controller方法中直接接收请求参数相同否认方法形参,可以直接得到请求参数的值。
WebRoot目录下创建一个from表单
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <body> <form action="${pageContext.request.contextPath}/hello4.action" method="POST"> <table> <tr> <td>用户名</td> <td><input type="text" name="username"/></td> </tr> <tr> <td>密码</td> <td><input type="text" name="password"/></td> </tr> <tr> <td>年龄</td> <td><input type="text" name="age"/></td> </tr> <tr> <td colspan="2"><input type="submit" value="提交"/></td> </tr> </table> </form> </body> </html>