Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Servlet vs Beans

I am new to java(learning JSF and other JAVA EE components) and have a very basic question.

Why do we need a Servlet when lot of the things can be done with Beans. What is there in servlet which cannot be done from a Bean or how is using Servlet better than Beans in a web based application.

like image 311
user1433804 Avatar asked Dec 21 '22 21:12

user1433804


2 Answers

With JSF, you're basically already using a servlet, the FacesServlet which you've most likely already registered in the web.xml yourself in order to get JSF to run. It's exactly that servlet which removes the need to write a bunch of servlets to perform repeated tasks such as gathering the request parameters, converting/validating them, updating javabean properties, invoking actions and navigating to the right view.

In JSF you do not need to create additional servlets to perform those tasks. You just create and declare a managed bean as a controller which in turn holds a simple javabean class as model which get bound to UI components in the view.

But sometimes JSF is overkill or too hard whenever one has never learnt JSF before and just want two, three or four web pages with only a contact form. JSF has a relatively steep learning curve, which requires a solid understanding of HTTP servlets as well. With "plain vanilla" servlets and JSP it's then easier to develop. But whenever the site grows out of its borders and you start copypasting/refactoring the common tasks, you'd be happy if you had chosen a MVC framework beforehand.

like image 77
BalusC Avatar answered Dec 27 '22 07:12

BalusC


Beans are used to represent your data. Servlets should be used to control your process.

In the MVC(Model, View, Controller) pattern Beans would be your Model which are data-centric and represents your data, act as the domain objects or simple data structures.

Servlets are the Controller that calls the correct model and dispatches them in the right order. They can be used to get the user requests and translate them into the right input for the Models to operate on.

I know the answer is very high level, but try to read-up on MVC pattern, you will get the idea better.

like image 39
kjp Avatar answered Dec 27 '22 06:12

kjp