SpringMVC学习笔记
4.1)通过ServletAPI获取
将HttpServletRequest作为控制器方法的形参,此时HttpServletRequest类型的参数表示封装了当前请求的请求报文的对象,代码如下:
@Controller
public class ParamController {
@RequestMapping("/testServletAPI")
//形参位置的request表示当前请求
public String testServletAPI(HttpServletRequest request){
HttpSession session = request.getSession();
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username:"+username+",password:"+password);
return "success";
}
}
新建 test_param.html ,代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>测试请求参数</title>
</head>
<body>
<h1>测试请求参数</h1>
<a th:href="@{/testServletAPI(username='admin',password=123456)}">1)测试使用servletAPI获取请求参数</a><br>
</body>
</html>
输出:【配置Tomacat后启动工程,浏览器访问:http://localhost:8080/SpringMvcDemo2/param 】页面如下:
点击链接1,页面跳转至:http://localhost:8080/SpringMvcDemo2/testServletAPI?username=admin&password=123456,页面如下:
控制台输出参数:
14:14:25.454 [http-nio-8080-exec-7] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/SpringMvcDemo2/testServletAPI?username=admin&password=123456", parameters={masked}
14:14:25.455 [http-nio-8080-exec-7] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to com.study.mvc.controller.ParamController#testServletAPI(HttpServletRequest)
username:admin,password:123456
14:14:25.514 [http-nio-8080-exec-7] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 200 OK
4.2)通过控制器方法的形参获取请求参数
在控制器方法的形参位置,设置和请求参数同名的形参,当浏览器发送请求,匹配到请求映射时,在DispatcherServlet中就会将请求参数赋值给相应的形参,代码如下:
@Controller
public class ParamController {
@RequestMapping("/testParam")
public String testParam(String username, String password, String[] hobby) {
//若请求参数中出现多个同名的请求参数,可以再控制器方法的形参位置设置字符串类型或字符串数组接收此请求参数
//若使用字符串类型的形参,最终结果为请求参数的每一个值之间使用逗号进行拼接
System.out.println("username:" + username + ",password:" + password + ",hobby:" + Arrays.toString(hobby));
return "success";
}
}
修改 test_param.html ,代码如下:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>测试请求参数</title>
</head>
<body>
<h1>测试请求参数</h1>
<a th:href="@{/testServletAPI(username='admin',password=123456)}">1)测试使用servletAPI获取请求参数</a><br>
<a th:href="@{/testParam(username='admin',password=123456)}">2)测试使用控制器的形参获取请求参数</a><br>
<form th:action="@{/testParam}" method="get">
用户名:<input type="text" name="user_name"><br>
密码:<input type="password" name="password"><br>
爱好:<input type="checkbox" name="hobby" value="a">a
<input type="checkbox" name="hobby" value="b">b
<input type="checkbox" name="hobby" value="c">c<br>
<input type="submit" value="测试使用控制器的形参获取请求参数">
</form>
</body>
</html>
输出:【配置Tomacat后启动工程,浏览器访问:http://localhost:8080/SpringMvcDemo2/param 】,输入相关信息,