Efficiency of JSP calling functions directly - java

Is it a good idea to have a JSP page call my java classes directly or is it better to do an http post to my web service? what is the difference in terms of scalability and security?

JSP has its own responsibility, view generation. Unless required, it doesn't make sense to embed any java code inside JSP. Invoked Servlet/Other framework controller to do business logic.
If the calls are with-in same web application, let us say from JSP1 to JSP2 (or) JSP1 to Servlet2, webservices calls doesn't make sense. They will be heavy.

JSP-Files are used to generate Servlets. So JSP-Files and Servlets are mostly the same. There is no difference for security or scalability.

Related

Java Servlet: structuring a legacy webapp. What framework or technology?

I'm developing a Web app (unfortunately a legacy one) in java (that runs on tomcat) with a very small, but not well organized (at least on this particular project), group and let me start by saying we have not much of experience in servlets programming.
The issue is the folloing.
I'm having kind of a trouble as the amount of servlets keep growing and growing while we implement new functions in this webapp. We don't have a project to follow and structure. Just the clint who randomly asks for new functionality out of the blue.
I would just say our web.xml is a mess. I think we should avoid to pollute the web.xml so much with new servlet every time (right now is about 800 lines and it's becoming hard to maintain), but i'm not sure about what i should do about it.
I'm exploring different possibilities, but we can't afford to explore too much so i would like to hear some idea or best practies from people with more experience than us.
I was thinking that maybe we should use CORBA ore something like that to implenet some kind of RPC. So while grouping common functionalities in a few bunch of servlets we could tame the chaos. Could it be a good idea?
What i have in mind is something like a few servlets that pose as entry points for the requests. I would like to group them by the type of response they give. So for example i have a servlet that serves me json after calling some other class that actually do the job to extract data ore manipulating data. Or again i would have a servlet that serves me files, files that another class or servlet produce. And so on. Am i looking at the problem in the right way?
I took a looked at some framework like DWR (Direct Web Remoting) but we would need to integrate it with a legacy webapp with ugly jsp pages full of scriptlet and we can't afford to jump into full ajax web pages in the limited time we have for the project.
We would need something more lightweight.
The more i search for a solution the more i get confused and overwelmed by the possibilities i find (REST, ORB, RPC, JSON-RPC...), so i ask for your help. Thanks in advance for every answers and tips.
You should definitely look into the Spring framework which is the de-facto standard for Java web development nowadays: http://projects.spring.io/spring-framework/
The Play Framework is also an interesting framework, giving you a Ruby-like development cycle: https://www.playframework.com/
Hello many of your points are valid so you can use new frameworks like spring or struts but it needs huge change over as many new levels will get added/introduced.But if you want to just get ride of many servlets you can/should use MVC architecture like framework in addition to that use a central level controller(a main servlet)-this will just take the request and checks in it (like switch case) as soon as switch case matched that helper class / utility class should called via instance or statically after that the response should also from that helper/utility class and should be sent to the main controller and that main controller will send it to respective jsps/html.

Programmatically Display a web page from a Servlet class

I'm really new to JSP and Servlets and all that jazz, and I'm confused about how to approach it.
Right now my main confusion is as follows:
It seems there are two ways to get a web page to display on the screen in a Java EE/JSP project:
Create an HTML page with the extension .jsp and in the web.xml file, map it to a url pattern (let's assume just /)
Create a Java class that extends Servlet, override the doGET() method to return a string of HTML code and map to this Java class in the web.xml.
My JSP project requires a decent amount of Java code to perform logic and login/logout operations. I've read that it's bad practice to inlcude Java code inside JSP pages as it becomes impossible to reuse, hard to keep track of, messy etc. I want to include much of code in Java, which will feel much more natural for me.
How should I build my project (assuming it's a simple beginner project in which I want to employ the best practices for organization, testing etc in preparation for building a larger project)? How can cleanly deploy web pages from inside Java classes, rather than having many JSP pages containing bits of Java code?
The pattern I've used in the past is to:
1) Write the servlet to perform whatever logic is necessary and to construct a reasonable number of serializable java objects to hold all of the data you want to be rendered via HTML.
2) The servlet stores those objects into the HTTP request and forwards the request and response objects to a JSP:
request.getRequestDispatcher("/some.jsp").forward(request, response);
3) The JSP can access the java objects in the request and merge the data with the static HTML to complete the request.
This is exactly the problem MVC pattern solves.
You do all your complex logic in the Controller (simple Java class, or a Servlet), then pass the data to View (JSP, Velocity, Freemarker, anything that can process the data and make a HTML).
There are several implementations of MVC for Java most popular being Spring MVC and Struts. Alternatively, you can just use your servlet for all your logic and then manually forward the request to a JSP for processing:
request.getRequestDispatcher("/index.jsp").forward(request,response);
If your are looking for best practices in clean separation of java code from the presentation, you might as well use a MVC Framework (Spring MVC or Struts are well know examples) that will help you to cleanly separate :
view layer (JSP)
controller layer
service layer
domain objects
persistence layer
It may be hard to begin with, but you will find nice tutorials through official sites and google.
If you want to only use servlets and JSP, the common rule is to have all logic and Java code in servlets, and that those servlets simply forward to JSP pages that will do the view part. The communication between then is done with request attributes (and of course, session and application context attributes.
Good luck ...
To manage bit of java code, you can use Scriptlet.
Also mentioned in other answers, you can use jsp:forward or response.sendRedirect
to call web pages.
Also see What is the difference between jsp:forward and response.sendRedirect
I'm not sure where you heard that its bad practice to include Java code in the HTML(JSP) files but in order to have a dynamically data driven website, Java is what you would use in the HTML(JSP). Keep in mind, all of your front end design will be in the HTML using JSP, and all of the your logic for handling requests and redirectors and passing data will be managed in the servlets using Java.
Your servlets can pass data, whether it be from a database or other data source, to the front end and your JSP will just help in displaying that data. It's called JSP for a reason. You can write Java in it.
The best approach for designing websites in Java is to use the MVC pattern that way it helps seperate all of the core functions of the site and can easily be scaled and managed.
Do you have any code that you have to show what you have done so far?

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.

Mocking a JSP's post method versus creating an API

I have an requirement as per which I have to call an existing java function which is called from the UI through jsp. Data is provided from a form.
I want to call that function from the java code.
Should I create an API which should be called from the java code, and pass all the parameters required for the java function
OR
create a mock of the form(if its possible) and pass it to jsp.
What is the recommended way?
If your code is within the same Web Application, you may want to get a handle to that JSP via a request dispatcher, then call that with wrapped request/response objects, suitably tweaked to hold just the parameters the JSP needs.
Using HttpClient may lead you to all kinds of issues, as this would go all the way to the network layer (for starters: are you sure that you can connect to your own app from the server? Are you sure you really know the IP/port? Are you sure there's no login or session required? And there's no security filter that makes sure your request comes via the load balancer? And so on on...)
Going with an API (even going to the trouble of having the code exposed as an API with a code change) may look cleaner, though. But then, if you're already using REST or SOAP, then it may not be so difficult.

Java Servlets: Performance

I am working on a web application in Java which gets data from servlets via AJAX calls.
This application features several page elements which get new data from the server at fairly rapid intervals.
With a lot of users, the demand on the server has a potential to get fairly high, so I am curious:
Which approach offers the best performance:
Many servlets (one for each type of data request)?
Or:
a single servlet that can handle all of the requests?
There is no performance reason to have more than one servlet. In a web application, only a single instance of a servlet class is instantitated, no matter how many requests. Requests are not serialized, they are handled concurrently, hence the need for your servlet to be thread safe.
The struts framework uses one servlet for everything in your app. Your stuff plugs into that one servlet. If it works for them, it will probably work for you.
One possible reason to have multiple services is that if you need to expand to multiple servers to handle the load in the future, it is easier to move a seperate service to it's own server than to do it "behind the scenes" if everything is comming out of one service.
That being said, there is extra maintinence overhead if you have multiple servlets, so it is a matter of balancing future flexibility with lower maintainability.
There is as such no performance enhancements in case you use multiple servlets since for each servlet request is handled in a separate thread, provided it is not single threaded.
But keeping modularity and separation of code, you can have multiple servlets.
Like Tony said, there really isn't a reason to use more than one servlet, unless you need to break up a complex Java Servlet class or perhaps implement an intercepting filter.
I'm sure you know that you can have multiple instances of the same servlet as long as you register different nodes in the web.xml file for your app -- ie, assuming you want to do that.
Other than that, from what I'm understanding, you might benefit from comet architecture -- http://en.wikipedia.org/wiki/Comet_(programming).
There are already some implementations of Comet on some servlet containers -- here's one look at how to use Ajax and Comet -- http://www.ibm.com/developerworks/java/library/j-jettydwr/. You should study before deciding on your architecture.
BR,
~A

Categories

Resources