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.
Related
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?
Currently doing a group project for college in Java. The assignment is to produce a zero-conf based distributed system. Our group decided on a conference chat application, using client-server architecture. As I joined the group late, a bulk of the code was already completed, and they had decided to develop an MVC architecture for the project. I have experience myself with MVC through Rails development, and can appreciate how handy it is in that context. However, I can't see the benefits of using it the way it has been implemented by my group.
There are two classes for Client and Server, each of which contains methods for sending and receiving datagrams, and fields such as sockets to enable the sending. There are also ServerController and ClientController classes. Each of these classes consists of only one field(a Server and a Client respectively), and all the methods are either wrappers for the public methods of the Server or Client, or simple utility methods. An example would be:
public void closeDownServer(){
server.closeDownServer();
}
To me, this seems completely pointless, and that in this instance MVC has been implemented just for the sake of using a design pattern. Can anyone tell me if there is any benefit to coding the application in this way? Is there any need for these controller classes at all?
The purpose of MVC is to provide abstraction to make later changes easier to implement, and to decouple your components. That might be why you see it as pointless now.... because your application is small and simple. If it will stay that way, then MVC might just be added bloat to your application. But if it's going to grow, MVC might be helpful for future development.
Consider a few cases that might illustrate why you would want to use MVC or an implementation that let model and view access each other directly, without a controller.
What if you need to perform some other actions when "closing the
server" that aren't related to your server class specifically? Where
would you do this?
What if you wanted to change your server implementation to a third party package? Would you rather change your controller code or change
implementation specific code in all your views?
What if you change the database you are using to store application data? Do you want your UI developers worrying about changing code in
the front end to accommodate this?
All of the above situations can be mitigated by using MVC, which will give you the proper separation of concerns and abstraction necessary to make developing and improving/changing code easier.
with a description this deep it is impossible to say if MVC pattern really is valid to your design or not.
But I can say this: there is a pattern far more important pattern than MVC pattern - the pattern of SIMPLICITY: if something in your code is completely useless and doing nothing, GET RID OF IT! There is no point having some class just because of some authority once said so.
Quite often when implementing MVC model, I have seen the controller combined with the view, especially when the app is simple. So you are not alone making this question. Later, if the requirement arises (multiple different views for instance) you can separate the controllers.
The controller means that you can change the behaviour of the view binding to the model (i.e., user input is transformed into the model by the controller). In this context, I'd say that a controller generally isn't needed, since you won't need to change this behaviour in the future.
When developing games and I need to implement MVC, I normally leave out the controller too (it's combined with the view).
I have been handed a large Spring - Hibernate project and have been told to go through the code and figure out how it works.
I have been able to run the project in JBoss and access pages locally, but I have no idea how to figure out how the program is layed out, as I have no web programming experience.
I have been told that it is "pretty simple" and is a "normal Spring-Hibernate project."
Any idea where to begin?
Well, for starters, you'll really need to learn at least the basics of how these frameworks operate. Here's a tutorial on Spring MVC, and here's a Hibernate tutorial.
You'll need to identify the classes that create the various layers; there are certainly going to be Controller classes (which take a web request and figure out how to construct the response) and DAO classes (Data Access Objects, which manage saving and retrieving data).
There will probably be JSP files which describe the views; that is, what the user sees. The HTML code that builds the actual web pages should be here.
My suggestion: pick one simple page and follow it through. Where's the JSP that sets up the HTML for that page? Where's the controller it gets POSTed to? Does that controller call a service class or a DAO? A validator? Etc. -- type in one bit of data and follow it all the way through. It will help to have an IDE that shows you the structure of the application, and allows you to go into debug mode and step through the code.
Good luck!
I am modifying existing java web application that was written long time ago, and it is written in the wrost possible way. It has business logic and sql statemens in JSP files.
Because of the certain constraint, I can not re-design the entire application. but I can implement better design in any new feature that I add.
can anybody suggest me any MVC framework that I could easily integrate in existing app. I need to have framework that is not depended on many external jar files and it does not cause any issues with existing application.
I am modifying existing java web
application that was written long time
ago, and it is written in the wrost
possible way. It has business logic
and sql statemens in JSP files.
Sounds like a good candidate for being thrown away to me.
Because of the certain constraint, I
can not re-design the entire
application. but I can implement
better design in any new feature that
I add.
The entire app needs to be re-designed, but you can't redesign the entire app. It's contradictory.
can anybody suggest me any MVC
framework that I could easily
integrate in existing app. I need to
have framework that is not depended on
many external jar files and it does
not cause any issues with existing
application.
You can't help but cause issues with the existing application, and there will be external JAR dependencies if you use a framework. I'd still recommend it, because a framework will give you a lift that will be worth the extra JARs. Your WAR file will be bigger - so what? Disk space is cheap.
Sounds to me like MVC is the least of your problems. You should be concentrating on the idea of a properly layered application first. If you had well-defined persistence and service tiers you might have a chance.
Think about the problem without worrying about the UI for now. Start with the persistence tier. Get a DAO and model objects going. Then move onto the service tier: transactions, units of work, and use cases implemented using the DAO and model objects. Unit test both layers thoroughly.
Once you have those you're free to concentrate on making the view tier work properly. It'll be easier letting the controllers interact with services. Your UI can be HTML, CSS and JavaScript or Flex. All the logic will be out of the view and into the back end where it belongs.
Don't be afraid of JAR dependencies. It could steer you away from something that will help you. I'd recommend Spring first and foremost. It'll help with all your layering issues. Its web MVC is as good as there is, too.
If you can't re-design the whole application and are concerned about the weight of the framework, then I suggest not adding a framework. You'll end up with a Frankenstein build where the application is inconsistent, and not a lot of benefit.
Instead, why not roll your own? When you add new features (or revise existing ones), you don't have to cram everything into a jsp. Create your own data access layer, and your own business object, and link those to each other and to the UI in your jsps appropriately.
I am in the middle of creating my own custom MVC web framework for a project. This project has very old code base where one JSP page directly submits a form to another JSP whereas the paths are also hardcoded. Now it is a big project and putting Struts or JSF will take considerable amount of time.
So my suggestion is to build a small custom MVC framework and convert many existing page flows into it and also encourage them to develop newer applications using this new MVC frameworks.
I would like to review this with all of you whether it makes sense or we should directly go to the standard MVC frameworks.
My idea
1. Create one front controller servlet which will have URL pattern like /*.sm
2. This servlet reads one config file and creates a map whose key is requestedURI and value is the class name of the command bean.
3. upon intercepting any action request it reads the parameter map (request.getParameterMap()). This servlet refers the already built map, understand whose command bean is to be invoked? Creates an instance of this command bean.
4. pass the parameter map to this command bean and calls execute method.
5. if any exception is found, front controller servlet forwards the request to one global error page
6. if everything is fine, it then forwards the request to the expected URI (by removong .sm and replace it with .jsp)
Do you think I am missing anything here? I know I can make it more fancy by providing error page per request page in the config file or so but those can be done later as well.
I think that you will end up reinventing the wheel rolling your own MVC framework. I know that it is tempting to make your own, since you won't have to get used to a new API but instead create your own and you can more easily adapt it to your specific usecases. But since it seems to be a very long lived application you will have to consider the fact, that your own framework (which may now be state of the art) will be legacy in a couple of years, too.
And that's where adapting one of the popular frameworks comes in handy. The creators of a new framework usually want others to move, too, so they will (or should) offer easy integration or migration options away from the frameworks they think they are doing better (Spring is a good example since it e.g. seamlessly integrates with existing Struts applications and you can gradually move your application without putting the old one into trash). Additionally most current frameworks are very versatile (which can sometimes be a problem since they need more time to get into it) and can be adapted to almost all usecases.
So I would recommend to review the existing solutions carefully (you can learn a lot from their design decisions and errors, too) and only start making your own if none of them matches your requirements.