AJAX with Spring MVC - java

What AJAX libraries work well with Spring MVC?
I'm new to developing with Spring and Spring MVC. From the documentation at http://www.springsource.org I'm not yet understanding what AJAX framework Spring MVC has built-in or what third party APIs and tooling might be suggested as working well with developing a Spring MVC application.
All recommendations are appreciated.
I did search through previous SO discussions on this subject, but I didn't get any clear direction.

Spring is super easy to use with Ajax. If Jackson is on the classpath Spring can use it for returning JSON to the caller. Something like this:
#RequestMapping( "/my/path" )
public #ResponseBody MyObject doSomething( #RequestParam Long myVal ) {
MyObject result = new MyObject( myVal );
// do something interesting
return result;
}
Then you can use jQuery (or your other favorite javascript library) to make a request to http://myserver/my/path and handle the resulting JSON object.
Google's GSON is also easy to use. As in:
#RequestMapping( "/my/path" )
public ResponseEntity<String> MyObject doSomething( #RequestParam Long myVal ) {
MyObject result = new MyObject( myVal );
// do something interesting
HttpHeaders headers = new HttpHeaders();
headers.set( "Content-Type", "application/json" );
String json = gson.toJson( result );
return new ResponseEntity<String>( json, headers, HttpStatus.CREATED );
}

Please go through the following link. It clearly explains how it needs to be done.
http://blog.springsource.org/2010/01/25/ajax-simplifications-in-spring-3-0/

Here is another approach to let Spring MVC to work with ZK UI components - Rich Web Application with Spring MVC CRUD Demo
In that article, it used Spring MVC controller to communicate with ZK UI components. (all in Java code)

Spring JS has support of Dojo JavaScript framework.
Spring Js

Spring doesn't deal with Javascript frameworks, per se. I don't know if Springsource does any advocacy for any particular Javascript framework or whether they are agnostic. Ajax is really just a technique enabled by browser technology in combination with the Javascript language and what matters is the ability to pass some kind of serialized data between client and server. It isn't that difficult to cook up your own basic AJAX framework and you could even design your own data encoding and not use JSON or XML. It is wise to adopt an existing framework and standards because you don't want to maintain a lot of ancillary code or worry about it, and instead focus on the problem you are trying to solve. So that is why there are many Javascript frameworks out there that can do asynchronous requests and some have some really nice features and capabilities that make your life easier, for example jQuery provides excellent DOM manipulation and browser-neutral functionality. I think that using Spring MVC in conjunction with the Jackson JSON library on the server side, and jQuery on the client side, is the basis for a very decent end-to-end solution. I have had a lot of success with jQuery and jQuery-UI, but other Javascript frameworks can work just as well. For complex applications, you basically end up needing what amounts to a second MVC on the client side because you need that breakdown between UI widgets and the data that has to move between client and server.

Related

Provide security in Spring

I am developing a basic crud web app in react and spring.
I am Testing with postman, as frontend is not ready yet.
I have this method, but i just discovered that anybody knows the id can send a HTTP request and get all data.
#PostMapping("/utente")
public ResponseEntity<Object> getDatiProfiloUtente(#RequestBody final Long idUtente){
HashMap<String, Object> map = new HashMap<>();
Paziente paziente = service.findPazienteById(idUtente);
map.put("nome", paziente.getNome());
map.put("cognome", paziente.getCognome());
map.put("email", paziente.getEmail());
map.put("nTelefono", paziente.getNumeroTelefono());
map.put("emailCaregiver", paziente.getEmailCaregiver());
map.put("nomeCaregiver", paziente.getNomeCaregiver());
map.put("cognomeCaregiver", paziente.getCognomeCaregiver());
return new ResponseEntity<>(map, HttpStatus.OK);
}
How can I provide security? I want that only the logged user can see his data.
You want to use the #Secured annotation provided by spring security, this article by baeldung is a great resource and explains exactly how to set up the method security you need.
You must use #EnableWebSecurity annotation. Spring boot provides great support for security. Spring can integrate with various third-party security applications as well as provide simple in-memory security.
Here in the original documentation there is a security implementation for a simple memory. I highly recommend you review it.
https://docs.spring.io/spring-security/site/docs/4.0.x/apidocs/org/springframework/security/config/annotation/web/configuration/EnableWebSecurity.html
However, in-memory management is often not useful. Instead, you may want to keep your user information in a database or in a different application.
Other than that, the best practice for Rest is to use jwt tokens. You might want to take a look at this example of how you can use it with Spring Boot.
https://www.javainuse.com/spring/boot-jwt

Spring Webflux: Controller return Mono<ResponseEntity<MyPojo>> vs Mono<MyPojo>

Question regarding return types I have seen with Spring Webflux.
In many examples, like online tutorials, the rest web controller of a Spring Webflux project will return a Mono<MyPojo>:
public Mono<MyPojo> monoPojo(String parameter) {
return WebClient.create("http://...").get().retrieve().bodyToMono(MyPojo.class)
.map(oneMyPojo -> unregisterRepository.insert(oneMyPojo));
}
But I am also bumping into projects where it returns Mono<ResponseEntity<MyPojo>>:
public Mono<ResponseEntity<MyPojo>> monoResponseEntityPojo(String parameter) {
return WebClient.create("http://...").get().retrieve().bodyToMono(MyPojo.class)
.map(oneMyPojo -> unregisterRepository.insert(oneMyPojo))
.map(ResponseEntity::ok);
}
What are the benefits of Mono<ResponseEntity<MyPojo>> over Mono<MyPojo>?
Lets clear some things up
A ResponseEntity<T> is from the org.springframework.httppackage while a ServerResponse is from the org.springframework.web.reactive.function.server package.
This should as a start should give you a hint of when to use what, and where.
But in short, you can use webflux in 2 ways, either by using old fashioned #RestController annotations, with annotated functions for each path. This a sort of "backwards compatibility mode" between regular servlet spring web, and webflux async event driven programming.
ResponseEntities are returned from old spring-web while if you instead opt in to use functional enpoints that exist in webflux, you need to return ServerResponses.
If you look in the code for the classes you will se that they work some parts the same, but other parts differently, especially how they store the body and serialize the bodies.
Handler functions and Filter functions in webflux only work with ServerResponses.
Now to your question, returning Mono<ResponseEntity<T> or Mono<T>.
Well it all comes down to how lazy you are.
If you return a Mono<T> the framework will try to figure out what type of content you have in the Mono, and then create a ResponseEntity accordingly. So if you are serializing it into json, it will set the content-type for you, and set the status usually to 200 OK
While if you wish, you can build your ResponseEntity completely custom, and return any status code, with any body, and any headers etc. etc.
So what it all comes down to is how lazy are you, how much do you want the framework to do for you, and how much to do you want to be explicit, and and type out everything by yourself, or customize.
Me, im lazy, i just return something that works.

REST implementation without HTML code in Java

In many of the tutorial or example I saw. Most people put down the html code right in the java file. I was wondering if there is another way or better practice instead of writing something like this.
#Path("/someExample")
public class SomeExample{
#GET
#Produces(MediaType.TEXT_HTML)
public String sayHtmlHello() {
return "<html> " + "<title>" + "Hello World RESTful Jersey"
+ "</title>" + "<body><h1>" + "Hello World RESTful Jersey"
+ "</body></h1>" + "</html> ";
}
I am new to the webservice and I was wondering instead of above can I do something like return from a html file itself?
If you're looking to return dynamic HTML, you're probably better off using an MVC framework (like Spring MVC), rather than a REST framework. If you want to stick with using the same REST Framework you are using, if you are using Jersey, Jersey has MVC Support
The general idea of how MVC frameworks work, is by using templates and controllers to populate models used in the templates. In pseudo code, you might have something like
template (index.html)
<html>
<body>
<h1>Hello {{ name }}</h1>
</body>
<html>
controller method
public Viewable index() {
Map<String, String> model = new HashMap<>()
model.put("name", "Peeskillet");
return new Viewable("index", model);
}
This is example code that you might use with Jersey (and its MVC support), but using Spring MVC, the concept would still apply, just the classes used would be different.
The basic concept is that you fill the model inside the controller, and tell the framework which template should be used. The framework will take the template, and inject the variables wherever you request them, and then return the converted view to the client.
You should decide on which framework you want to use and read the documentation linked to above for more details. Spring MVC was made specifically as an MVC framework, where Jersey is a REST framework that added MVC support as an afterthought. So you will get more features with Spring MVC. But for basic MVC functionality, using Jersey would work.
As an aside, if you are already coming from an MVC framework (like Spring MVC) background, then you need to shift your thinking a little bit. With REST API (or web services as you call it), normally you won't be sending HTML page responses. Normally it will be a lighter weight data format like JSON. If you are creating a web application that interacts with the REST API, you would normally using AJAX (Javascript) to request the JSON, and it use the JSON data to update the DOM. That's generally how it works.

Java Spring + ReactJs

There is this typical traditional JAVA Spring + JSP application that I am working on. It's a full fledged working application with more than 50 pages. The client feels its slower and wants to make it faster by using ReactJs for new pages. From performance point I understand his concerns. Now I am not a JAVA expert and I am new to ReactJS but i have worked on AngularJs(SPA) applications extensively before.
Right now the way the application works is when we call a url say http://example.com/mycontroller/myaction.do, the app maps the url to certain controller and action in a JAVA controller.
#RequestMapping(value = "/mycontroller/myaction.do", method = RequestMethod.GET)
public ModelAndView myfunction(HttpServletRequest request, HttpServletResponse response) throws IOException {
ModelAndView mav = new ModelAndView("myJSPPage");
mav.addObject("pageDetails", myPageDetails);
return mav;
}
Once the action gets executed the html page is rendered in the browser along with server data and jQuery takes care of the UI part.
Now speaking of ReactJs,
React is just a UI, Lots of people use React as the V in MVC.
Which comes to my questions:
Can i use React in Java JSP Pages and access Java variables in React ?
If not what are other options/ways to use React with these kind of applications.
If its not possible to use React in current application, do i need to write the whole application from scratch using React. What are the challenges i might face?
Yes. Its possible to pass the Java objects and lists to your javascript application using Nashorn which comes bundled with java 8.
Second option is to do the rendering on client and fetch the required data using ajax/websockets.
I believe sticking to using JSP’s along with React won’t benefit you much in terms of performance. Because the main benefit of using SPA’s is that you don’t need to re-render the whole web page when some data changes or when actions are dispatched.
If performance is your main concern then I encourage you to implement a React application (the V) and make Spring your controller (the C) and make them communicate JSON objects (the M (data)).

REST API invocation in Java

Suppose I need to write a Java client, which calls a REST API (with HTTP GET). I know it returns the data in JSON by default and I do not need to supply any headers.
Now I can use either Apache HttpClient to invoke the API or read the URL directly (get a stream from the URL with url.openStream and read the data). The second approach seems to me much simpler. Which one would you suggest and why ?
All the REST clients provide a wrapper over basic java URL based APIs. These clients are easy to use and provide all the necessary functionality. Your code will be much cleaner in case you use Apache HttpClient. And Apache's API are quite reliable.
I would use special libraries for that, like Jersey client or Apache CXF client.
https://jersey.java.net/documentation/latest/client.html
http://cxf.apache.org/docs/jax-rs.html
These ones are part of Java EE standard, a well defined specification which is widely used.
For JSON, consider https://github.com/FasterXML/jackson. Depending on what client you use, you will find information about how to make it work.
If you are not a big fan of JavaEE, and you look for neat and elegant API, and you are interested in working with a language on top of Java, Groovy HTTPBuilder is such a library that works like a charm!
twitter = new RESTClient( 'https://twitter.com/statuses/' )
resp = twitter.post( path : 'update.xml',
body : [ status:msg, source:'httpbuilder' ],
requestContentType : URLENC )
assert resp.status == 200
assert resp.data.user.screen_name == userName
You can use spring-data-rest and Spring's RestTemplate. No need to write a webapp as you can bootstrap Spring easily into a standalone java application putting AnnotationConfigApplicationContext in the Main(). It's quite simple.
For example, suppose you have a Restful URL, http://localhost:8080/croot/books/ that returns a list of books (deserialized into objects of type Book).
Using Spring's RestTemplate you can do the following:
public Resource<List<Resource<Book>>> findAll() {
return restTemplate
.exchange(
"http://localhost:8080/croot/books/",
HttpMethod.GET,
null,
new ParameterizedTypeReference<Resource<List<Resource<Book>>>>() {
}).getBody();
}
You can also process this using spring-data-hateoas allowing you to further decouple the client from the server and helps process what to do next, say in pagination.
This is a very simplified/contrived example but the REST support in Spring 3 combined with the spring-data framework is quite elegant.
Using Spring you also get the advantage of Jackson for JSON processing as the RestTemplate will have one of the flavors of Jackson's message converters (provided through MappingJackson2HttpMessageConverter for example) in it's list of default converters used for processing.

Categories

Resources