Using java beans in AJAX - ajax

I am asking because I have only seen java beans used with a framework like struts or JSF.
Is it possible to send and access a java bean over an AJAX request?
Servlet myServlet creates and fills a java bean instance, and sets it in the request scope. An already loaded jsp/html page uses AJAX to request data from myServlet. Can this bean be accessed in any way? After thinking for a while, I have come to accept that this cannot be done.
If it can't be done, what would be the best practice when trying to transmit data from a model (i.e. user information from a database) asynchronously to a client when using Tomcat/Servlets and JSP?

It's technically possible if you serialize the javabean to a byte array or even a base64 encoded string using the usual Java Serialization API.
But how would it ever make sense to use a proprietary format to transfer data around? How would non-Java clients (e.g. JavaScript!) ever be able to consume the serialized Java object? These days XML, JSON and even CSV are much more widely supported and accepted. Practically every self-respected programming language has tools to easily convert between XML/JSON/CSV and the model as definied in the programming language in question. E.g. Java has JAX-RS API to easily convert between javabeans and XML or JSON. JavaScript has —obviously— builtin support for JSON (guess what "JS" in JSON stands for).
To learn and play around with the basic concept, head to this answer: How to use Servlets and Ajax?
To learn about the advantages of JAX-RS over servlet, head to this answer: Servlet vs RESTful

You can still use struts or jsf as you would normally to construct markup(html). And then consume the markup that was constructed via ajax and then append to the dom. If you are familiar with jQuery, something like jQuery('#selector').load('actionUrl.action');
But if you are looking to examine a java bean, then you will have to serialize it to xml or json. If you are using a web framework like struts2 or spring, there is likely a mechanism for doing this serialization for you. If you want to edit the bean you will have to serialize, then edit the serialized bean, and then deserialize back to the java bean.

Related

What's the bare minimum topics to cover from JSP and Servlet to learn SpringBoot?

So I Want to build projects using spring Boot directly as I'm under a bit of time crunch. Please help me out.
What you need to know about JSP: nothing. JSP is old and clunky, use Thymeleaf instead. But if you're building single page web apps you don't need any templates, you just need to know how to accept and return JSON.
Servlets: you need to understand the threading model, that there's only one servlet being traversed by multiple threads, and any instance variables will be accessed by all the http request threads. More than servlets you need to know filters, because Spring Security uses them.

Is is recommended to use JSON Schema Validation in the place of Bean Validation JSR303 for Spring Boot Rest APIs?

Can we use JSON Schema Validation in the place of Java Bean Validation JSR303 for Spring Boot Rest APIs for Enterprise Applications? Which one is more efficient to validate request Payload to Spring Boot Rest APIs?
(i.e. performance wise, cross-validation wise and RegEx pattern based validation)
It is a good question and there are no definitive answers for it as, perhaps, it is dependent on the application domain and remains subjective to that. At the base level (which usually covers 90%) of all use cases of validating user input to the REST service, both have the equivalent facility to validate data adequately. Both support constraints which can be used to achieve the same result.
However, on one front Bean Validation stands out is its ability to define custom validators, which can be used to validate very specific domain/application dependent constraints. For example, if there is case where a class which has 3 attributes (say, A,B and C) and a constraint is required that is either A occurs or B & C occurs but not both, then it is not really possible to put a constraint in JSON schema directly, it has to be handled through design of the schema (similarly in XML, actually it is more complicated with XML).
On the other hand in Bean Validation a custom validator can be written to handle this situation quite easily.
However, these kind of cases are few and far between.
Another point to consider is the integration of the Bean Validation in the underlying framework e.g. Spring, Jersey, RESTEasy etc., JSON schema validation is not yet integrated in the frameworks.
Therefore, given the support for the tech, it is perhaps better to stick with Bean Validation 2.0 and leverage the underlying frameworks capability to validation (this is, however, purely my view).
From an application development prospect, Java bean validator is sufficient for the business needs. From a system integration point, JSON schema externalizes the business rules and provides a platform independent interface control. So if your system involves many subsystems, JSON schema gives a better way to verify message payload.
I prefer OpenAPI Specification, which can be regarded roughly as a JSON Schema dialect, to bean validation 2.0 (JSR380).
OpenAPI is the de-facto (correct me) standard to describe RESTful API today. There are tools for validation accroding to OpenAPI spec is available, an incomplete collection can be found at here. And of course it works well with Java/Spring.
OpenAPI validates JSON string rather than a POJO, thus it can handle the following case naturally while bean validation in Java cannot: say i want to validate the object in the request body of a PATCH request, and the object must have a property named A, while the value of A is can be null;
And there are more than validation you can do with an OpenAPI spec in your hand. Because an OpenAPI schema does not only define what the data model of RESTful API looks like, it also describes other aspects (endponts, parameters and status code etc.) of the API in the same file. Out there are a bunch of code generators to auto-generate server-side or client-side code to serve requests or retrive response in whatever language.

Command objects and DTOs, difference?

When we speak of command objects in Grails and even in Spring, are they the same as data transfer objects? Meaning, is a command object an example of the implementation of the DTO enterprise design pattern? If not, what is the difference?
A data transfer object (DTO) is an object (simple java bean) that carries data between any two layers or processes. You might generally introduce/use DTO layer & populate the DTO bean with the data received from an external web service or external system. Refer Martin Fowler's blog on Data Transfer Object for more details
Command object is just a spring (mvc) terminology which maps the html form data to a java bean (form bean). Here Spring Dispatcher servlet & helper classes map the data from html form to the java bean. In Grails, command objects do serve more than data carriers like AST transformation.
In summary, they both are data carriers from one layer to the other.
Is a command object in Spring an example of the implementation of the DTO enterprise design pattern ?
Yes, but the point to note is that the Spring Dispatcher servlet &
helper classes populate the command object with html form data.

Spring mvc - get data from other server, what object to use and how to reuse it?

I have some url that I need to read data from there and use it in my controller.
Usually in java application I use http client, to get data from some url.
My questions are:
What object to use in spring mvc to get data from some url (like http client) ?
How to reuse this objects, so every time not to create it ?
Thank you!
In agreement with the comment by #Evgeny and #Beau above, you can use any client library you like. HttpClient is VERY bean friendly and, for cases where it might be difficult to construct the configuration, you can always provide a Spring factory bean to construct the object.
If you are looking to abstract away the plumbing of the HttpClient API usage, utilize the RestTemplate suggested by #Evgeny (I believe that it is also his brainchild) It is a VERY rich and simple API to leverage.

A heavily customized Spring Web application and the dispatcher servlet

We have a web application that uses spring, struts and camel right now and there is a lot of customization we have done to allow us to know when beans are added to the context.
So, we have gotten to a point where we would like to remove struts from the application, because we are only using it to handle actions and we figure we could either use spring or camel to do the same thing. So I was able to get it to work with camel/velocity, but we didn't like how we really couldn't use the request object directly in the jsp (afaik, you have to put everything in the header of the Exchange and in the jsp you would do ${header.someReqVariableName}).
So we wanted to go the spring route, but since we load the context.xml directly, we have a provider that extends ContextSingletonBeanFactoryLocator and we pass the xml file name as a param, we haven't been able to figure out how to get the DispatcherServlet to work without giving it another configuration xml.
Is there a way to either:
Have camel use jsp for processing a jsp (and have all the usage of jsp tags)?
or
Have spring to see that a context has already been loaded and use that instead of having another new one?
or
Something better I have thought up?
You can use camel-jetty to expose HTTP endpoints, but I wouldn't use it for any complex web app development (JPS, etc). I'd use use Spring MVC (or similar) and use Camel for any complex routing/messaging requirements...
Here is another way, you can use the producer template to send the request to the camel context if you can get the reference of the camel context from the spring.

Resources