JSF 1.2 : Not able to retrieve bean values in xhtml page - jsf-1.2

Am using JSF 1.2 . I have a servlet. When this servlet is hit, am getting the data from request parameters, in doPost, and I need to set it in bean so that I can show it on xhtml page.
My code is like below.
userId= request.getParameter("userID");
MyBean myBean = new MyBean();
myBean.initialize(userId);
In initialize method of myBean am setting userId value into a globalVariable.
In my logs in bean, globalVariable value is getting printed. But its not getting displayed on xhtml page.
Am redirecting to xhtml page in doPost method like below,
RequestDispatcher dispatcher = request.getRequestDispatcher("/jsp/html/index.jsf");
dispatcher.forward(request, response);
In index.xhtml page, I have
<h:outputText value="#{myBean.globalVariable}"></h:outputText>
In my phaselistener am not doing any thing much. I just have beforPhase method.
Why am I not able to print the value in jsf page but able to print the value in log in bean?

Before forwarding, you need to put the bean in the scope, exactly there where JSF expects it.
If it's a request scoped bean, use HttpServletRequest#setAttribute().
request.setAttribute("myBean", myBean);

Related

Spring MVC: flash attribute vs model attribute

What is the different between flash and model attribute?
I want to store an object and display it in my JSP as well as reuse it in other controller. I have use sessionAttribute and it works fine in the JSP, but the problem is when I try to retrieve that model attribute in other controller.
I lose some data. I searched around and found that flash attribute allows to past past value to different controller, doesn't it?
If we want to pass the attributes via redirect between two controllers, we cannot use request attributes (they will not survive the redirect), and we cannot use Spring's #SessionAttributes (because of the way Spring handles it), only an ordinary HttpSession can be used, which is not very convenient.
Flash attributes provide a way for one request to store attributes intended for use in another. This is most commonly needed when redirecting — for example, the Post/Redirect/Get pattern. Flash attributes are saved temporarily before the redirect (typically in the session) to be made available to the request after the redirect and removed immediately.
Spring MVC has two main abstractions in support of flash attributes. FlashMap is used to hold flash attributes while FlashMapManager is used to store, retrieve, and manage FlashMap instances.
Example
#Controller
#RequestMapping("/foo")
public class FooController {
#RequestMapping(value = "/bar", method = RequestMethod.GET)
public ModelAndView handleGet(Model model) {
String some = (String) model.asMap().get("some");
// do the job
}
#RequestMapping(value = "/bar", method = RequestMethod.POST)
public ModelAndView handlePost(RedirectAttributes redirectAttrs) {
redirectAttrs.addFlashAttribute("some", "thing");
return new ModelAndView().setViewName("redirect:/foo/bar");
}
}
In above example, request comes to handlePost, flashAttributes are added, and retrieved in handleGet method.
More info here and here.

Returning null from a spring mvc controller method

I have read the Spring documentation and I was not able to find relevant information regarding the expected behavior of a Spring MVC controller method returning null (with a return type of String).
Can someone please provide a reply or direct me to relevant documentation? Or to put it another way, what would be the benefit of returning null from a Spring MVC controller method?
In Spring 2, when you returned null from a controller you were saying to the Spring dispatcher that you don't want it to search for a view.
You did this if you were handling the response yourself by writing the response content directly and then flushing the output stream (you were managing a file download for example).
If you didn't return null, Spring would have forwarded to a view who would try to write to the response also, messing up your already written data or resulting in an exception if the response was already commited.
Returning null was a way of saying back off to Spring's view resolver.
A lot of things changed in Spring 3 and now the same can be obtained by having an #RequestMapping annotated method that returns void.
If you have a return type of String but you return null I think that it uses the default RequestToViewNameTranslator for translating an incoming HttpServletRequest into a logical view name when the view name wasn't explicitly supplied.
Return type String in spring mvc generally returns your view resolver, it can be your JSP, html or any other view page.
http://www.mkyong.com/spring3/spring-3-mvc-hello-world-example/
Suppose you want to return a normal String like "hi", you can use #ResponseBody annotation to do this.

Spring MVC: Session attribute required - not found in session

I am receiving the following error on submitting my form:
org.springframework.web.HttpSessionRequiredException: Session attribute 'rulesForm' required - not found in session
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodInvoker.raiseSessionRequiredException(AnnotationMethodHandlerAdapter.java:722)
My JSP contains the following:
<form:form id="rulesForm" modelAttribute="rulesForm" action="save.do">
...
</form>
My Controller contains the following:
#Controller
#RequestMapping("/rules")
#SessionAttributes({"rulesForm", "deskForm"})
public class RulesController {
.
.
.
#RequestMapping(value = "/save.do")
public ModelAndView saveRuleAttributesAndRules(#Valid
#ModelAttribute("rulesForm")
RulesFormDTO rulesForm, BindingResult bindingResult, HttpSession session, Principal principal) {
It seems that if I leave my browser open for a while with my form displaying and then I attempt to perform a submit after some time I get this error.
Really what I want to happen in this case is for the new "rulesForm" object to be created...how can I achieve this?
Thanks
As the Javadoc on #SessionAttribute indicates use of the annotation means you want store the specified model attributes in the session, which means you need to add them to the model first. Spring MVC will not create them.
In other words when you add a #ModelAttribute("rulesForm") controller method argument you're telling Spring MVC to look for it in the model or create a new instance if not found. However if you also add #SessionAttributes, Spring MVC will not attempt to create a new instance and will expect the object to be either in the model or in the session. You can use a #ModelAttribute method to add your object initially.

Does Velocity template has implicit request object?

I'm rephrasing my existing question to a more generic one. I want to know if Velocity has got implicit object references like JSP does.
I'm particularly interested in knowing about the request object.
In JSP we can get the attribute in the request scope like <%= request.getAttribute("req1") %>
I know that JSP is a servlet and <%= request.getAttribute("req1") %> ends up as a part of _jspService() method which has the request object available to it before the scope of the request ends.
I'm not sure how Velocity works behind the scenes (it may be leaving the request object behind by the time it plays it role)
To test that I did the following thing which was a the part of my previous question.
I have a Spring MVC TestController in which I'm setting a request attribute. I'm using Velocity templates for rendering the views.
#RequestMapping(value="/test", method=RequestMethod.GET)
public ModelAndView display(HttpServletRequest req, HttpServletResponse resp){
...
req.setAttribute("req1", "This should be present for first request");
...
}
In the Velocity template I'm doing something like
Request: $request.getAttribute('req1')
but I'm not getting the value of req1. I know I should have put req1 in model map instead of request but I want to know about implicit request object ref.
I tried $req1 as well but its not working.
When I'm doing the same thing with the model and returning it back, everything is working correctly.
Where am I going wrong?
Update: The same thing is happening with req.getSession().setAttribute("req1", testObject) also.
Salaam,
req.getSession().getAttribute("req1", testObject) == $req1
AFAIK, you cannot access the request object at VelocityViewServlet's templates, unless you explicity set the request object in context or use a v-tool .
Take a look at this question: Velocity + Spring. The Spring folks haven't kept the integration with Velocity very up to date.
Once you've created that extension and set it up to be used properly in your servlet configuration, you'd be able to simply put the object on the ModelAndView and from there do whatever you need with it.

Spring 3.0 HEAD Requests

recently we moved to spring 3.0 Controller handling like this:
#Controller
public class MyController {
#RequestMapping(method = RequestMethod.POST)
protected String onSubmit ( Form form, Errors errors) {
// handle POST
}
#RequestMapping(method = RequestMethod.GET)
protected void getForm ( Form form ) {
// handle GET
}
}
Now we are getting lots of Exceptions in our logs because of HEAD Requests.
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'HEAD' not supported
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter$ServletHandlerMethodResolver.resolveHandlerMethod(AnnotationMethodHandlerAdapter.java:621)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:422)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:415)
...
I would like to support HEAD Requests the same way like GET Requests, but obeying the HTTP reference of course:
The HEAD method is identical to GET
except that the server MUST NOT
return a message-body in the response.
The metainformation contained in
the HTTP headers in response to a HEAD
request SHOULD be identical to the
information sent in response to a GET
request. This method can be used
for obtaining metainformation about
the entity implied by the request
without transferring the entity-body
itself. This method is often used
for testing hypertext links for
validity, accessibility, and recent
modification.
http://www.ietf.org/rfc/rfc2616.txt
Does anybody has an elegant solution or is there even a spring solution out-of-the-box?
I searched the web but did not find any answers to this.
I believe this is what you're looking for:
http://www.axelfontaine.com/2009/09/transparently-supporting-http-head.html
In the current Spring (4.3.10) HEAD is automatically supported:
#RequestMapping methods mapped to "GET" are also implicitly mapped to
"HEAD", i.e. there is no need to have "HEAD" explicitly declared. An
HTTP HEAD request is processed as if it were an HTTP GET except
instead of writing the body only the number of bytes are counted and
the "Content-Length" header set.
https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-ann-requestmapping-head-options
Just add HEAD as a supported method the the request mapping:
#RequestMapping(method = {RequestMethod.GET, RequestMethod.HEAD})
Update: I think you can provide a custom class that extends AnnotationMethodHandlerAdapter to be the method handler (in dispatcher-servlet.xml), and just bypass the HEAD support check there. But I'd just use the replace features of an IDE to add it.

Resources