use HttpServletRequest in my Spring MVC application? Any benefits? - java

I came across authentication code in my company's java code. The application is a set of several REST services built on Spring MVC. There is a method that gets called in one of the authentication services on the HttpServletRequest object called getHeader(). And the method retrieves an AuthId. Why would they use HttpServletRequest in a spring MVC application? What are the benefits of using this servlet type code in the spring app? What would this method do? Any alternatives?

Spring MVC provides a lot of fabulous abstractions on top of HttpServletRequest, so you can avoid its low-level implementation details. You rarely need to access it directly.
For example, you could get a header value like Content-Type like this:
#GET
#Path("/myService")
public Response doSomething(#HeaderParam("Content-Type") String contentType) {
...
}
But there are times when you do need to access the HttpServletRequest directly--usually when you are using another API that demands it. If you are using some other library with a method you need that takes HttpServletRequest, then you got to grab it from Spring MVC directly.
For example, check out this method in this random UrlUtil class:
public static String encodeUrlPathSegment(String pathSegment, HttpServletRequest httpServletRequest) {
//Get a path segment
}
You have no choice but to grab HttpServletRequest from Spring MVC.

Spring MVC is built on the Servlet API. Anything you could do with a Servlet, you can therefore do with Spring MVC. What the Spring MVC framework provides is a wrapper to code a web application in a specific architectural style. This wrapper adds behavior and some times simplifies tasks.
Why would they use HttpServletRequest in a spring MVC application?
In this case, because it is the most direct way to get the header.
What are the benefits of using this servlet type code in the spring
app?
Spring doesn't have to wrap anything. You get it directly from the source.
What would this method do?
Read the javadoc.
Any alternatives?
In a #Controller class' handler method, you can declare a parameter annotated with #RequestHeader and have Spring pass an argument that it retrieves from the HttpServletRequest headers.
This is, by default, restricted to #Controller methods annotated with #RequestMapping. If your service class is a HandlerInterceptor, Filter, or other type of class and simply has a reference to the HttpServletRequest object, there is nothing more you can do than retrieve it directly with getHeader(String).

Here is an alternative : Spring MVC define the parameter annotation #RequestHeader to read httpServletRequest headers :
#RequestMapping(...)
public #ResponseBody String myMethod(#RequestHeader String AuthId){
//the value of the parameter AuthId is the value of request header named AuthId
...
}

Related

How does Java Spring resolve #Payload annotation? [duplicate]

I created a Spring MVC project using a template that is created from the STS and this is what is generated in the controller:
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, Model model) {
//stuff
}
My question is, how does the locale and model variable get passed into the home method?
Also, what are the possible options for the objects that can be passed to the method?
The general answer is "Spring magic"; however, "Supported handler method arguments and return types" in the MVC chapter of the Spring reference guide has the exact answers to your questions.
The technical answer is through the use of SpringMVC HandlerAdapter mechanism.
By way of spring's DispatcherServlet, a Handler adapter is created and configured for each dispatched request.
I think the "spring magic" in this case is the AnnotationMethodHandlerAdapter located in the spring mvc packages. This adapter basically will be "mapped" to an HTTP request based on HTTP paths, HTTP methods and request parameters tied to the request.
So essentialy when the spring dispatcher servlet identifies a request with path "/", it will check for methods in it's container annotated with the RequestMapping annotation.
In your case it find's it...
Then the real magic begins...
Using java reflection, Spring will then resolve the arguments of your controller method. So in your case the Locale and model will automatically be passed to you. If you included another web like parameter, such as HttpSession, that will be passed to you.

How to encapsulate Model, Principal, HttpServletRequest into single object to be provided as method argument for all Spring MVC controller method?

I am trying to avoid declaring/supplying same set of parameters to Spring MVC controller methods used throughout my application.
These are specific spring related parameters and not domain models/application objects.
These parameters include :
Device, Model, Principal, HttpServletRequest, HttpServletResponse.
Is there a way to encapsulate all these into single object (or probably custom annotation) to supply these to all controller methods?

Angular JS & Spring REST -How to Convert JSON Model object to HttpServletRequest for a legacy app

I need to work on an enterprise legacy Java application that is developed in servlets & jsp's.Planning to convert this legacy app to a Single Page application using angular js & Spring MVC REST.
In the new development, AngularJS will be submitting the model object's (as JSON ) to Spring REST methods.
In the existing application there is a lot of code in servlets and classes (at least 2000 lines in 30 classes) written to get request parameter's using HttpServletRequest i.e., request.getParameter("name");
Is it possible to be able to inject/convert the model (JSON) object submitted by angularJs to Spring MVC REST methods into HttpServletRequest object, so that I need not change all the legacy code & classes?
Not considering to use the #RequestParam annotation in the method signature as the number of parameters are high.
Whatever JSON Object you are defining like below and which you trying to pass backend
var dataToPass={
name:"XYZ",
id:12,
selstat:[12,14]
};
For that, you need to create JAVA POJO with similar name like below
class UIData{
private String name; // Getter and Setter
private Integer id; // Getter and Setter
private List<Integer> selstat; // Getter and Setter
}
And in Spring while defining mapping in controller, you need to use annotation #ResuestBody in argument like below
#RequestMapping(value ='/mappingURL', method = RequestMethod.POST)
public #ResponseBody RsponseObject processData(#RequestBody UIData uiData, HttpServletRequest request)
throws MyException {
// Process you data
}
This will automatically convert JSON object into POJO instance.
Please go through Spring Documentation for more details.
And make sure content-type in header while passing is application/json along with Jackson library added in your dependency.

Is there any framework for performing RPC from javascript to Java bean(spring bean)?

This is the short description of my situation...
I have spring bean BookingServiceImpl which implements BookingService
BookingService has method: RoomDescription getRoomDescriptionById(String roomId);
I also have JSP page with javascript on it
I want to do something like this in javascript
var roomDescription = bookingService.getRoomDescriptionById(222);
/// ... use roomDescription
The question is: is there any existent framework which does things like that (magically allows to cal spring beans from javascript without additional boiler-plate code, assuming all parameters and method results are JSON-friendly)?
Spring provides mechanisms to expose RESTful endpoints via the Web MVC framework
The documentation is very good. A Controller definition for your specific example could look like this:
#Controller
#RequestMapping(value = "/rooms/{roomId}", method = RequestMethod.GET, produces="application/json")
#ResponseBody
public Room getRoom(#PathVariable String roomId, ModelMap modelMap) {
return bookingService.getRoomById(roomId);
}
On the javascript side, you could use jQuery to make an ajax call to retrieve the data. Here is an example of what that could look like:
$.getJSON('http://yourserver.com/rooms/222',
function(room) {
// Do something with room.description
});
This is a basic example (without proper error handling, security, etc). It's the closest thing to an existent framework that I'm aware of for Spring RESTful calls from javascript. If you need to access the Room data on the client side javascript then you'll need to expose it via some Spring construct (e.g. a Controller)
Take a look at DWR. This is as close as you will get to creating js clients.
http://directwebremoting.org/dwr/documentation/server/integration/spring.html

Where to store request specific values in Spring MVC?

I'm using Spring MVC and I want to store request specific values somewhere so that they can be fetched throughout my request context. Say I want to set a value into the context in my Controller (or some sort of handler) and then fetch that value from some other part of the Spring request/response cycle (could be a view, view resolver, interceptor, exception handler, etc)... how would I do that?
My question is:
Does Spring MVC already provide a method to do what I described above?
If Spring doesn't have this functionality, any ideas on the best way to do this (by extending something maybe)?
Thanks!
If you need to pass an object from your controller to view, you can use Spring's ModelMap.
#RequestMapping("/list")
public String list(ModelMap modelMap) {
// ... do foo
modelMap.addAttribute("greeting", "hello");
return viewName;
}
on your view:
<h1>${greeting}</h1>
You could use sessionAttributes.
Session Attributes
I took the latest version of the api (3.1) since you didn't mention your version of spring.

Categories