Spring MVC 保存並獲取屬性參數


  在開發控制器的時候,有時也需要保存對應的數據到這些對象中去,或者從中獲取數據。而Spring MVC給予了支持,它的主要注解有3個:@RequestAttribute、@SessionAttribute和@SessionAttributes,它們的作用如下。
  •@RequestAttribute獲取HTTP的請求(request)對象屬性值,用來傳遞給控制器的參數。
  •@SessionAttribute在HTTP的會話(Session)對象屬性值中,用來傳遞給控制器的參數。
  •@SessionAttributes,可以給它配置一個字符串數組,這個數組對應的是數據模型對應的鍵值對,然后將這些鍵值對保存到Session中。

注解@RequestAttribute

  @RequestAttribute主要的作用是從HTTP的request對象中取出請求屬性,只是它的范圍周期是在一次請求中存在
  代碼清單15-23:請求屬性 requestAttribute.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>

<%
    //設置請求屬性
    request.setAttribute("id", 111L);
    //轉發給控制器
    request.getRequestDispatcher("../attribute/requestAttribute.do").forward(request, response);
%>

</body>


</html>

 

  代碼清單15-24:控制器獲取請求屬性

package com.ssm.chapter15.controller;

import com.ssm.chapter15.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

@Controller
@RequestMapping("/attribute")
public class AttributeController {

    // @Autowired
    // private RoleService roleService;

    @RequestMapping("/requestAttribute")
    public ModelAndView reqAttr(@RequestAttribute(value = "id", required = false) Long id) {
        System.out.println("id =>" + id);
        ModelAndView mv = new ModelAndView();
        // Role role = roleService.getRole(id);
        // mv.addObject("role", role);
        mv.addObject("role", id);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }

}

 

注解@SessionAttribute和注解@SessionAttributes

  這兩個注解和HTTP的會話對象有關,在瀏覽器和服務器保持聯系的時候HTTP會創建一個會話對象,這樣可以讓我們在和服務器會話期間(請注意這個時間范圍)通過它讀/寫會話對象的屬性,緩存一定數據信息。
  先來討論一下設置會話屬性,在控制器中可以使用注解@SessionAttributes來設置對應的鍵值對,不過這個注解只能對類進行標注,不能對方法或者參數注解。它可以配置屬性名稱或者屬性類型。它的作用是當這個類被注解后,Spring MVC執行完控制器的邏輯后,將數據模型中對應的屬性名稱或者屬性類型保存到HTTP的Session對象中。

  代碼清單15-25:使用注解@SessionAttributes

package com.ssm.chapter15.controller;

import com.ssm.chapter15.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

@Controller
@RequestMapping("/attribute")
//可以配置數據模型的名稱和類型,兩者取或關系
@SessionAttributes(names = {"id"}, types = {Role.class})
public class AttributeController {

    @RequestMapping("/sessionAttributes")
    public ModelAndView sessionAttrs(Long id) {
        ModelAndView mv = new ModelAndView();
        // Role role = roleService.getRole(id);
        Role role = new Role(id, "射手", "遠程物理輸出");
        //根據類型,Session將會保存角色信息
        mv.addObject("role", role);
        // 根據名稱,Session將會保存id
        mv.addObject("id", id);
        //視圖名稱,定義跳轉到一個JSP文件上
        mv.setViewName("sessionAttribute");
        return mv;
    }

}

 

  代碼清單15-26:sessionAttribute.jsp驗證注解有效性

<%@ page language="java" import="com.ssm.chapter15.pojo.Role" 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>

<%
    Role role = (Role) session.getAttribute("role");
    out.println("id = " + role.getId() + "<p/>");
    out.println("roleName = " + role.getRoleName() + "<p/>");
    out.println("note = " + role.getNote() + "<p/>");
    Long id = (Long) session.getAttribute("id");
    out.println("id = " + id + "<p/>");
%>

</body>
</html>

 

  讀取Session的屬性,Spring MVC通過@SessionAttribute實現。
  代碼清單15-27:JSP設置Session屬性 sessionAttribute.jsp

<%@ page language="java" import="com.ssm.chapter15.pojo.Role" 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>

<%
    Role role = (Role) session.getAttribute("role");
    out.println("id = " + role.getId() + "<p/>");
    out.println("roleName = " + role.getRoleName() + "<p/>");
    out.println("note = " + role.getNote() + "<p/>");
    Long id = (Long) session.getAttribute("id");
    out.println("id = " + id + "<p/>");
%>

</body>
</html>

 

  代碼清單15-28:獲取Session屬性

package com.ssm.chapter15.controller;

import com.ssm.chapter15.pojo.Role;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttribute;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

@Controller
@RequestMapping("/attribute")
//可以配置數據模型的名稱和類型,兩者取或關系
@SessionAttributes(names = {"id"}, types = {Role.class})
public class AttributeController {

    @RequestMapping("/sessionAttribute")
    public ModelAndView sessionAttr(@SessionAttribute("id") Long id) {
        System.out.println("id =>" + id);
        ModelAndView mv = new ModelAndView();
        // Role role = roleService.getRole(id);
        Role role = new Role(id, "射手", "遠程物理輸出");
        mv.addObject("role", role);
        mv.setView(new MappingJackson2JsonView());
        return mv;
    }

}

 

注解@CookieValue和注解@RequestHeader

  從名稱而言,這兩個注解都很明確,就是從Cookie和HTTP請求頭獲取對應的請求信息,它們的用法比較簡單,且大同小異,所以放到一起講解。只是對於Cookie而言,用戶是可以禁用的,所以在使用的時候需要考慮這個問題。下面給出它們的一個實例,如代碼清單15-29所示。
  代碼清單15-29:使用@CookieValue和@RequestHeader

package com.ssm.chapter15.controller;

import com.ssm.chapter15.pojo.Role;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;

@Controller
@RequestMapping("/cookie")
public class CooKieController {

    @RequestMapping("/getHeaderAndCookie")
    public String testHeaderAndCookie(@RequestHeader(value = "User-Agent", required = false, defaultValue = "attribute") String userAgent
            , @CookieValue(value = "JSESSIONID", required = true, defaultValue = "MyJsessionId") String jsessionId) {
        System.out.println("User-Agent:" + userAgent);
        System.out.println("JSESSIONID:" + jsessionId);
        return "index";
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM