springMVC 获取参数
1.servlet
@GetMapping("/params")
public String test5(HttpServletRequest request){
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println(username + " " + password);
return "test6";
}
2 通过控制器形参获取参数
@GetMapping("/params2")
public String test6(String username,String password){
System.out.println(username + " " + password);
return "test6";
}
3 RequestParam
@GetMapping("/params3")
public String test7(@RequestParam(value = "username" ,required = false,defaultValue = "jack") String username,String password){
System.out.println(username + " " + password);
return "test6";
}
4 RequestHeader
设置了defaultValue 没有值即为默认值
@GetMapping("/params3")
public String test7(
@RequestParam(value = "username" ,required = false,defaultValue = "jack") String username,String password
,@RequestHeader(value = "haha",defaultValue = "valuehaha") String host){
System.out.println(username + " " + password);
System.out.println("host:"+ host);
return "test6";
}
5 CookieValue
cookie的生命周期为浏览器关闭才结束
public String test5(HttpServletRequest request){ HttpSession session = request.getSession(); String username = request.getParameter("username"); String password = request.getParameter("password"); System.out.println(username + " " + password); return "test6"; }
@GetMapping("/params3")
public String test7(
@RequestParam(value = "username" ,required = false,defaultValue = "jack") String username,String password,
@RequestHeader(value = "haha",defaultValue = "valuehaha") String host,
@CookieValue("JSESSIONID") String cookie
){
System.out.println(username + " " + password);
System.out.println("host:"+ host);
System.out.println("cookie:" + cookie);
return "test6";
6 通过实体类型pojo获取参数
package com.cj.mvc.bean; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; public class User { private String username; private Integer age; private String sex; public User() { } public User(String username, Integer age, String sex) { this.username = username; this.age = age; this.sex = sex; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } @Override public String toString() { return "User{" + "username='" + username + '\'' + ", age=" + age + ", sex='" + sex + '\'' + '}'; } }
@RequestMapping("/testBean")
public String testBean(User user){
System.out.println(user);
return "test1";
}
解决乱码

浙公网安备 33010602011771号