注解 @RequestParam,@RequestHeader,@CookieValue,Pojo,servlet原生A

时间:2021-11-27 04:51:11

 我们的超链接:<a href="http://www.mamicode.com/springMvc/testRequestParam">testRequestParam</a><br/> 

/**
*
* @param username
* @param age
* @return
* 1.没有加required=false,
* 这样访问会报错,如果加了的话,数据类型是int,必须加defaultValue="0"
* 否则也会报错,要么将数据类型改为Integer
*/
@RequestMapping(value="/testRequestParam")
public String testRequestParam(@RequestParam(value="username") String username,
@RequestParam(value="age",required=false,defaultValue="0") int age){
System.out.println("testRequestParam,"+"username: "+username
+" age"+age);

return SUCCESS;
}

2.@RequestHeader

我们的超链接:<a href="http://www.mamicode.com/springMvc/testRequestHeader">testRequestHeader</a><br/>

我们header的值可以是 请求头中的任何一个

@RequestMapping("/testRequestHeader")
public String testRequestHeader(@RequestHeader(value="Accept-Encoding") String str){
System.out.println("testRequestHeader()..."+str);
return SUCCESS;
}

3.@CookieValue

 我们的超链接:<a href="http://www.mamicode.com/springMvc/testCookieValue">testCookieValue</a><br/>

@RequestMapping("/testCookieValue")
public String testCookieValue(@CookieValue(value="JSESSIONID" ) String sessionId){
System.out.println("testCookieValue().... "+sessionId);

return SUCCESS;
}

4.Pojo 

我们建两个类,一个User ,Address,并生成get,,set方法,并生成tostring方法

public class User {
private String username;
private String password;
private String email;
private int age;
private Address address;

.......

}

public class Address {
private String province;
private String city;

.....

}

我们的表单是:

<form action="springMvc/testPojo" method="post">
username:<input type="text"><br>
password:<input type="password"><br>
email:<input type="text"><br>
age:<input type="text"><br>
province:<input type="text"><br>
city: <input type="text"><br>

<input type="submit" value="Summit">
</form>

对应的代码:

@RequestMapping("/testPojo")
public String testPojo(User user){
System.out.println(user);
return SUCCESS;
}

                                   

5.servlet原生API

@RequestMapping("/testServlet")
public void testServlet(HttpServletRequest request,HttpServletResponse
response ,Writer out) throws IOException{
System.out.println("testServlet :"+request+": "+response);
out.write("testServlet()...");

}

我们的超链接:<a href="http://www.mamicode.com/springMvc/testServlet">testServlet</a><br/>

注解 @RequestParam,@RequestHeader,@CookieValue,Pojo,servlet原生API