One or multiple servlets per webapp? - java

I know, it depends on the webapp. But in the normal case, what do you do: one servlet, that serves different pages (like an standalone-application with changing content) or for every page a single servlet.
Take for instance a blog. There is the start-page with the most recent blog-entries, an article-view for displaying one blog-entry and an archive. Do you implement this with three different servlets, or one that is dispatching to the functions. At least a good part of the stuff is shared, like http-headers.
So, what are your experiences, what works best?

Usually you will create a servlet per use case. Servlets acts like controllers for your application. When you identify an interaction from a user then implement a servlet to control that interaction.
That is, if you are using plain servlet/JSP to build the site. If you are using a framework like struts you will find that they implement the front controller pattern and use a single servlet that recieves all the requests and forwards these requests to action classes that implement the actual logic of the user request. this is much harder to do yourself but its a good practice...its the reason why so many people use these frameworks.
So the short answer is, you will create many servlets per webapp since each webapp will expose several use cases.
[EDIT] Re-reading your question it seems as if you are using the term site to mean page or view. Again, it depends on what is happening on that view. For instance, To display the newest blog entry, you can have a servlet that constructs the list of entries from the database for display. If the user clicks on an entry then another servlet can retrieve that single entry for viewing and so on. Mainly, each action is a use case therefore a different servlet.

Most web frameworks use a dispatcher servlet (ex: Spring MVC) that takes care of routing requests to appropriate classes/controllers.
When you start having lots of pages, this approach works best because you have a more user friendly way (in regard to web.xml) of declaring/managing a class that handles http requests and its url. Example (spring mvc again):
#Controller
public class MyController {
#RequestMapping("/viewPosts")
public void doViewPosts(HttpRequest r, HttpResponse res) {
//...
}
}
Besides, having a dispatcher servlet keeps your code flow centralized.

It depends.
In my latest projects, I have implemented a single servlet that delegates to several servlet-like objects which are instantiated in a dependency injection fashion. For instance, I have something like this in my servlet (pseudo-code):
for(Handler handler : handlers) {
if(handler.handle(request, response)) {
return;
}
}
where Handler is an interface with a boolean handle(request, response) method. I obtain my handlers from a container (be it Spring or something even more lightweight).
The reason for this is that I really like dependency injection, and it is difficult to achieve it in Servlets; and I really don't feel much at home with most frameworks that provide web-component dependency injection- I like the simplicity of servlets.
Were not for this, I would go with multiple servlets, although there's a trade-off; either you have an enormous web xml with lots (and lots) of servlet mappings or you have a very complex servlet (unless you use something like my d-i approach).

Related

Converting WebApp into Desktop Application [Java]

I've been writing this very easy Webapp. It receives two parameters, a word and a letter. It counts how many times the letter can be found in said word.
I have a Dynamic Web Project in Eclipse with the following:
OccurencesCounter.java : has the method count with two params: word and letter. it returns the count (amount of times letter found)
OccurencesServlet.java In here I create an OccurencesCounter obj, I get the params, I call the function count etc, and I forwards request/response to result.jsp
result.jsp I show the results I've calculated.
This has been done for an exercice on Parameters and MVC.
According to the MVC pattern, I can change this webapp easily in a desktop application.
I know i need to change my view, result.jsp.
I need a main class. The rest of the code should stay the same.
My question is the following: What do I use the servlet for? I can't fathom how I could still need it.
I think I can use JOptionPane to input my parameters ("HelloWorld" , "o"), but bypass the servlet alltogether. I'd just need the OccurencesCounter class and my main class.
Is this normal? Or should I use the servlet (in some unknown way to me).
I'm confused, as this is an assignment telling me: We only want you to adjust the view when you create a desktop application, as it is requested by the MVC pattern. Make sure you have one model that works for both assignments.
Thank you
A Servlet listens to http requests and executes Java code, if the requests url matches the servlet mapping. This is useful when working with HTTP (server side/web application) but not in a desktop application (event driven).
We only want you to adjust the view (not your class) when you create a desktop
application, as it is requested by the MVC pattern.
They want you to reuse your OccurencesCounter class in both environments. Thats always possible, if that class does not include any kind of technique, related to the environment, for example a Servlet.
Make sure you have one model that works for both assignments.
Actually, you class is not a "model", from MVCs point of view. Its more of a service, that can be called (delegation) by a controller, returning the result (model) and displaying it on any kind of view.
So just create a class with a main method and run your OccurencesCounter class from there.
If you followed the MVC pattern in you web application you should have :
Model : a set of service, dao, and business classes that will be reused in the desktop application
Controller : a set of servlet (or controllers if you used a framework) -> al that is UI related and have to be rewritten
View : a set of HTML, JSP, CSS, etc. -> must be rewritten
The MVC model allows to (almost) easily replace the view part, if you want to migrate from JSP to Velocity or Thymeleaf but still in a web application

Overriding Sling DefaultGetServlet.java

I'm working on a servlet to perform some logic specific to a resourceType in sling and set information to the request to be accessible via the jsp then handing off the request to the jsp similarly to the first solution provided in this answer.
Here's some example code to represent my situation:
#SlingServlet(
resourceTypes="myapp/components/mycomponent",
methods="GET",
extensions={"html"}
)
...
#Reference
private ServletResolver serlvetResolver;
protected void doGet(....) {
setPropertiesToRequest();
Servlet servlet = servletResolver.resolveServlet(resource, "....jsp");
servlet.service(slingRequest, slingResponse);
clearPropertiesFromRequest();
}
Because of this, I've noticed that I've lost sling's selector handling (I've had to roll my own simpler version to determine which jsp to render. Full featured sling selector handling is described in more detail here). I wanted to reach out to the stack overflow community and ask what else I may be missing out on by depriving the default get handler of the request. I've scanned through the source code but I think there may be more going on.
Secondly, I'd be interested in thoughts on how and where this approach may impact performance of the request resolution.
Thanks, Thomas
Processing the business logic in Java and delegating to scripts for rendering sounds like a job for the recently released Sling Models. Using that should remove the need to implement your own handling of selectors, as those won't affect the model selection, only the rendering scripts.
Not sure what you are trying to achieve here, but the main problem seems to me that your SlingServlet handles the html extension and by itself does not have selectors to filter a bit more. Thus it of course intercepts all the requests to your component. Then you have to take care of the selectors again to be able to choose the correct JSP.
The question is, why do you use a SlingServlet for it when you anyway do the rendering by JSP?
Can't you implement your logic in the JSP or better in a bean referenced in the JSP?
In our company we use our custom tag that takes care of this, but there are public frameworks available from other Adobe Partner:
https://github.com/Cognifide/Slice
http://neba.io/index.html

How to create a session cookie in java with path while still having good programming practice of functional programming

I really like functional programming, I like its immutability concepts and also it's no side-effects concepts for functions.
I'm trying to take some of these concepts into java.
Now I have some kind of a servlet which receives a request and if browser did not send a cookie to server then i would like to create a cookie with a certain path to the user.
now inside the servlet i don't want to hold that logic because its common to multiple servlets.
so i extract it into some kind of a cookie manager which will do that:
CookieManager.java.handleCookies(request, response)
Check if browser sent cookie.
If not set cookie with new session cookie value with certain path.
however i don't like it because now the servlet will call the CookieManager.java.handleCookie will have a side effect I would rather it to return some kind of a response and further use it in my servlet wihtout having it effect its parameters that i'm passing into it.
anyone can suggest a solution which would both be elegant, no side effects, and excellent in performance?
thanks
You can make use of servlet filter. It would be well suited for your case. You can map your filter to URL pattern and write your code inside dofilter method. Filters are recommended if you want to have pre and post prcoess of request/response. Since you are doing preprocess for you request it would fit in your case. If is also loosely coupled, because you can remove it, modify it, or add another rule anytime without modifying the core servlet code.
One good solution is to use create a servlet which will act as a parent class for all other servlets.
Now in this servlet put this logic of cookie handling in a common function say handlecookie.
In your get and post APIs of this servlet first call this handleCookie and then service API of servlet (keep this empty)
In al child servlet classes you can only override the service class inherited from the parent class and things should work fine for you
Servlet filters are other solution that you can make use of.

Creating objects from request

I'm working on some user related tasks for a website. For cases when the person is registering or editing a user, they fill out a form and the request is handled in a servlet. At the moment, the servlet is taking all the request parameters and building a User object from them, like this:
User toRegister = new User(request.getParameter("name"),
request.getParameter("lastName"));
There's more parameters but you get the point.
So this sort of code is being reused in a bunch of different servlets (registering, admin adding user, user updating self, admin updating others etc) and it's kinda ugly, so I wanted to clean it up. The two alternatives I could think of were a constructor that takes the request object or a static method in the User class to create and return a new User based on the request.
It's not much of a question since I know they would both work but I couldn't find any sort of best practices for this situation. Should I keep to handling the requests individually in the servlets in case the forms change or should I implement one of the above methods?
DON'T add a c'tor that takes a Request as an argument. You only couple your User class to the Servlet API this way.
Instead use a Web Framework as #skaffman suggests. There are many of these, and it will make your life easier.
EDIT: If you refuse to learn a new framework you can at least use BeanUtils of some similar framework to do the data binding only. I do recommend the Web Framework option though.
Instead of coding all the business logic in the servlet, why dont you use basic MVC framework. Using a framework will make your coding and testing a lot easier.

How to display common information in multiple views in an MVC application?

What is the best way to share common objects between multiple views in an MVC application? Say I have a LoginController that takes a user name and password and authenticates the user and loads their data (account info, full name, etc.). I want to display this on each page - something like a header with "Welcome <user name>, you have <account value> in your account." I don't think I should just store that user object in session. Do I have to return it with each controller?
I'm using the Spring framework for this application, but I don't think that matters. There must be some generic way to handle this common use case.
Update
Not sure if this matters, but I also need the UserID (a primary key returned upon login) as a parameter into other controllers. As this is just another value on the user object returned but not displayed, I would think the answer would be the same as data that is displayed.
You're not really sharing common objects - this is common data (and yes, wrapped by an object). Lets say you have a minimal UserInfo class and a corresponding template fragment that displays it. That fragment will be included in your views.
But regardless of the framework (and how you add this common fragment to your views) the framework/template engine will need to find a 'userInfo' binding and get the required fields.
Unless you are planning on hitting your (db) back-end on every page request to get that information, you will need to cache it. Typically this will be in the session.
If there's quite a lot of logic associated with the common elements, it may be easier to perform a sub-request using ServletRequest.getRequestDispatcher() aka <jsp:include />, then you can go through the whole request processing cycle again with a "Sub-Controller" and "Sub-View".
EDIT: look at Spring MVC HandlerInterceptors
I've handled this exact use case before in a Spring MVC application by having a HandlerInterceptor (Javadoc link) add these details to the ModelAndView for all pages in which I needed it.
Since the whole purpose of a HandlerInterceptor is to be able to have common functionality applied to many requests and/or responses by a single piece of code, this is a natural fit. An Interceptor allows you to hook into either the pre- or post-handle step of a Controller; and you can configure your UrlHandlerMapping to only apply the interceptor to certain URLs (or patterns of URLs) if you wish.

Categories

Resources