How to share a member of the form in Spring MVC?
How do I make a value retrieved from a form object available to another class.
Lets call this class Sample.java
. How do I make the values submitted from the
JSP form
available to class Sample.java
and keep it there for use until the user logs out.
I tried adding a public String variable in Controller method shown below and then creating an instance of Controller in Sample.java to get the value but it always returns a null
.
@RequestMapping( value = "abc/xyz/dummyPath.html", method = Reque开发者_JAVA技巧stMethod.POST )
public String processThisValue( @ModelAttribute( "myValues" ) MyBean myBean,
ModelMap model)
{
log.info("I am in my controller.........");
String valuePassed = myBean.getValuePassed();
log.info("Prints fine here: " + valuePassed);
return "";
}
The solution come in two parts:
1)
and keep it there for use until the user logs out.
You can use a Session scoped bean to hold the value.
2)
how do I make the values submitted from the JSP form available to class Sample.java
The Controller stores the Submitted value in that session bean. The Simple.java class (hopefully) a bean too, access that bean to get the value.
(I have no IDE at the moment, so I need to scribble it a bit)
@Component
@Scope(BeanDefinition.SCOPE_SESSION)
public class MySessionBean()
private String content;
Getter/setter
}
@Controller
...
@Autowire
private MySessionBean mySessionBean;
...
public String processThisValue( @ModelAttribute( "myValues" ) MyBean myBean,
ModelMap model) {
//myBean is only a simple class!!!!!
...
this.mySessioBean.setContent(valuePassed);
...
}
@Service
public class Sample() {
@Autowire
private MySessionBean mySessionBean;
public void doSomething() {
System.out.println("the current users value:" + mySessionBean.getValue());
}
}
You can use Httpsession to set your user session inside your Spring MVC Controller
public String processThisValue( @RequestParam("value") String value, HttpSession session
ModelMap model) {
MyBean.setTheValue("value");
session.setAttribute("key", MyBean);
return "somepage";
}
@Scope session annotation is nice but once your controller got too big then it can cause some scaling issue. I prefer the old tedious HttpSession :)
精彩评论