您好,登錄后才能下訂單哦!
session如何在SpringMVC項(xiàng)目中使用?很多新手對此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。
session保存方式:
1、javaWeb工程通用的HttpSession
2、SpringMVC特有的@SessionAttributes
我個(gè)人比較關(guān)注@SessionAttributes的用法,畢竟現(xiàn)在是在用SpringMVC嘛。但是我看網(wǎng)上那些文章,基本都是只說明了基礎(chǔ)用法,詳細(xì)的使用和細(xì)節(jié)卻基本沒有,我想這是不夠的,所以我自己做了一些測試,然后整理了下代碼做了個(gè)demo,記錄并分享下,有什么不足的歡迎提出來討論。
好了,廢話就說到這,下面正戲開始!
結(jié)論
嗯,為了給一些不喜歡看代碼的客官省去翻結(jié)論的麻煩,我這里就先把我測試后的結(jié)論先列一下吧。
1、可以通過SpringMVC特有的ModelMap、Model在Controller中自動(dòng)保存數(shù)據(jù)到session,也可以通過傳統(tǒng)的HttpSession等參數(shù)保存session數(shù)據(jù)
2、保存session數(shù)據(jù)必須使用@SessionAttributes注解,該注解有2種參數(shù)聲明方式(value和types),且該注解聲明必須寫在類上,不能在方法上
3、保存的session數(shù)據(jù)必須與@SessionAttributes注解中的參數(shù)列表對應(yīng),未被聲明的參數(shù)無法保存到session中
4、使用SessionStatus可以清除session中保存的數(shù)據(jù),注意是全部清除,無法單獨(dú)刪除指定的session數(shù)據(jù)。同時(shí),清除時(shí)有效權(quán)限遵循上述第2、3條規(guī)則(借用此規(guī)則可人為達(dá)到刪除指定session數(shù)據(jù)的效果)
5、通過ModelMap等讀取session中數(shù)據(jù)時(shí),也有上述的參數(shù)權(quán)限限制
6、使用ModelMap或Model等保存session數(shù)據(jù)時(shí),ModelMap必須作為方法參數(shù)傳入,在方法中新定義的無效。同時(shí),只要把ModelMap作為參數(shù)傳入,即使是被別的方法調(diào)用也能起效
7、使用@ResponseBody注解時(shí)(一般配合ajax使用),無法保存session數(shù)據(jù)
8、@SessionAttributes注解可以使用value和types 2種參數(shù)列表
9、使用HttpSession的傳統(tǒng)方式操作沒有上述注解及權(quán)限等限制,下面有簡單測試,但是不做具體說明
以下還有幾個(gè)應(yīng)該算是常識性的知識點(diǎn)
10、操作session數(shù)據(jù)可以跨類,與包或者url的路徑等也沒有關(guān)系
11、同一個(gè)session值操作,后面的值會(huì)覆蓋前面的值
測試代碼及簡單說明
開發(fā)工具: Spring Tool Suite 。
spring專為SpringMVC搞出來的一款基于Eclipse的IDE開發(fā)工具,集成了Maven和Tomcat,最近用下來感覺還不錯(cuò)的,推薦下。
首先來一個(gè)項(xiàng)目結(jié)構(gòu)截圖吧
因?yàn)楹竺娴臏y試中有用到ajax的@ResponseBody注解,所以要在pom.xml文件中配置jar包。
<!-- 使用@ResponseBody注解所需的2個(gè)包 --> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-core-asl</artifactId> <version>1.9.13</version> </dependency> <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version>1.9.13</version> </dependency>
下面是主要的測試代碼
package test.dmh.session; import java.util.Enumeration; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; /** * @SessionAttributes 只聲明了參數(shù)test1 */ @Controller @SessionAttributes(value={"test1"}) public class HomeController { private static final Logger logger = LoggerFactory.getLogger(HomeController.class); @RequestMapping(value = "/show1") public String show(ModelMap modelMap, HttpSession session) { logger.info("show session"); for (Object key : modelMap.keySet()) { Object value = modelMap.get(key); System.out.println(key + " = " + value); } System.out.println("***********************************"); Enumeration<String> e = session.getAttributeNames(); while (e.hasMoreElements()) { String s = e.nextElement(); System.out.println(s + " == " + session.getAttribute(s)); } System.out.println("***********************************"); return "home"; } @RequestMapping("/set1") public String setSession(ModelMap modelMap) { logger.info("set session 1"); modelMap.addAttribute("test1", "value 1"); //設(shè)置一個(gè)在@SessionAttributes中聲明過的參數(shù) modelMap.addAttribute("test2", "value 2"); //設(shè)置一個(gè)未在@SessionAttributes中聲明過的參數(shù) return "home"; } @RequestMapping("/setM") public String setSessionM(Model model) { logger.info("set session 1"); model.addAttribute("test1", "value 1"); //設(shè)置一個(gè)在@SessionAttributes中聲明過的參數(shù) model.addAttribute("test2", "value 2"); //設(shè)置一個(gè)未在@SessionAttributes中聲明過的參數(shù) return "home"; } @RequestMapping("/clear1") public String clear(SessionStatus status) { logger.info("clear session 1"); status.setComplete(); return "home"; } }
package test.dmh.session.controller; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; /** * 沒有使用@SessionAttributes注解 */ @Controller public class IndexController { private static final Logger logger = LoggerFactory.getLogger(IndexController.class); @RequestMapping("/set2") public String setSession(ModelMap modelMap, HttpSession session) { logger.info("set session 2 : without @SessionAttributes"); modelMap.addAttribute("test3", "value 3"); session.setAttribute("test4", "value 4"); return "home"; } }
package test.dmh.session.controller; import java.util.Enumeration; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; @Controller @SessionAttributes(value={"test5", "index"}) public class IndexController2 { private static final Logger logger = LoggerFactory.getLogger(IndexController2.class); @RequestMapping("/set3") public String setSession(ModelMap modelMap, HttpSession session) { logger.info("set session 3"); modelMap.addAttribute("test5", "value 5"); session.setAttribute("test6", "value 6"); ModelMap map = new ModelMap(); map.addAttribute("test7", "value 7"); this.setValueToSession(modelMap, session, "Hello World"); return "home"; } @ResponseBody @RequestMapping(value="/login") public Map<String, Object> login(ModelMap modelMap, HttpSession session) { logger.info("login"); Map<String, Object> map = new HashMap<String, Object>(); map.put("success", true); map.put("info", "登錄成功!"); modelMap.addAttribute("testAjax", "test ajax value"); session.setAttribute("httpTestAjax", "http test ajax Value"); setValueToSession(modelMap, session, "This is Ajax"); return map; } private void setValueToSession(ModelMap modelMap, HttpSession session, String value) { logger.info("set session private"); modelMap.addAttribute("index", value); session.setAttribute("httpIndex", value); } @RequestMapping("/clear2") public String clear(SessionStatus status) { logger.info("clear session 2"); status.setComplete(); return "home"; } @RequestMapping(value = "/show2") public String show(ModelMap modelMap, HttpSession session) { logger.info("show session"); for (Object key : modelMap.keySet()) { Object value = modelMap.get(key); System.out.println(key + " = " + value); } System.out.println("***********************************"); Enumeration<String> e = session.getAttributeNames(); while (e.hasMoreElements()) { String s = e.nextElement(); System.out.println(s + " == " + session.getAttribute(s)); } System.out.println("***********************************"); return "home"; } }
這里如果也是跟我一樣用STS建的項(xiàng)目,默認(rèn)jsp文件會(huì)有配置<%@ page session="false" %>,一定要?jiǎng)h除或者注釋掉。否則無法在頁面上展示session中的數(shù)據(jù),當(dāng)然通過我這邊寫的/show測試直接看后臺(tái)代碼也是可以的。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> 4 <html> <head> <title>Home</title> </head> <body> <h2> Hello world! </h2> <p> The test1 is ${sessionScope.test1}. </p> <p> The test2 is ${sessionScope.test2}. </p> <p> The test3 is ${sessionScope.test3}. </p> <p> The test4 is ${sessionScope.test4}. </p> <p> The test5 is ${sessionScope.test5}. </p> <p> The test6 is ${sessionScope.test6}. </p> <p> The test7 is ${sessionScope.test7}. </p> <p> The index is ${sessionScope.index}. </p> <p> The httpIndex is ${sessionScope.httpIndex}. </p> <br> <input type="button" value="test" onclick="test();"> <script src="resources/js/jquery.min.js"></script> <script type="text/javascript"> function test() { $.ajax({ type : "POST", url : "login", dataType : "json", success : function(data) { console.log(data); window.open("/session/test", "_self"); }, error : function() { alert("出錯(cuò)了!"); } }); } </script> </body> </html>
另外還有一個(gè)特別針對@SessionAttributes參數(shù)配置的測試代碼
package test.dmh.session.controller; import java.util.Enumeration; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.bind.support.SessionStatus; @Controller @SessionAttributes(value={"index1", "index2"}, types={String.class, Integer.class}) public class IndexController3 { private static final Logger logger = LoggerFactory.getLogger(IndexController3.class); @RequestMapping("/setIndex") public String setSession(ModelMap modelMap) { logger.info("set session index"); modelMap.addAttribute("index1", "aaa"); modelMap.addAttribute("index2", "bbb"); modelMap.addAttribute("index2", "ccc"); modelMap.addAttribute("DDD"); modelMap.addAttribute("FFF"); modelMap.addAttribute(22); return "home"; } @RequestMapping(value = "/showIndex") public String show(ModelMap modelMap, HttpSession session) { logger.info("show session"); for (Object key : modelMap.keySet()) { Object value = modelMap.get(key); System.out.println(key + " = " + value); } System.out.println("***********************************"); Enumeration<String> e = session.getAttributeNames(); while (e.hasMoreElements()) { String s = e.nextElement(); System.out.println(s + " == " + session.getAttribute(s)); } System.out.println("***********************************"); return "home"; } @RequestMapping("/clearIndex") public String clear(SessionStatus status) { logger.info("clear session index"); status.setComplete(); return "home"; } }
測試過程簡單說明:
因?yàn)閰?shù)比較多,所以我也是懶得想名字,序列化的test1、2、3過去了。
測試的時(shí)候就是在瀏覽器上輸入網(wǎng)址:http://localhost:8080/session/show1
然后把后綴show1改成別的,比如set1, set2以及clear1, clear2這些,具體的請看我代碼中的@RequestMapping配置。
每次輸入set1,set2這些以后,需要輸入show1,show2來通過控制臺(tái)查看session中的內(nèi)容,當(dāng)然直接在瀏覽器上看顯示信息也是可以的。
這邊我再說一下主要的幾個(gè)結(jié)論:
1、使用ModelMap自動(dòng)保存數(shù)據(jù)到session必須配置@SessionAttributes注解
2、使用@SessionAttributes注解只能聲明在類上,聲明以后,該類中的方法操作session數(shù)據(jù)只能對@SessionAttributes中配置的參數(shù)起作用,包括保存、清除和讀取。
最后還有針對@SessionAttributes中的參數(shù)配置得出的幾點(diǎn)結(jié)論:
1、配置參數(shù)提供value和types,存放的都是數(shù)組類型。(只有1個(gè)參數(shù)時(shí)不需要寫成數(shù)組形式,比如@SessionAttributes(value="test1", types=Integer.class))
2、使用value配置參數(shù)類似于Map的鍵值對中的key
3、實(shí)用types配置參數(shù)后,后臺(tái)保存的key就是它的類型,個(gè)人感覺只有在保存自定義類對象的時(shí)候有些用處,比如types=User.class,一般的常用類對象如String等我覺得還是用value的鍵值對比較好。當(dāng)然,具體情況還是要具體分析的。
看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。