SpringMVC_处理模型数据之SessionAttributes

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/hoho_12/article/details/79832323

SpringMVCTest.java

package com.wxh.springmvc.handlers;

import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

import com.wxh.springmvc.entities.User;

@SessionAttributes(value={"user"},types={String.class})
@RequestMapping("/springmvc")
@Controller
public class SpringMVCTest {

	private static final String SUCCESS = "success";
	
	/**
	 * @SessionAttributes 除了可以通过属性名指定需要放到会话中的属性外(实际上使用的是 value 属性值),
	 * 还可以通过模型属性的对象类型指定哪些模型属性需要放到会话中(实际上使用的是 types 属性值)
	 * 
	 * 注意: 该注解只能放在类的上面. 而不能修饰放方法.
	 */	
	@RequestMapping("/testSessionAttributes")
	public String testSessionAttributes(Map<String,Object> map){
		User user = new User("tom", "1111", "[email protected]", "12");
		map.put("user", user);
		map.put("school","qinghua");
		return  SUCCESS;
	}
	
	
	/**
	 * 目标方法可以添加Map类型(实际上也可以是 Model 类型或 ModelMap 类型)的参数
	 * @param map
	 * @return
	 */
	@RequestMapping("/testMap")
	public String testMap(Map<String,Object> map){
		System.out.println(map.getClass().getName());
		map.put("names", Arrays.asList("Tom","Jerry","Mike"));		
		return SUCCESS;
	}
	
	/**
	 * 目标方法的返回值可以是ModelAndView类型。
	 * 其中可以包含视图和模型信息
	 * SpringMVC 会把ModelAndView 的model中的数据放入到request域对象中。
	 * @return
	 */
	@RequestMapping("/testModelAndView")
	public ModelAndView testModelAndView(){
		String viewName = SUCCESS;
		ModelAndView modelAndView = new ModelAndView(viewName);
		
		//添加模型数据到ModelAndView中。
		modelAndView.addObject("time", new Date());
		
		return modelAndView;
	}
	
	
	/**
	 * 可以使用 Serlvet 原生的 API 作为目标方法的参数 具体支持以下类型
	 * 
	 * HttpServletRequest 
	 * HttpServletResponse 
	 * HttpSession
	 * java.security.Principal 
	 * Locale InputStream 
	 * OutputStream 
	 * Reader 
	 * Writer
	 * @throws IOException 
	 */	
	@RequestMapping("/testServletAPI")
	public void testServletAPI(HttpServletRequest request,
			HttpServletResponse response, Writer out) throws IOException{
		System.out.println("testServletAPI, " + request + ", " + response);
		out.write("hello springmvc");
		//return SUCCESS;
	}
	
	/**
	 * Spring MVC会按照请求参数名和POJO属性名进行自动匹配
	 * 自动为该对象填充属性值,支持级联属性。
	 * 如:dept.deptId、dept.address.tel等 
	 */
	
	@RequestMapping("/testPojo")
	public String testPojo(User user){
		System.out.println("testPojo : "+ user);		
		return SUCCESS;
	}
	
	/**
	 * 了解:
	 * @CookieValue:映射一个Cookie 值,属性同@RequestParam
	 */
	@RequestMapping("/testCookieValue")
	public String testCookieValue(@CookieValue("JSESSIONID") String sessionId){
		System.out.println("testCookieValue: sessionId: " + sessionId);
		return SUCCESS;
	}
	
	/**
	 * 了解:
	 * 映射请求头信息 
	 * 用法同@RequestParam
	 * @return
	 */
	
	@RequestMapping("/testRequestHeader")
	public String testRequestHeader(@RequestHeader(value="Accept-Language") String al){
		System.out.println("testRequestHeader, Accept-Language: " + al);
		return SUCCESS;
	}
	
	/**
	 * 
	 * @RequestParam 来映射请求参数
	 * value 值即请求参数的参数名
	 * required 该参数是否必须,默认为true
	 * defaultValue 请求参数的默认值
	 */	
	@RequestMapping("/testRequestParam")
	public String testRequestParam(@RequestParam(value="username") String un,
			@RequestParam(value="age",required=false,defaultValue="0") int age){
		System.out.println("testRequestParam,username "+un+",age: "+age);		
		return SUCCESS;
	}
	
	/**
	 * Rest 风格的URL
	 * 以CRUD为例:
	 * 新增: /order POST  
	 * 修改:/order/1 PUT      update?id=1
	 * 获取:/order/1 GET      get?id=1
	 * 删除:/order/1 DELETE   delete?id=1
	 * 
	 * 如何发送 PUT 请求和DELETE 请求呢?
	 * 1.需要配置HiddenHttpMethodFilter
	 * 2.需要发送POST请求
	 * 3.需要在发送POST 请求时携带一个name="_method" de 隐藏域,值为DELETE 或 PUT
	 * 
	 * 在SpringMVC中的目标方法中如何得到id呢?
	 * 使用@PathVariable 注解
	 * 
	 * @param id
	 * @return
	 */
	
	
	@ResponseBody()//加上此注解解决405的问题
	@RequestMapping(value="/testRest/{id}",method=RequestMethod.PUT)
	public String testRestPut(@PathVariable Integer id){
		System.out.println("testRest PUT: "+id);
		return SUCCESS;
	}	
	
	@RequestMapping(value="/testRest/{id}",method=RequestMethod.DELETE)
	@ResponseBody()//加上此注解解决405的问题
	public String testRestDelete(@PathVariable Integer id){
		System.out.println("testRest Delete: "+id);
		return SUCCESS;
	}
	
	@RequestMapping(value="/testRest",method=RequestMethod.POST)
	public String testRest(){
		System.out.println("testRest POST ");
		return SUCCESS;
	}
	
	@RequestMapping(value="/testRest/{id}",method=RequestMethod.GET)
	public String testRest(@PathVariable Integer id){
		System.out.println("testRest GET: "+id);
		return SUCCESS;
	}
	
	/**
	 * @PathVariable 可以来映射URL中的占位符到目标方法的参数中。
	 * @param id
	 * @return
	 */
	@RequestMapping("/testPathVariable/{id}")
	public String testPathVariable(@PathVariable("id") Integer id){
		System.out.println("testPathVariable: "+ id);
		return SUCCESS;
	}
	
	
	@RequestMapping("/testAntPath/*/abc")
	public String testAndPath(){
		System.out.println("testAntPath");
		return SUCCESS;
	}
	
	/**
	 * 了解:可以使用params和 headers来更加精确的映射请求,params 和 headers支持简单的表达式
	 * @return
	 */	
	@RequestMapping(value="testParamsAndHeaders",
			params={"username","age!=10"}, headers={"Accept-Language=en-US,zh;q=0.8"})
	public String testParamsAndHeaders(){
		System.out.println("testParamsAndHeaders");
		return SUCCESS;
	}
	
	
	/**
	 * 常用:使用method 属性来指定请求方式  
	 * @return
	 */
	
	@RequestMapping(value="/testMethod",method=RequestMethod.POST)
	public String testMethod(){
		System.err.println("testMethod");
		return SUCCESS;
	}
	
	/**
	 * 1.@RequestMapping 除了修饰方法,还可来修饰类
	 * 2.
	 * 1).类定义处:提供初步的请求映射信息,相对于web应用的根目录
	 * 2).方法处:提供进一步的细分映射信息。
	 * 相对于类定义处的url。若类定义处未标注@RequestMapping。则方法处标记的url相对于web应用的根目录。
	 * @return
	 */
	
	@RequestMapping("/testRequestMapping")
	public String testRequestMapping(){
		System.out.println("testRequestMapping");
		return SUCCESS;
	}
	
}

index.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>

	<a href="springmvc/testSessionAttributes">Test SessionAttributes</a>
	<br><br>
	
	<a href="springmvc/testMap">Test Map</a>
	<br><br>
	
	<a href="springmvc/testModelAndView">Test ModelAndView</a>
	<br><br>
	
	<a href="springmvc/testServletAPI">Test ServletAPI</a>
	<br><br>
	
	<form action="springmvc/testPojo" method="post">
		username:<input type="text" name="username">
		<br>
		password:<input type="password" name="password">
		<br>
		email:<input type="text" name="email">
		<br>
		age:<input type="text" name="age">
		<br>		
		city:<input type="text" name="address.city">
		<br>
		province:<input type="text" name="address.province">
		<br>
		<input type="submit" name="Submit">
	</form>
	<br><br>
	
	
	<a href="springmvc/testCookieValue">Test CookieValue</a>
	<br><br>
	
	<a href="springmvc/testRequestHeader">Test RequestHeader</a>
	<br><br>
	
	<a href="springmvc/testRequestParam?username=wxh&age=11">Test RequestParam</a>
	<br><br>
	
	<!--put请求-->
	<form action="springmvc/testRest/1" method="post">
		<input type="hidden" name="_method" value="PUT">
		<input type="submit" value="TestRest PUT">
	</form>
	<br><br>
	
	<!--delete请求-->
	<form action="springmvc/testRest/1" method="post">
		<input type="hidden" name="_method" value="DELETE">
		<input type="submit" value="TestRest DELETE">
	</form>
	<br><br>
	
	<!-- post请求 -->
	<form action="springmvc/testRest" method="post">
		<input type="submit" value="TestRest POST">
	</form>
	<br><br>
	<!-- get请求 -->
	<a href="springmvc/testRest/1">Test Rest Get</a>
	<br><br>	
	
	<a href="springmvc/testPathVariable/1">Test PathVariable</a>
	<br><br>	
	
	<a href="springmvc/testAntPath/aa/abc">Test AntPath</a>
	<br><br>
	
	<a href="springmvc/testParamsAndHeaders?username=wxh&age=10">Test TestParamsAndHeaders</a>
	<br><br>

	<!--post请求-->
	<form action="springmvc/testMethod" method="post">
		<input type="submit" value="submit">
	</form>

	<!-- get请求 -->
	<br><br>
	<a href="springmvc/testMethod">Test Method</a>
	
	<br><br>
	<a href="springmvc/testRequestMapping">Test RequestMapping</a>
	
	<br><br>
	<a href="helloworld">Hello world</a>

</body>
</html>

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h4>success</h4>
	
	time: ${requestScope.time }
	<br><br>
	
	names: ${requestScope.names }
	<br><br>
	
	request user: ${requestScope.user }
	<br><br>
	
	session user: ${sessionScope.user }
	<br><br>
	
	request school: ${requestScope.school }
	<br><br>
	
	session school: ${sessionScope.school }
	<br><br>
</body>
</html>

User.java

package com.wxh.springmvc.entities;

public class User {
	private String username;
	private String password;
	
	private String email;
	private String age;
	
	private Address address;
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}
	public String getAge() {
		return age;
	}
	public void setAge(String age) {
		this.age = age;
	}
	public Address getAddress() {
		return address;
	}
	public void setAddress(Address address) {
		this.address = address;
	}
	
	@Override
	public String toString() {
		return "User [username=" + username + ", password=" + password + ", email=" + email + ", age=" + age
				+ ", address=" + address + "]";
	}
	public User(String username, String password, String email, String age) {
		super();
		this.username = username;
		this.password = password;
		this.email = email;
		this.age = age;
	}
	
	public User(){
		
	}
	
}

猜你喜欢

转载自blog.csdn.net/hoho_12/article/details/79832323
今日推荐