Single servlet to handle a single page web application design - java

I have a single page web application designed to look like a desktop application using plain Jsp/Servlet. In the back end I have one servlet with action param being passed for various actions occurs on the single web page. 90% of the requests are ajax. When the functionality grows on the single web page there will be more actions exist under single servlet. Now my questions are
having single servlet to manage a lot of operations a good design? What would be the better design?
What is the performance benefit when having single vs multiple servlet?
Will the servlet code be unmanageable at one point when it grows?
For company policy reasons I can't use the spring mvc..

having single servlet to manage a lot of operations a good design? What would be the better design?
No. A single class having basically all the responsibilities of your backend is not good design. Unless it only serves as a dispatcher to actions, but then you would reinvent the wheel that all the existing MVC frameworks have already invented for years (Spring MVC, etc.). Frankly, I would fight against the "company policy", and use the appropriate tool for the job: Spring MVC, or JAX-RS, or any other modern framework that can be used to easily implement a proper REST backend.
What is the performance benefit when having single vs multiple servlet?
None.
Will the servlet code be unmanageable at one point when it grows?
Yes. You'd better follow the REST principles and assign different URLs to your different actions instead of using a parameter to pass the action. Moreover, all actions should not use the same HTTP method. Searching or reading information should use GET, while creating stuff should use POST and updating stuff should use PUT.
And of course, use one servlet per URL.

you can use jsf
its a single servlet
called FacesServlet
--
jokes aside,
you could use a single servlet, and create multiple classes to handle different scenarios and keep your servlet class under 100 lines of code with good design
but this is essentially writing mvc yourself

REST is the right approach as suggested by JB Nizet. Use JAX-RS for handling the request. In case you don't want to take that route, you can use a single servlet but use the servlet like a controller that send the request to different modules to handle it. Single servlet is fine as long as you don't put all the code in the same class.
In case you use multiple servlets, the design would get better when you plan to move one of the servlets to a different server. But with multiple servlets, the UI (html or java script) needs to handle routing to the right servlet
Code will be unmanageble only if you write everything in one servlet class... If designed correctly it should be manageable.

Related

ATG servlet and Droplet

I'm new for the ATG framework and I want to know different between Servlet and droplet in ATG. I read some tutorials , but still haven't clear idea.
I haven't worked with ATG in a few years, and you may be working with a different version than I did, but a simple way to answer this would be to say that Servlets are more of a J2EE MVC concept, the controller in that case, while Droplets are ATG's "controller". ATG's design patterns aren't exactly MVC (there tends to be quite a bit more logic in the view in most cases), but droplets are meant to be reusable components that the view (your JSPs) use to get data from the model (your xxxManager, xxxService, Repository layer classes, etc.)
For example, if I'm working on a page that is meant to display the shopping cart, I might register a "/Cart" servlet in my web.xml in J2EE. When a doGet is invoked on this servlet, I would call all of the model components I need to gather data about the cart, and use the RequestDispatcher to send that data to a JSP. All of my model/controller logic is done here, and then sent to be rendered by the view.
In ATG, you tend to rely less on web.xml configurations and more on components registered and instantiated by Nucleus. So you might create your cart.jsp and use tags like to grab the data you need ad hoc. You might have a droplet to calculate the current price and display it, or to get promotions applied to the profile and list them. Each piece of data you need for the page, you could use a droplet tag to gather and display.
You might say that droplets tend to be "on page" while servlets are meant to be "between pages."
When you say only Servlet, then that is a generic Java software component that provides a functionality based on a request it receives. A Java servlet needs to run in a servlet container.
Specific to ATG, there are two kinds of components that are termed as servlets - DynamoServlet and PipelineableServlet.
A DynamoServlet is the base class you need to extend to create a Droplet. A Droplet is basically a piece of Java code that you can run on a JSP page running within an ATG application. It is included on a JSP page using the tag that ATG provides. When a JSP executes, it will execute the code within the Droplet and present the output of the Droplet on the page.
A PipelineableServlet is a class (which is part of a chain of classes called a Servlet Pipeline) that provides a functionality when an HTTP request is received. Each servlet in the chain performs a specific operation on the request and relays the modified request to the next servlet in the chain.

Servlet vs REST

I need to create 5 methods on the server side, which will work with binary data. The remote clients are applet and JavaScript. The Client will send files to the server, and the server must parse these files and then return the response as XML/JSON.
So I am confused - is it good practice to use REST-service in this case? Or should I use a servlet?
My colleague told me:
"Creating REST-service that will be used only by one Application isn't
good. REST must be created only when it will be used by many apps. And
REST has some disadvantages over servlet: REST is slower than servlet;
it more difficult to write thread-safe REST than servlet"
However, I see some disadvantages with using Servlet: I need to send a function name that I want to call (i.e. as extra HTTP parameter send function name)
and then inside the doPost method perform the following switch:
switch(functionName) {
case "function1":
function1();
break;
case "function2"
function2();
break;
//.... more `case` statements....
}
In case of REST I can simple use different URLs for different functions.
Also, in the case of REST, it more convenient to return JSON/XML from server.
You are confusing two paradigms here:
REST is a software architecture “style”;
Servlet is a server-side technology.
You can, for example, implement REST-like services using Servlets.
Well,
I wouldn't agree with your colleagues' opinion that isn't good to have rest used by only one application, since you may decide in the future to have different applications using the same rest api. If I were you I would choose the pure REST. Why?
If you're using some framework for rest implementation (let's say apache cxf or jersey) you get lots of stuff out of the box - you write POJO you get a rest, you get serialization and deserialization, to and from let's say, JSON object out of the box (eventually you will need to implement some JsonProviders but this is not a big deal).
It is intuitive to work (if you design your rest APIs well).
Very easily consumable by JavaScript clients (especially if you're using JQuery or something like that)
However, it strongly depends of what exactly do you want to do, if you have some strong transactional logic, the rest could be quite tricky. If you're only going to do POST requests (without using the other HTTP methods) you might want to use the Servlet since you won't have to work with additional frameworks and making more dependencies. Note that the REST is more or less an architectural concept and it does not contradict with the Servlet technology, if you're stubborn enough you can make a rest api only with servlets :-).
Hope I've helped.
First, you're speaking in terms of two different paradigms. It's kinda apples-and-oranges.
REST is a style of service that uses HTTP operations (GET, PUT, etc.) to read and write the state of resources. Think of resources as "nouns" and "things".
Servlet, on the other hand, is a software specification originally provided by Sun Microsystems for connecting HTTP requests to custom Java code. Servlets often speak in terms of method calls: "verbs" and "actions".
Since your question implies that you are looking to deal with input->output methods, just a plain servlet should do the job.
I cannot see any problems on using Jersey and create a REST service. I know that I'm a REST-taliban but it's really simple to implement this kind of architecture using JAX-RS, so... why not?
Your colleagues say: "REST must be created only when it will be used by many apps" but I cannot see how this can be true.Why I cannot create a REST service for a single app?
Sounds like your collegue is applying premature optimisation. If you can write it with a JAX-RS library quickly, do so... If it then proves to be the bottleneck only then do you take the time to rewrite as servlet.
In my experience the performance overhead of JAX-RS is not sufficiently big to justify the development and maintenance overhead of writing the equivalent in servlets directly where the problem maps well to JAX-RS
Depending on your container version, Jersey (or any other JAX-RS implementation) will still use a Servlet for dispatching requests to the appropriate handler.
If your application is truly RESTful, then JAX-RS will do what you want. Otherwise, consider using a FrontController to interpret the Request and forward it to the appropriate handler.
Also, don't confuse XML or JSON with REST. You will get these for free in most (if not all) JAX-RS implementations, but these implementations still delegate content marshalling to other libraries (e.g. JAXB).
Here is the similiar link. he has done it with simple servlet
http://software.danielwatrous.com/restful-java-servlet/

Create a html response when user visits internal URL

When a user hits a particular internal URL I need to return some html that is created dynamically.
Some back end services will be called to genrated a list of keys which is then used to generated a list of html
href links which are displayed to the user.
For this I am considering using a servlet. Is this a good methodology ?
Since servlets have been around for some time maybe there are newer/better ways of implementing this ?
There are tons of solutions, most of them (in Java) being based on the servlet API. If you use Spring already, Spring has a module called Spring MVC, which is a framework based on the servlet API to create web applications, based on the MVC pattern:
Model holding the data from the database
View (implemented, most of the time, using JSPs) generating markup based on the data contained in the model
Controller getting the data from the database, and dispatching to the appropriate view
This is a good pattern used by most web frameworks, but every one has its own way of doing, strengths and weaknesses.
You could do with a simple servlet, but generating markup from a servlet is ugly. That's why servlets are usually used in combinations with JSPs, following the MVC pattern. You could implement a micro-MVC framework by yourself, using only servlets and JSPs, but Spring-MVC and other frameworks offer so many additional advanteges that the investment is worth it. I personally like Stripes very much, and it's very simple.
Servlets are the Java way of exposing simple interfaces for HTTP request.
This can also be achieved by a REST framework like Jersey, but its a bit more complicated, so if you need a simple one opertaion interface, I'd go with servlets.

Java EE 6: JSF vs Servlet + JSP. Should I bother learning JSF?

I am trying to get familiar with Java EE 6 by reading http://java.sun.com/javaee/6/docs/tutorial/doc/gexaf.html. I am a bit confused about the use of JSF.
Usually, the way I develop my Web App would be, Servlet would act like a controller and JSP would act like a View in an MVC model. So Does JSF try to replace this structure? Below are the quote from the above tutorial:
Servlet are best suited for service-oriented App and control function of presentation-oriented App like dispatching request
JSF and Facelet are more appropriated for generating mark-up like XHTML, and generally used for presentation-oriented App
Not sure if I understand the above quote too well, they did not explain too well what is service-oriented vs presentation-oriented.
A JavaServer Faces application can map HTTP requests to component-specific event handling and manage components as stateful objects on the server.
Any knowledgeable Java developer out there can give me a quick overview about JSF, JSP and Servlet? Do I integrate them all, or do I use them separated base on the App? if so then what kind of app use JSF in contrast with Servlet and JSP
A JavaServer Faces application can map HTTP requests to component-specific event handling and manage components as stateful objects on the server.
Sound like what servlet can do, but not sure about manage components as stateful objects on the server. Not even sure what that mean? Thanks in advance.
JSF basically enables you to develop a web application with only model objects (JavaBeans) and views (JSP/XHTML pages). With "plain vanilla" JSP/Servlet you'll have to bring in a lot of code to control, preprocess, postprocess, gather data, validate, convert, listen, etc the HTTP request and response. And then I'm not talking about refactoring it to a high (abstract) degree so that you can also end up the same way as JSF does (just a JavaBean class and a JSP/XHTML page per use case).
I've posted a more detailed answer on the subject before here: What is the difference between JSF, Servlet and JSP?
In JSF uses one specific Servlet (the Faces Servlet) to handle all incoming requests and dispatch them to the appropriate beans.
JSF is a component-based MVC framework, while JSP is a view technology.
You can use JSP with JSF, although Facelets is the preferred view technology.
JSF provide an abstraction layer with several responsibilities, but most important it handles all the messy details of HTML forms and transferring data back and forth between web pages and Java POJO beans (getX, setX methods), which is notoriously difficult to do right.
It also provides navigation and in the latest incarnation in Java EE 6 rudimentary AJAX support is available allowing for simple updates of the web page as the user inputs data.
You might find it easier to think of it as a way to avoid writing JavaScript yourself.
If you like XML choose JSF. In case that you are an actionlistener fan
doPost,doGet etc choose Servlet and JSP.
JSF Framework targets to simplify development integration of web-based user interfaces. As #bozho stated you can mix JSP and JSF. However, the "view" component in JSF is facelets - which can be viewed as little UI widgets, which are more or less self contained with respect to DHTML styling and JavaScript event generation and call back.
"Should I bother learning.. ?"
Not sure. I haven't seen JSF picking up that much steam even though it was around (Atleast in theory) for last 5 years.

When do you use a JSP and when a Servlet? [duplicate]

This question already has answers here:
What is the difference between JSF, Servlet and JSP?
(16 answers)
Closed 7 years ago.
I have an application that sends the customer to another site to handle the payments. The other site, outside of the customer, calls a page on our server to let us know what the status is of the payment. The called page checks the parameters that are given by the payment application and checks to see whether the transaction is known to us. It then updates the database to reflect the status. This is all done without any interaction with the customer.
I have personally chosen to implement this functionality as a JSP since it is easier to just drop a file in the file system than to compile and package the file and then to add an entry into a configuration file.
Considering the functionality of the page I would presume that a servlet would be the preferred option. The question(s) are:
Is my presumption correct?
Is there a real reason to use a servlet over a JSP?
What are those reasons?
A JSP is compiled to a servlet the first time it is run. That means that there's no real runtime difference between them.
However, most have a tradition to use servlets for controllers and JSPs for views. Since controllers are just java classes you can get full tool support (code completion etc.) from all IDEs. That gives better quality and faster development times compared to JSPs. Some more advanced IDE's (IntelliJ IDEA springs to mind) have great JSP support, rendering that argument obsolete.
If you're making your own framework or just making it with simple JSPs, then you should feel free to continue to use JSPs. There's no performance difference and if you feel JSPs are easier to write, then by all means continue.
JSPs: To present data to the user. No business logic should be here, and certainly no database access.
Servlets: To handle input from a form or specific URL. Usually people will use a library like Struts/Spring on top of Servlets to clear up the programming. Regardless the servlet should just validate the data that has come in, and then pass it onto a backend business layer implementation (which you can code test cases against). It should then put the resulting values on the request or session, and call a JSP to display them.
Model: A data model that holds your structured data that the website handles. The servlet may take the arguments, put them into the model and then call the business layer. The model can then interface with back-end DAOs (or Hibernate) to access the database.
Any non-trivial project should implement a MVC structure. It is, of course, overkill for trivial functionality. In your case I would implement a servlet that called a DAO to update the status, etc, or whatever is required.
JSPs should be used in the presentation layer, servlets for business logic and back-end (usually database layer) code.
I don't know any reason why you can't use a JSP as you describe (it gets compiled to a servlet by the containter anyway), but you're right, the preferred method is to make it a servlet in the first place.
There are 2 pretty simple rules:
Whenever you want to write Java code (business logic), do it in a Java class (so, Servlet).
Whenever you want to write HTML/CSS/JS code (view/template logic), do it in a JSP.
Related question:
How to avoid Java code in JSP
JSPs are a shortcut to write a servlet. In fact they are translated to servlet java code before compilation. (You can check it under some tomcat subdir wich I don't remember the name).
To choose between servlet an JSP I use a simple rule: if the page contains more html code than java code, go for JSP, otherwise just write a servlet. In general that translates roughly to: use JSPs for content presentation and servlets for control, validation, etc.
Also, Its easier to organize and structure your code inside a servlet, since it uses the plain java class syntax. JSPs tend to be more monolithic, although its possible to create methods inside then.
JSP's are essentially markup that automatically gets compiled to a servlet by the servlet container, so the compile step will happen in both instances. This is why a servlet container that supports JSP must have the full JDK available as opposed to only needing the JRE.
So the primary reason for JSP is to reduce the amount of code required to render a page. If you don't have to render a page, a servlet is better.
I know this isn't the popular answer today, but: When I'm designing an app from scratch, I always use JSPs. When the logic is non-trivial, I create ordinary Java classes to do the grunt work that I call from the JSP. I've never understood the argument that you should use servlets because, as pure Java classes, they are more maintainable. A JSP can easily call a pure Java class, and of course an ordinary Java class is just as maintainable as any servlet. It's easier to format a page in a JSP because you can put all the markup in-line instead of having to write a bunch of println's. But the biggest advantage of JSPs is that you can just drop them in a directory and they are directly accessible: you don't need to mess with setting up relationships between the URL and the class file. Security is easily handled by having every JSP begin with a security check, which can be a single call statement, so there's no need to put security into a dispatch layer.
The only reason I can see to use a servlet is if you need a complex mapping between URLs and the resulting execution class. Like, if you want to examine the URL and then call one of many classes depending on session state or some such. Personally I've never wanted to do this, and apps I've seen that do do it tend to be hard to maintain because before you can even begin to make a change you have to figure out what code is really being executed.
Most java applications nowadays are build on the MVC pattern...
In the controller side (servlet) you implement business logic. The servlet controller usually forward the request to a jsp that will generate the actual html response (the View in MVC).
The goal is to separate concerns... Thousands of books have been written on that subject.
In an MVC architecture, servlets are used as controller and JSPs as view.
But both are technically the same. JSP will be translated into servlet, either in compile time (like in JDeveloper) or when accessed for the first time (like in Tomcat).
So the real difference is in the ease of use. I'm pretty sure that you'll have a hard time rendering HTML page using servlet; but opposite to common sense, you'll actually find it pretty easy to code even a fairly complex logic all inside JSP (with the help of some prepared helper class maybe). PHP guys do this all the time. And so they fall into the pitfall of creating spaghetti codes.
So my solution to your problem: if you found it easier to code in JSP and it wouldn't involve too many code, feel free to code in JSP. Otherwise, use servlet.
Agreed with all the points above about the differences between JSPs and Servlets, but here are a couple additional considerations. You write:
I have an application that sends the
customer to another site to handle the
payments. The other site, outside of
the customer, calls a page on our
server to let us know what the status
is of the payment. The called page
checks the parameters that are given
by the payment application and checks
to see whether the transaction is
known to us. It then updates the
database to reflect the status. This
is all done without any interaction
with the customer.
Your application is consuming the payment service of another application. Your solution is fragile because if the payment service in the other application changes, that breaks your JSP page. Or if you want to change your application's payment policies, then your page will have to change. The short answer is that your application should be consuming the application's payment service via a web service. Neither a servlet nor a JSP page is appropriate place to put your consumption logic.
Second, along those lines, most usages of servlets/JSP pages in the last few years have been put inside the context of a framework like Spring or Struts. I would recommend Spring, as it offers you the full stack of what you need from the server pages to web service gateway logic to DAOs. If you want to understand the nuts and bolts of Spring, I would recommend Spring in Action. If you need to understand better how to tier an enterprise architecture written in a language like Java (or C#), I would recommend Fowler's Patterns of Enterprise Application Architecture.
Yeah, this should be a servlet. A JSP may be easier to develop, but a servlet will be easier to maintain. Just imagine having to fix some random bug in 6 months and trying to remember how it worked.
In java servlet the HTML tags are embeded in java coding.
In JSP the java codings are embeded in HTML tags.
For big application for big problem the servlet is complex to read,understand,debug,etc because of unreadability of embeding more html tags inside the java coding..So we use jsp.In jsp it is easy to understand,debug,etc.
Thanks & Regards,
Sivakumar.j
i think its up to you?
because
JSP is Java inside of HTML
and Servlet is a Java that can do the HTML inside
hmmm... servlet is more sercure than jsp because if you submit to Servlet and forward to another JSP there is no file extension appear and also you cant see what Page it is..
but the advantage of JSP is you can code there easily.

Categories