this is a very noob question. I have a project to do that exemplifies the use of RESTFUL APIs. I am using java spring + MySQL and JSPs for front-end. My question is this. Does HttpServletRequest use REST?
For example, I have one controller with this method in it:
#RequestMapping(value = "/list_events", method = RequestMethod.GET)
public String navigateToEventList(HttpServletRequest request){
request.setAttribute("events",eventService.getAll());
return "listevents";
}
I have the controller class annotated with #Controller. If I swap it to #RestController, it stops working. So, am I using rest in this method for example? And if not, what should I use?
And in my jsp file this is what I have for example:
<c:forEach var="event" items="${events}">
<tr>
<td>${event.id}</td>
<td>${event.title}</td>
<td>${event.description}</td>
<td>${event.type}</td>
<td>${event.date}</td>
<td>${event.location}</td>
</tr>
</c:forEach>
JSP is used when the client needs to display the contents in HTML (web-browser). RESTful web-services used when the client is some other application accepting data responses (it maybe the JavaScript in browser or some other application).
I have the controller class adnotated with #Controller. If I swap it
to #RestController, it stops working.
If you swap it to #RestController the response intended to be JSON, or XML.
You can achieve the same result with annotation #Controller your calss and #ResponseBody on each of the methods (if you need mix of REST and non-REST responses).
What you're doing now is returning the HTML/JSP page to your browser, and it's not a RESTful web-service - it's the first case I described above.
Does HttpServletRequest use REST?
REST means Representational state transfer, and it's architectural style of the application.
HttpServletRequest it's just a requested body from current API. It can be used as either in RESTful or in non-RESTful servces.
Related
html file not returning in the Rest API and return the file name only like 'index' for the following code when used #RestController and working fine only for #Controller.
Here I am using spring boot REST application and index.html with bootstrap
If you know REST web services then you must know the fundamental difference between a REST API and a web application i.e. the response from a web application is generally view (HTML + CSS) because they are intended for human viewers.
REST API just returns data in form of JSON or XML because most of the REST clients are programs. This difference is also obvious in the #Controller and #RestController annotation.
#RestController = #Controller + #ResponseBody
When you use #Controller annotation then it corresponds to MVC workflow in Spring Boot and it renders the view. The key difference is that you do not need to use #ResponseBody on each and every handler method once you annotate the class with #RestController.
#ResponseBody is a Spring annotation which binds a method return value to the web response body. It is not interpreted as a view name. It uses HTTP Message converters to convert the return value to HTTP response body, based on the content-type in the request HTTP header. The content type can be JSON or XML.
It is the expected behaviour of #RestController. The main difference between #RestController and #Controller is #RestController will by-pass the view resolution but #Controller will not.
Technically , it is due to the presence of the #ResponseBody of the #RestController. #ResponseBody will enable RequestResponseBodyMethodProcessor to process the result return from the #RestController method and it will mark that the request has been fully handled within the controller method and by-pass the view resolution process (see this).
I have REST API with Java Springboot 2.1.5.RELEASE and need to prevent every controller to check first the RequestBody contain XSS or not. if yes I want to return like BadRequest. The App only for API no HTML, JSP and etc
Here is sample my controller
#PostMapping("/test1")
public ResponseEntity<ResponseModel> process(#Valid #RequestBody Student request)
I've tried with some library to check Student to Json and clean the XSS like https://github.com/OWASP/json-sanitizer/ and etc
but still, doesn't work
and Already check https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
but still not found about implement in java api
I expect every request to API reject/return 400(BadRequest)
The validation can be on Controller, Filter, Interceptor or Spring Security
It seems like I can do everything that the Controller class do inside Spring Web-Flow, for example decision making and switching from page to page. To my understanding, its the C inside the MVC model. Am I correct about this?
So my question is, is there any advantage to still include a Controller class when using Spring Web-Flow?
If you need access to the request and response, an appropriate design might still include a controller while also having a flow.xml. For example, if you had this code:
HttpServletRequest request = (HttpServletRequest)context.getExternalContext().getNativeRequest();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getNativeResponse();
It's more intelligible to put that in a controller rather than a service.
Also, if you want to register a custom editor, it might make sense to have the controller have this logic in the initBinder() method.
Spring Web Flow uses the Spring MVC framework. The DispatcherServlet handles the request. A FlowHandlerMapping is used to map the request to a particular Web Flow.
Web Flow is to solve the problem involved with controller logic that spans multiple-page navigation (a pageflow, or wizard).
Web Flow can eliminate the need for specialized controller classes to accomplish following a path of page transitions/form updates along a predefined workflow. If you don't need to do this, you can save yourself a lot of configuration/complexity just by using MVC.
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
...
}
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