Spring MVC session Attribute set intially - java

I have used the Spring MVC. I set the Session Attribute value like
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String initHome(Model model) {
if (!model.containsAttribute("clientObject")) {
model.addAttribute("clientObject", createDefaultClient());
}
return "homeMenu";
}
It is working fine if i click the home menu url(/home). but if i did not go the
home means it says error as 'session attribute clientObject is required'
so i decided to set sessionattibutes in constructor of controller
#Autowired
public MyController(Model model) {
if (!model.containsAttribute("clientObject")) {
model.addAttribute("clientObject", createDefaultClient());
}
}
it also says error
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myController'
I tried to set using the RequestMapping also like
#RequestMapping(value = "/", method = RequestMethod.GET)
public void initController(Model model) {
if (!model.containsAttribute("clientObject")) {
model.addAttribute("clientObject", createDefaultClient());
}
}
this method is also not called intially
my cointroller look like
#RequestMapping("/sample")
public class MyController {
..
..
is it possible to set the sessionAttribute value in the constructor of controller? or any other way to set the session Attribute initially?
Thanks in advance for your help.

Assuming your createDefaultClient is in the controller add a #ModelAttribute annotation to it.
#ModelAttribute("clientObject")
public ClientObject createDefaultClient() { ... }
This method will be called before any request handling method (as explained in the reference guide)
If you combine that with a #SessionAttribute annotation on your class (which you might already have). You should be able to achieve what you want.
In your request handling methods (methods annotated with #RequestMapping) you can now simply inject the client object as a method argument.
#RequestMapping(value = "/home", method = RequestMethod.GET)
public String initHome(#ModelAttribute("clientObject") ClientObject clientObject) {
// Do something with the clientObject
return "homeMenu";
}
This will only work consistenly within the same controller, so if you need the ClientObject to be used somewhere else (another controller for instance), this isn't going to work (nor is #SessionAttributes designed for that).

Related

SpringMVC:Is there any custom Resolver available to resolve "RequestMapping" annotated method?

Some of my RequestMapping annotated controller method are annotated with something like #Authentication("user"/"admin"). So I can now user aop to authenticate all the requests.
But now I am also using cumtomized HandlerMethodArgumentResolver, I want to resolve authentications before HandlerMethodArgumentResolver.
What I want to achieve is something like this:
#Authentication("user")
#RequestMapping("/xxx", method = RequestMethod.GET)
public getxxx(Token token) {
System.out.println(token.getUserId());
}
Is that possible?
Edit:
Token token in the argument is not necessary. For example:
#Authentication("user")
#RequestMapping("/xxx", method = RequestMethod.GET)
public getxxx() {
// do something authenticated "users" can only do
}

Spring MVC: bind request attribute to controller method parameter

In Spring MVC, it is easy to bind request parameter to method paramaters handling the request. I just use #RequestParameter("name"). But can I do the same with request attribute? Currently, when I want to access request attribute, I have to do following:
MyClass obj = (MyClass) request.getAttribute("attr_name");
But I really would like to use something like this instead:
#RequestAttribute("attr_name") MyClass obj
Unfortunately, it doesn't work this way. Can I somehow extend Spring functionality and add my own "binders"?
EDIT (what I'm trying to achieve): I store currently logged user inside request attribute. So whenever I want to access currently logged user (which is pretty much inside every method), I have to write this extra line user = (User) request.getAttribute("user");. I would like to make it as short as possible, preferably inject it as a method parameter. Or if you know another way how to pass something across interceptors and controllers, I would be happy to hear it.
Well, I finally understood a little bit how models work and what is #ModelAttribute for. Here is my solution.
#Controller
class MyController
{
#ModelAttribute("user")
public User getUser(HttpServletRequest request)
{
return (User) request.getAttribute("user");
}
#RequestMapping(value = "someurl", method = RequestMethod.GET)
public String HandleSomeUrl(#ModelAttribute("user") User user)
{
// ... do some stuff
}
}
The getUser() method marked with #ModelAttribute annotation will automatically populate all User user parameters marked with #ModelAttribute. So when the HandleSomeUrl method is called, the call looks something like MyController.HandleSomeUrl(MyController.getUser(request)). At least this is how I imagine it. Cool thing is that user is also accessible from the JSP view without any further effort.
This solves exactly my problem however I do have further questions. Is there a common place where I can put those #ModelAttribute methods so they were common for all my controllers? Can I somehow add model attribute from the inside of the preHandle() method of an Interceptor?
Use (as of Spring 4.3) #RequestAttribute:
#RequestMapping(value = "someurl", method = RequestMethod.GET)
public String handleSomeUrl(#RequestAttribute User user) {
// ... do some stuff
}
or if the request attribute name does not match the method parameter name:
#RequestMapping(value = "someurl", method = RequestMethod.GET)
public String handleSomeUrl(#RequestAttribute(name="userAttributeName") User user) {
// ... do some stuff
}
I think what you are looking for is:
#ModelAttribute("attr_name") MyClass obj
You can use that in the parameters for a method in your controller.
Here is a link a to question with details on it What is #ModelAttribute in Spring MVC?
That question links to the Spring Documentation with some examples of using it too. You can see that here
Update
I'm not sure how you are setting up your pages, but you can add the user as a Model Attribute a couple different ways. I setup a simple example below here.
#RequestMapping(value = "/account", method = RequestMethod.GET)
public ModelAndView displayAccountPage() {
User user = new User(); //most likely you've done some kind of login step this is just for simplicity
return new ModelAndView("account", "user", user); //return view, model attribute name, model attribute
}
Then when the user submits a request, Spring will bind the user attribute to the User object in the method parameters.
#RequestMapping(value = "/account/delivery", method = RequestMethod.POST)
public ModelAndView updateDeliverySchedule(#ModelAttribute("user") User user) {
user = accountService.updateDeliverySchedule(user); //do something with the user
return new ModelAndView("account", "user", user);
}
Not the most elegant, but works at least...
#Controller
public class YourController {
#RequestMapping("/xyz")
public ModelAndView handle(
#Value("#{request.getAttribute('key')}") SomeClass obj) {
...
return new ModelAndView(...);
}
}
Source : http://blog.crisp.se/tag/requestattribute
From spring 3.2 it can be done even nicer by using Springs ControllerAdvice annotation.
This then would allow you to have an advice which adds the #ModelAttributes in a separate class, which is then applied to all your controllers.
For completeness, it is also possible to actually make the #RequestAttribute("attr-name") as is.
(below modified from this article to suit our demands)
First, we have to define the annotation:
#Retention(RetentionPolicy.RUNTIME)
#Target(ElementType.PARAMETER)
public #interface RequestAttribute {
String value();
}
Then we need a [WebArgumentResolver] to handle what needs to be done when the attribute is being bound
public class RequestAttributeWebArgumentResolver implements WebArgumentResolver {
public Object resolveArgument(MethodParameter methodParameter, NativeWebRequest nativeWebRequest) throws Exception {
// Get the annotation
RequestAttribute requestAttributeAnnotation = methodParameter.getParameterAnnotation(RequestAttribute.class);
if(requestAttributeAnnotation != null) {
HttpServletRequest request = (HttpServletRequest) nativeWebRequest.getNativeRequest();
return request.getAttribute(requestAttributeAnnotation.value);
}
return UNRESOLVED;
}
}
Now all we need is to add this customresolver to the config to resolve it:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="customArgumentResolver">
<bean class="com.sergialmar.customresolver.web.support.CustomWebArgumentResolver"/>
</property>
</bean>
And we're done!
Yes, you can add your own 'binders' to the request attribute - see spring-mvc-3-showcase, or use #Peter Szanto's solution.
Alternatively, bind it as a ModelAttribute, as recommended in other answers.
As it's the logged-in user that you want to pass into your controller, you may want to consider Spring Security. Then you can just have the Principle injected into your method:
#RequestMapping("/xyz")
public String index(Principal principle) {
return "Hello, " + principle.getName() + "!";
}
In Spring WebMVC 4.x, it prefer implements HandlerMethodArgumentResolver
#Override
public boolean supportsParameter(MethodParameter parameter) {
return parameter.getParameterAnnotation(RequestAttribute.class) != null;
}
#Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
return webRequest.getAttribute(parameter.getParameterAnnotation(RequestAttribute.class).value(), NativeWebRequest.SCOPE_REQUEST);
}
}
Then register it in RequestMappingHandlerAdapter

What parameters should take a controller's method, which is deleting records from the database?

I'm creating a simple training project. I've implemented a controller method, which deletes an item from the list. The method is looking like this:
#Controller
#RequestMapping(value = "/topic")
public class TopicController {
#Autowired
private TopicService service;
...
#RequestMapping(value = "/deleteComment/{commentId}", method = RequestMethod.POST)
public String deleteComment(#PathVariable int commentId, BindingResult result, Model model){
Comment deletedComment = commentService.findCommentByID(commentId);
if (deletedComment != null) {
commentService.deleteComment(deletedComment);
}
return "refresh:";
}
}
This method is called from the button-tag, which is looking in the following way:
<form><button formaction = "../deleteComment/1" formmethod = "post">delete</button></form>
In my project the form-tag is looking like a clickable button. But there is a serious problem: controller's method is never triggered. How can I trigger it, using a button-tag?
P.S. the call is performed from the page with URI http://localhost:8080/simpleblog/topic/details/2 and controller's URI is the http://localhost:8080/simpleblog/topic/deleteComment/2
UPDATE:
I've created hyperlink 'delete', clicking on which should delete a comment, and I received an exception
java.lang.IllegalStateException: Errors/BindingResult argument declared without preceding model attribute. Check your handler method signature!
And it's true: I really have no #ModelAttribute in my controller method, preceding BindingResult parameter. But I have no clue, which type of type should it be?
<form>'s method attribute is GET by default. I don't know what are you trying to do with formmethod and formaction attributes, but in default HTML they mean nothing.
You must try something like:
<form action="../deleteComment/1" method="post">
<button>delete</button>
</form>
EDIT:
You are declaring some unused parameters in your method. BindingResult must be used with a #Valid annotated attribute (search #Valid here to see some examples), but this is not your case. So, please just try:
#RequestMapping(value = "/deleteComment/{commentId}", method = RequestMethod.POST)
public String deleteComment(#PathVariable int commentId){
...
}

Java - Spring 3.0 MVC and #ModelAttribute

I need some clarification about Spring 3.0 MVC and #ModelAttribute annotated method parameter. I have a Controller which looks like this one:
RequestMapping(value = "/home")
#Controller
public class MyController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView foo() {
// do something
}
#RequestMapping(method = RequestMethod.POST)
public ModelAndView bar(
#ModelAttribute("barCommand") SomeObject obj) {
// do sometihng with obj and data sent from the form
}
}
and on my home.jsp i have a form like this one which sends his data to the RequestMethod.POST method of MyController
<form:form action="home" commandName="barCommband">
</form:form
Now if i try to access home.jsp i get this Exception:
java.lang.IllegalStateException:
Neither BindingResult nor plain target object for bean name 'barCommand' available as request attribute
To resolve this i found that i need to add the
#ModelAttribute("barCommand") SomeObject obj
parameter to the Request.GET method of MyController, even if i won't use obj in that method. And for example if add another form to home.jsp with a different commandName like this:
<form:form action="home/doSomething" commandName="anotherCommand">
</form:form
i also have to add that parameter on the RequestMethod.GET, which will now look like:
#RequestMapping(method = RequestMethod.GET)
public ModelAndView foo( #ModelAttribute("barCommand") SomeObject obj1,
#ModelAttribute("anotherCommand") AnotherObj obj2) {
// do something
}
or i get the same exception. What i'm asking is if this is a normal Spring 3 MVC behaviour or if i'm doing something wrong. And why do i need to put all the #ModelAttribute parameters on the RequestMethod.GET method?
Thanks in advance for you help
Stefano
Here is the spring mvc reference. Looked through it briefly and found 2 approaches:
#InitBinder
#ModelAttribute("bean_name") with method.
You may use first to customize data binding and, thus, create command objects on-the-fly. Second allows you to annotate method with it and prepopulate model attributes with this name:
#ModelAttribute("bean_name")
public Collection<PetType> populatePetTypes() {
return this.clinic.getPetTypes();
}
I hope it will populate model attributes with name 'bean_name' if it is null.

Spring 3.0 set and get session attribute

I want to read a domain object (UserVO) from session scope.
I am setting the UserVO in a controller called WelcomeController
#Controller
#RequestMapping("/welcome.htm")
public class WelcomeController {
#RequestMapping(method = RequestMethod.POST)
public String processSubmit(BindingResult result, SessionStatus status,HttpSession session){
User user = loginService.loginUser(loginCredentials);
session.setAttribute("user", user);
return "loginSuccess";
}
}
I am able to use the object in jsp pages <h1>${user.userDetails.firstName}</h1>
But I am not able to read the value from another Controller,
I am trying to read the session attribute as follows:
#Controller
public class InspectionTypeController {
#RequestMapping(value="/addInspectionType.htm", method = RequestMethod.POST )
public String addInspectionType(InspectionType inspectionType, HttpSession session)
{
User user = (User) session.getAttribute("user");
System.out.println("User: "+ user.getUserDetails().getFirstName);
}
}
The code you've shown should work - the HttpSession is shared between the controllers, and you're using the same attribute name. Thus something else is going wrong that you're not showing us.
However, regardless of whether or not it works, Spring provides a more elegant approach to keeping your model objects in the session, using the #SessionAttribute annotation (see docs).
For example (I haven't tested this, but it gives you the idea):
#Controller
#RequestMapping("/welcome.htm")
#SessionAttributes({"user"})
public class WelcomeController {
#RequestMapping(method = RequestMethod.POST)
public String processSubmit(ModelMap modelMap){
User user = loginService.loginUser(loginCredentials);
modelMap.addtAttribute(user);
return "loginSuccess";
}
}
and then
#Controller
#SessionAttributes({"user"})
public class InspectionTypeController {
#RequestMapping(value="/addInspectionType.htm", method = RequestMethod.POST )
public void addInspectionType(InspectionType inspectionType, #ModelAttribute User user) {
System.out.println("User: "+ user.getUserDetails().getFirstName);
}
}
However, if your original code isn't working, then this won't work either, since something else is wrong with your session.
#SessionAttributes works only in context of particular handler, so attribute set in WelcomeController will be visible only in this controller.
Use a parent class to inherit all the controllers and use SessionAttributes over there. Just that this class should be in the package scan of mvc.
May be you have not set your UserVO as Serializable.

Categories