你能帮我写一个Spring MVC风格的代码,与这段代码类似吗?
session.setAttribute("name","value");
如何将使用@ModelAttribute
注释的元素添加到会话中,并获得对它的访问权限?
你能帮我写一个Spring MVC风格的代码,与这段代码类似吗?
session.setAttribute("name","value");
如何将使用@ModelAttribute
注释的元素添加到会话中,并获得对它的访问权限?
directly add one attribute to session:
@RequestMapping(method = RequestMethod.GET)
public String testMestod(HttpServletRequest request){
ShoppingCart cart = (ShoppingCart)request.getSession().setAttribute("cart",value);
return "testJsp";
}
and you can get it from controller like this :
ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
Make your controller session scoped
@Controller
@Scope("session")
Scope the Objects ,for example you have user object that should be in session every time:
@Component
@Scope("session")
public class User
{
String user;
/* setter getter*/
}
then inject class in each controller that you want
@Autowired
private User user
that keeps class on session.
The AOP proxy injection : in spring -xml:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
<bean id="user" class="com.User" scope="session">
<aop:scoped-proxy/>
</bean>
</beans>
then inject class in each controller that you want
@Autowired
private User user
5.将HttpSession传递给方法:
String index(HttpSession session) {
session.setAttribute("mySessionAttribute", "someValue");
return "index";
}
6. 通过 @SessionAttributes("ShoppingCart") 将 ModelAttribute 存入会话:
public String index (@ModelAttribute("ShoppingCart") ShoppingCart shoppingCart, SessionStatus sessionStatus) {
//Spring V4
//you can modify session status by sessionStatus.setComplete();
}
或者您可以像以下方法,将模型添加到整个控制器类中:
@Controller
@SessionAttributes("ShoppingCart")
@RequestMapping("/req")
public class MYController {
@ModelAttribute("ShoppingCart")
public Visitor getShopCart (....) {
return new ShoppingCart(....); //get From DB Or Session
}
}
<%=session.getAttribute("ShoppingCart.prop")%>
在Jstl中:
<c:out value="${sessionScope.ShoppingCart.prop}"/>
<p th:text="${session.ShoppingCart.prop}" th:unless="${session == null}"> . </p>
使用 @SessionAttributes
请参阅文档:使用 @SessionAttributes 在请求之间将模型属性存储在HTTP会话中
"了解Spring MVC模型和会话属性"也很好地概述了Spring MVC会话,并解释了何时如何将 @ModelAttribute
转移到会话中(如果控制器带有 @SessionAttributes
注解)。
该文章还解释说,最好在模型上使用 @SessionAttributes
而不是直接在 HttpSession 上设置属性,因为这有助于Spring MVC对视图保持不可知性。
SessionAttribute
注释是最简单和直接的,而不是从请求对象中获取会话并设置属性。
在控制器中可以向模型添加任何对象,如果它的名称与@SessionAttributes
注释中的参数匹配,则该对象将存储在会话中。
在下面的例子中,personObj
将可用于会话。
@Controller
@SessionAttributes("personObj")
public class PersonController {
@RequestMapping(value="/person-form")
public ModelAndView personPage() {
return new ModelAndView("person-page", "person-entity", new Person());
}
@RequestMapping(value="/process-person")
public ModelAndView processPerson(@ModelAttribute Person person) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("person-result-page");
modelAndView.addObject("pers", person);
modelAndView.addObject("personObj", person);
return modelAndView;
}
}
@RequestMapping("/testing")
@Controller
public class TestController {
@RequestMapping(method = RequestMethod.GET)
public String testMestod(HttpServletRequest request){
request.getSession().setAttribute("name", "value");
return "testJsp";
}
}
要在JSP中访问相同的内容,请使用${sessionScope.name}
。
有关@ModelAttribute
的详细信息,请参阅此链接。
这样做不是最简单且最短吗?我知道并测试过- 在这里完美运行:
@GetMapping
public String hello(HttpSession session) {
session.setAttribute("name","value");
return "hello";
}
p.s. 我来到这里寻找答案:“如何在Spring-mvc中使用会话属性”,但是阅读了很多篇文章却没有看到我已经在我的代码中写了最明显的答案。我没有看到它,所以认为它是错误的,但实际上不是。因此,让我们分享这个问题的最简单解决方案的知识。
@Controller
@RequestMapping("/owners/{ownerId}/pets/{petId}/edit")
@SessionAttributes("pet")
public class EditPetForm {
@ModelAttribute("types")
public Collection<PetType> populatePetTypes() {
return this.clinic.getPetTypes();
}
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pet") Pet pet,
BindingResult result, SessionStatus status) {
new PetValidator().validate(pet, result);
if (result.hasErrors()) {
return "petForm";
}else {
this.clinic.storePet(pet);
status.setComplete();
return "redirect:owner.do?ownerId="
+ pet.getOwner().getId();
}
}
}
@SessionAttributes
和@SessionAttribute
来保留会话属性。@Controller
@SessionAttributes("SessionKey")
public class OrderController extends BaseController {
GetMapping("/showOrder")
public String showPage(@SessionAttribute("SessionKey") SearchCriteria searchCriteria) {
// method body
}
@RequestMapping(value = "/login")
@ResponseBody
public BooleanResponse login(HttpSession session,HttpServletRequest request){
//HttpServletRequest used to take data to the controller
String username = request.getParameter("username");
String password = request.getParameter("password");
//Here you set your values to the session
session.setAttribute("username", username);
session.setAttribute("email", email);
//your code goes here
}
在视图方面,你不需要改变特定的东西。
<c:out value="${username}"></c:out>
<c:out value="${email}"></c:out>
登录后,将上述代码添加到您网站的任何位置。如果会话正确设置,您将在那里看到值。请确保正确添加了jstl标签和El表达式(这里是设置jstl标签的链接https://menukablog.wordpress.com/2016/05/10/add-jstl-tab-library-to-you-project-correctly/)。
使用这个方法非常简单易用
HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getNativeRequest();
request.getSession().setAttribute("errorMsg", "your massage");
在 JSP 中,一旦使用就要删除。
<c:remove var="errorMsg" scope="session"/>
package test;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class ControllerClass {
@GetMapping(value = "/someValue")
public String requestHandler(HttpServletRequest request, Model model) throws Exception {
String value = request.getSession().getAttribute("someAttribute");
model.addAttribute("attributeName", "value is "+ value);
return "JspFileName";
}
}
session
作用域相同的类中的bean时,注入User
bean才能正常工作。否则,如果没有会话存在,则会抛出异常,因为在注入user
bean到另一个类时,上下文@runtime中不会有任何活动会话! - Jose Mhlanga