javabean vs servlet [duplicate] - java

This question already has answers here:
What is a JavaBean exactly?
(23 answers)
Closed 6 years ago.
I was searching for difference between javabean and servlet. I found
Servlet corresponds a Controller
JavaBean corresponds a Model
and
java bean is a reusable component,where as the servlet is the java
program which extends the server capability
Now, what does re-usable means in javabean. Can't we re-use servlet ?
I will appreciate, if anyone can explain this, with few examples.

Servlets and JavaBeans are completely different concepts. The servlet API provides for servicing Internet requests, typically from client browsers but not limited to that.
JavaBeans are a component architecture for encapsulating functionality. A typical use would be a bean used by a servlet to handle database inquiries, but bean architecture is used in lots of places.
Sessions are the servlet mechanism for storing objects related to a particular user, these objects may or may not be beans. Beans used to create user interfaces (with your clever IDE) have more stringent requirements. Beans used in servlets and JSP are typically simpler.
Making it more straight, JavaBeans are to Java what ActiveX controls are to Microsoft. Javabeans can run on server side, client side, within an applet etc.
So, both have nothing in common except Java.

JavaBeans and Servlet are both concepts part of the Java EE (Java Enterprise Edition) package release in 1999/2000.
The servlet is a Java class (used as an Controller) in a java Web Application. Its role is to manage the HTTP Request and generate an HTTP Response. The Servlet is using JavaBeans to get its information from the database for instance.
The JavaBean is a simple java class used to represent the model of your application. To be called a JavaBean, the class must have public getters and setters for all its properties, must have a no-argument constructor, and must be serializable.
It is interesting to understand that this simple JavaBean concept migrates to the Enterprise Java Bean (EJB) in early 2000. But experience proved that EJBs were quite complicated to managed in the Java EE environment. Consequently, Enterprise JavaBeans were mostly replaced by "Pojos" (Plain Old Java Object) popularized by IOC Containers (like Spring in 2003). IOC pulled back Javabean to its former concept. IOC replaced the overall EJB-J2EE Templating pattern, Service Locator, Business Delegate patterns to a simple Injection of Dependencies (DI).

They are two completely different things.
A servlet is used for handling requests in a web application, so yes it is similar to a controller.
A Java bean is any java class that adheres to a set of rules, see: What is a "Java Bean"?
I guess whatever you are reading is telling you how each fit into the MVC pattern

The Life cycle of Servlet manage by Web container where In case of Java Bean you are initialize or initiate your java Bean.
There are two type of servlet, Generic Servlet which support different type of protocol request where HTTPServlet which support HTTP protocol.
In most of the framework like struts/Spring, they use servlet as controller to take the request call and depends on the configuration, it's divert the call to different Action Class/Action Controller

Java bean is a data access object which is used to interact with the database.Java bean is a POJO (Plain Old Java Object).A servlet is used with the JSP, like an interface for JSP.
Both java bean and Servlet are part of the MVC.

Related

How JSF managed bean can be more beneficial than normal Java Servelet [duplicate]

This question already has answers here:
What is the difference between JSF, Servlet and JSP?
(16 answers)
Closed 8 years ago.
In java ee 7 it is recommended to use jsf as default presentation technology. JSP is deprecated as they say.
So to start with jsf i found that it uses managedbean which can handle events and provides data to views. It also manages pages flow.
So my questions are:
is it is really recommended to use jsf model in java ee than what is the use of servlet?
As per my understanding managedbean extends servlet capability at some extent.
If i wanted to use servlet in jsf based app how can i?
Can i use request and response objects in JSF managed bean?
I would like to manually send response based on request and response cycle as Servlet does.
Yes, Java EE started with specific dedicated classes. Only late there came a POJO trend, with the use of annotations. Servlets form the earliest Java EE technology, but they are still very relevant. Also JSF needs a servlet container, providing the servlet related classes, But JSF is less tightly coupled, and there are uses outside the traditional web apps.
The MVC model: beans for Model, JSF for View and servlet for Controller. A servlet might forward to some apt view/JSF after preparing data (beans). For special use cases servlets might be more suited or at least more direct, PDF generation, charts. Not to forget servlet filters.
Let the URL map on a servlet. Annotations might be used. There prepare beans, which you can set and hold in any scope, the request scope being the most light and one-way. Then forward:
request.getRequestDispatcher("/contact.jsf")
.forward(request, response);
Or from the ServletContext:
context.getRequestDispatcher("/context/contact.jsf")
.forward(request, response);
As there are many technologies out there for web-apps, you found a good solid starting point; it might be refreshing also trying other frameworks.

When to use Servlet or #Controller

I need to get a few things cleared up. I have been looking for an answer for this one, but I can't seem to find a good answer to my specific questions (eg. this question was nibbling on the answer: Difference between servlet and web service).
To my understanding, there are different ways you can implement the "request handling", aka "Controller", in an "MVC oriented" web application, two of them being:
A Java specific Servlet (ie. one you create by clicking new ->
Servlet, in eclipse for example), used as a "Controller". This one
extends HttpServlet and you use methods like doGet and doPost etc.
A Spring MVC annotated #Controller class (yes, using a DispatcherServlet). With this one you use the #RequestMethod GET/POST etc.
Now to my questions...
When do you use one or the other?
Are there any general advantages to use one method over the other? (Like, is one method recommended over the other in general?)
[EDIT]: Emphasized keywords
If you're a student interested in learning the language then I would stick with servlets for now. It's possible to write a web app using just servlets but in practice you'll probably want to look at JSP's too.
A JSP is a convenient way to write a servlet that allows you to mix html with scripting elements (although it's recommended to avoid Java code in your jsp in favour of tags and el expressions). Under the covers it will be compiled as a servlet but it avoids you having to use lots of messy print statements.
It's important to have at least a basic understanding of servlets and JSP's. Spring MVC is one of many frameworks built on top of servlets to try make the task of writing a web application a bit easier. Basically all requests are mapped to the DispatcherServlet which acts as a front controller.
The DispatcherServlet will then call the controller whose annotations match the incoming request. This is neater than having to write these mappings yourself in the web.xml (although with servlet 3.0 you can annotate servlets now). But you also get many other benefits that can be used like mapping form fields to an object, validating that object with jsr303 annotations, map inputs and outputs to xml or json etc etc. Plus it's tightly integrated with core spring so you can easily wire in your services for the controller to call.
It's worth noting that there are a plethora of competing frameworks built on top of servlets. Spring MVC is one of the most popular so it's not a bad choice to look into.
A Servlet and a Spring MVC Controller can be used to do the same thing but they act on different level of a Java Application
The servlet is a part of the J2EE framework and every Java application server (Tomcat, Jetty, etc) is built for running servlets. Servlet are the "low level" layer in the J2EE stack. You don't need a servlet.jar to run you application because it's prepackaged with the application server
A Spring MVC controller is a library built upon the servlet to make things easier. Spring MVC offers more built-in functionalities such as form parameter to controller method parameter mapping, easier handling of binary form submissions (i.e. when your form can upload files). You need to package the required jars to your application in order to run a Spring MVC Controller
You should use a servlet when you need to go "low level", and example could be for performance reason. Spring MVC performs good but if it has some overhead, if you need to squeeze out all you can from your application server (and you have already tuned the other layers such as the db) go with a servlet. You can choose a servlet if you want to understand the foundation of the J2EE web specifications (i.e. for educational purposes)
In all the other cases you can/should choose a web framework. Spring MVC is one of them; with Spring MVC you don't need to reinvent the wheel (i.e binary form management, form parameter to bean conversion, parameter validation and so on).
Another plus of Spring MVC is that in one class you can easily manage input from different urls and methods, doing the same in a servlet is possible but the code is more complicated and less readable.
My opinion is that Spring MVC is good for building rest services and managing simple applications (i.e web application with simple forms). If you need to manager very complex forms with Ajax, nested forms, and an application with both session and page state my advice is to switch to a component based framework (like apache wicket for example).
JSF and JSP aswell as Spring MVC builts upon Servlets. The problem this that servlets are not very "nice" to work with because you have to write direct html.
If you are able to use mordern web technologies I would just use servlets in positions that need direct http output like writing an image from a database to http.
Using SpringMVC or JSF which work with a Dipatcherservlet or FacesServlet is just faster and more fun. They parse your files and send it through a servlet.

What is the preferred way to use EJBs and Servlets for web applications?

I am trying to familiarize myself with JavaEE. I am a bit confused as to what the purpose of each "component" (for lack of a better word) is: Session Beans and Servlets, and how they properly interact with a web application (client-side JavaScript).
In an attempt to understand this I am building a simple web application. What is the preferred way to use each component to build something similar to the following:
User visits a "Log in" page
User inputs data and clicks submit. I then send an request with AJAX to log in the user.
The server side then validates the user input and "logs" the user in (returns user profile, etc.)
When sending the request, do I send it to a Servlet (which uses an EJB), or to a Session Bean through WSDL? How do I go about maintaining a "state" for that user using either method? I assume with Session Beans it's as simple as annotating it with #Stateful.
Also, I assume the requests sent from the client side must be in SOAP format. How easy is it to use something more lightweight (such as JSON)? While I would prefer to use something lightweight, it's not necessary if SOAP makes development faster/easier.
The Java Enterprise Edition tutorial address pretty much all of the topics you bring up; what's the purpose with the different kind of bean types, how do I implement web services, how do I implement authentication, etc.
I highly recommend you take the time to build the sample application, especially if you're completely new to the Java Enterprise Edition (Java EE). It is important you build up a good understanding of the core concepts because it can be hard to know what to focus on in the beginning due to the breadth and depth of technologies and standards that comprise Java EE.
One thing to keep in mind is that while Java EE certainly tries to support best practice and enable design and development of secure enterprise applications that perform and scale well, it does not prescribe or limit enterprise applications to follow one particular protocol, data format, and enterprise application design pattern. Some protocols and formats are better supported out of the box by the core framework implementations, and some choices are vendor-dependent, but very few specific technology choices are locked into the specification.
To answer some of your specific questions, Java EE has great support for SOAP, but it does not preference nor limit web services to the SOAP protocol. With JAXB and JAX-RS it is just as easy to develop RESTful web services that accept and return XML or JSON, or both. It's up to you to decide whether you need to use SOAP, REST, or another protocol.
It's also your choice whether you want to use frameworks like JAX-RS or explicitly develop Servlets to handle HTTP requests and responses. In many cases, JAX-RS will have everything you need, meaning you'll be able to implement your web services as plain old Java methods with a few annotations without ever having to bother with marshalling and unmarshalling contents and parameters.
Similarly, with JAXB it's up to you whether you want to use WSDL or not. It's great if you have WSDL definitions, but no problem if you don't.
In many cases you will typically maintain state using the Java Persistence Architecture framework (JPA), and access and manipulate such data through stateless session beans. Developers new to Java EE are often tempted to use stateful session beans to maintain state that is better managed in the persistent storage. The tutorial takes you through the different kinds of bean types and their purpose.
Web services (WSDL, SOAP, etc.) are usually used for communications between applications.
Inside a single web app, you usually make simple GET/POST requests, using AJAX or not, and receive either a full HTML page, or a fragment of HTML (AJAX), or XML or JSON data (AJAX). The browser usually talks to a servlet, but it's rare to use servlets directly.
The usual way is to use a framework on top of servlets. The frameworks can be divided in two big categories : action-based frameworks (Stripes, Spring MVC, Struts, etc.) or component-based frameworks (JSF, Wicket, Tapestry, etc.).
In a n-tier application, all of the above technologies are supposed to only contain the presentation layer. This presentation layer talks to a business layer, where the real business logic happens, where transactions are used to access databases, messaging systems, etc. This business layer is where EJBs are used.
You can create basic architecture as follows :
Create EAR instread two different Project like EJB Jar and Web Application WAR
You can create servlets which will call some delegate class which has logic to reffer the EJB
Either by calling it as remote call/ Either by Using #EJB annotation in the Delegation Class.
ServletClass {
do/post(){
DelegateClass d = new DelegateClass();
d.callMethod(withParam);
}
}
DelegateClass {
#EJB
EJBlocalinterface ejbintance;
void callMethod(DefinPrarm){
ejbinstance.callEJBMethod();
}
}
#Statelss
EJBbeanClass implements EJBlocalinterface{
void callEJBmethod(someParam){
}
}

Why Java Beans have to be serializable?

Is it necessary that a Java Bean implements the Serializable interface?
It's one of the "typical" features as described in the Javabeans specification.
Here's an extract of chapter 2.1 What is a bean?
Individual Java Beans will vary in the functionality they support, but the typical unifying features
that distinguish a Java Bean are:
Support for “introspection” so that a builder tool can analyze how a bean works
Support for “customization” so that when using an application builder a user can
customize the appearance and behaviour of a bean.
Support for “events” as a simple communication metaphor than can be used to connect
up beans.
Support for “properties”, both for customization and for programmatic use.
Support for persistence, so that a bean can be customized in an application builder and
then have its customized state saved away and reloaded later.
And here's an extract of chapter 5.5 Summary of Persistence:
All beans must support either Serialization or Externalization.
In practice, it's not explicitly necessary for it to function. It will in general also just work fine without implementing Serializable. It's however useful whenever you'd like to store them "plain" on harddisk or send "plain" over network. For example when it's a session scoped bean which is to be stored in the HTTP session and the server is been confugured to persist and revive HTTP sessions during shutdown/restart. At any way, whenever you face a NotSerializableException with the bean's full qualified classname in the message, then it's enough sign to let it implement Serializable.
Yes.
By definition - a Java bean is exactly that, a serializable POJO (plain old Java object), with a no-argument constructor and private fields with getters/setters.

What's the deal with web service generation and JavaBeans?

I recently wrote some data access methods (plain old Java) that use immutable objects for both the request objects and the resulting data objects. I like the immutable objects because they prevent a good deal of confusion from appearing in the client code which I've seen in the past when people attempt to mutate and reuse objects.
Anyway, that was months ago. Now a colleague is having trouble with some web service generation stuff (attempting to expose my methods) which expects everything everywhere to be a JavaBean.
My question is: does web service stuff generation stuff always mandate use of JavaBeans? Is there another way?
Most web service frameworks provide some way for you to supply custom serializers/deserializers for types. Sounds like that is what you need here.
If it isn't clear why that's necessary, it is because the framework needs to know how to translate your Java class into XML and vice versa. Serializing and deserializing JavaBeans (classes with get and set properties) is easy if you follow the naming strategy, but you should also be able to supply your custom type serializers for classes that do not follow the bean pattern.
There are two general approaches to Web service development: top-down and bottom-up.
In the top-down approach, a Web service is based on the Web service interface and XML types, defined in WSDL and XML Schema Definition (XSD) files. The developer first designs the implementation of the Web service by creating a WSDL file. From this skeleton Java classes can be created to which the developer can add the required code. This skeleton implementation serves as an interface with the business logic. This process is also one of the J2EE standard - JAX-RPC based API for Web services which defines standard mappings between Java classes and XML types.
In the bottom-up approach, a Web service is created based on the existing business logic in Java beans or EJBs. A WSDL file is generated to describe the resulting Web service interface. Seems like your colleague is using this approach.
I would recommend a top-down rather than a bottom approach as you would have more control on the interface definitions and naming. Also your colleague could use your existing classes through the tooling generated skeleton interface.

Categories

Resources