Returning null from a spring mvc controller method - spring-mvc

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.

Related

How to ignore Null values in Post request body in Spring Boot

I am calling a REST service with POST verb. Post request body is constructed dynamically.In some cases few fields will be populated with null values.Even though I used my Request pojo with #JsonInclude(Include.NON_NULL) or #JsonInclude(JsonInclude.Include.NON_NULL) null value fields are not getting removed.
My sample request will be looks like below.
I am constructing requestEntity by myself and not parsing it before posting.
resetTemplate.exchange(uri,HTTP.POST,requestEntity,responseObject)
How do I remover in the request body fileds with null value
I am using Spring Boot 1.5.9 and it uses Jackson 2.x
#JsonInclude(Include.NON_NULL) should have worked for you!
You seem to be constructing the request entity by yourself and not sure if you are passing on a JSON string with NON_NULL. Try this instead directly with entity if you have annotated with Jackson annotations.
restTemplate.postForEntity(uri, requestDto, ResponseDto.class);
Just use this #JsonSerialize(include = Inclusion.NON_NULL) instead of #JsonInclude(Include.NON_NULL) and it works..!!
NOTE :com.fasterxml.jackson.databind.annotation.JsonSerialize.Inclusion is now deprecated.

Manually doing what the ModelAttribute annotation does in Spring MVC

I have an action method on a Spring MVC controller that has an argument annotated with #ModelAttribute. However, I don't know at compile time what the type of this parameter will be - I know the abstract base type but not the derived type.
At runtime, I will be able to decide what class I am expecting and I will be able to get a new'd up instance of this class. However, I have no idea what code I should be calling to parse the request data in the same fashion that #ModelAttribute does.
I've looked around and it seems that if i can get a hold of a WebRequestDataBinder I can use that to populate my object, but for that I need a BinderFactory and this is where I kind of get lost.
Can anyone give me some pointers here - or tell me that I am looking at it the wrong way and need to do something else?
you can inject the model itself in your controllers method and access the attribute yourself.
#RequestMapping(...)
public void doStuff(ModelMap model) {
Object attr = model.get("nameOfAttribute");
// ...
}

Formatting uri template string values in ASP.NET WebApi

I have an ASP.NET WebApi application that has some controller methods that expect certain strings to be passed in as method parameters (declared as part of the route template).
On all the methods, the strings passed in are base64-encoded -- which means each controller method must base64-decode them before doing anything with them. While I can obviously have each method do this easily enough, I was wondering if there was a way to perform the decoding before the string actually gets passed to the controller method. I presume this is something along the lines of an action filter or custom formatter, but I'm not familiar enough with asp.net web api to know where to start on that?
Summary:
I've got route templates like : {controller}/{encodedString}/whatever
where {encodedString} is always a base64-encoded string.
and controllers with methods like
GetWhatever(string encodedString)
{
Base64Decode(encodedString);
// do other stuff...
}
I would like to use some part of the asp.net webapi pipeline to decode {encodedString} before the controller method is actually called. What path should I start down in order to do this?
You can create a custom model binder and attach it to the parameters using the ModelBinderAttribute. In the model binder you then do the base64 decoding.
For a reference on parameter binding in Web API check:
How WebAPI does Parameter Binding

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.

best practice for Spring validation of AJAX JSON data

I'm using AJAX to send JSON data from web page to back end, and need some validation strategies. I noticed that there're several ways to validate form parameters like SimpleFormController with ValidationUtils class and similar command object binding methods. But is there any suggestion to validate JSON data?
Thanks for even
Avoid the whole controller hierarchy. It is obsolete. Use the new restful style in spring mvc (available in 2.5, improved in 3.0).
There, you can define:
#RequestMapping("/url/foo")
public String handleFooInput(#Valid YourObject obj) { .. }
This will bind the input JSON to the object you specify, and will validate it (if it is annotated with javax.validation annotations). Three preconditions to that:
have jackson and jackson-mapper on your classpath, so that an object is created based on the JSON input
have a javax.validation provider (hibernate-validator for example) on the classpath
put <mvc:annotation-driven /> in your dispatcher-servlet.xml

Resources