proper logic of a java servlet interface? [duplicate] - java

This question already has answers here:
Design Patterns web based applications [closed]
(5 answers)
Closed 6 years ago.
I'm coding my first servlet (academic purpose) and I not have clear what is the proper way to do the interface with HTML client.
If the client requests are of many type, like "I want a coffee", "I want a pizza" etc, (actually I think I'll need only login and data send/request) however, how the servlet must handle these? considering that a servlet have only one get/post method.
A) one servlet (serverAddr/myApp/myServlet) that check with a parameter which request is received and call the proper function (with a switch. Don't sound good).
B) a servlet with specific purpose for each request, like "doCoffee" (serverAddr/myApp/coffee), "doPizza" (serverAddr/myApp/pizza) etc.
In this case, I have many servlet that form the web application.
I hope have explained my question, thanks.

You are right : the two solutions (a doGet() methods which handles multiple use cases and as many servlets as usecases) are not good design in a general way.
That's why, since very long time, Java EE applications don't use massively directly their own HttpServlet implementation but use Java EE UI frameworks which allow to have a flexible design in the web controllers.
Behind, a HttpServlet provided by the framework is used but we don't need to worry about it because it's ready to be used. One of their main goal is handling all boilerplate, complex and repetitive code to allow developers to have a flexible way of designing their web applications.
For example, JSF 1 (which is not very recent) allow to use JSF backingbean to map a JSP view to a almost classic Object Java and not a rigid servlet with just a single doGet() method to handle our needs.
In this backingbean, you can add any methods as in a classic java class and you call these methods from your JSP in a Java classic way : myBean.myMethod().
Most of Java EE UI frameworks (SpringMVC, GWT, Struts 2, etc...) allow to do that.

Related

How can I pass errors from service layer to vanilla Java Servlets? [duplicate]

This question already has answers here:
How perform validation and display error message in same form in JSP?
(3 answers)
Closed 1 year ago.
I'm currently using TomEE 8.0.8 WebProfile. I can't use Spring nor anything else besides what's included in TomEE.
I'm trying to implement a 3 tier application. The application has already been implemented in a 2 tier way (Business logic is written in HTTPServlet classes, which call DAOs and then dispatch to .jsp files). I'm having some difficulties trying not to tie up business logic with Servlet implementation details.
All my service classes are Stateless EJB with methods which may take DTOs as parameters and return other DTOs as result.
These service classes should return more than one error if needed (for example: bad length for attr 1, bad format for attr 2, empty attr 3): my idea was to create a custom Exception with a List<> of errors to throw from service layer. However, I don't know if this is approach is correct nor if there is some clean way to handle these exception on the controllers, without "try/catch" everywhere. (Maybe an interceptor? Is it possible with vanilla servlets?)
Your question relates more to design approach rather than implementation, therefore it can have more than one answer. However, in your context of 3-tier application one you are following is:
JSP (client browser) --> Servlet --> EJB --> Database
Which is traditionally used and a sound approach, from that perspective (and this is strictly my view), you can do the data validations in the servlet layer, preferably with a framework like Java Validation Framework. The interceptor approach would also be sound, servlet filters can be leveraged here to provide the validation.

JSP and MVC Best Practices

I am new to JSP programming and am writing a web app for a family member. As I study, I hear a lot about how JSP's are supposed to be used for presentation and servlets are for business logic. My question is basically about how far that goes and when my use of JSTL would be bad practice. Here's an example: I have a login page for my app, and I am using c:if's with custom functions connected to my java classes to process the form. Would that be considered poor MVC practice or, since I'm only referencing my logic code from EL, is this a legitimate use of JSP's?
Your question contains a lot of what are best-practices which invokes a lot of opinion and debate, which is usually frowned upon in this forum. In general, the JSP is the "V"iew in MVC and should be used to present the data provided by the "M"odel which would be your Java code. The "C"ontroller is often scattered between the M and the V (inviting more debate, sorry).
Any logic you put in your JSP that is beyond looking at the data given you and deciding how to present it, moves it towards the Model. Your login page should just collect the credentials and present them to the Model, which should in turn respond with "Invalid" and re-request the credentials (or fail completely) or if valid, move on to the next page.
In practice, IMHO, you should not put a lot, if any, code that manipulates the data except for formatting it - creating table entries, wrapping with links, etc. You should not (IMHO) query databases, perform calculations, etc., in the JSP - let the Model do that.
As duffymo stated, JSPs are old, but they are still valid. I would suggest that you also consider AngularJs (ng) (after reading about the controversy of V1 v. V2).
JSP is an outdated technology and there are very few Softwares that still use it. But if you want to use it I would suggest that you use Oracle Coding Standards with it. This page should give you a clear idea of what you should and shouldn't do with it.
The best practice with JSP - is not to use JSP at all. I’ll try to explain why and be clear.
First I have to explain something that does not have a connection to JSP at all, but it will help you to understand exact problems with JSP technology.
In functional programming there is a term - pure function. It means that it does not have side effects. Additionally, such function does guarantee that for each invocation with the same input it ALWAYS return the same output.
In OOP functions are not pure. It may have side effects. It makes our life more complicated. But what is important is that these side effects can happen only WITHIN your function. You can debug it. More or less it is UNDER YOUR CONTROL.
Let’s imagine our functionality written in JSP as a function f with input I and output O:
O f(I)
The first problem with JSP is that it DOES have side effects AND such side effects can happen not only inside of your function f, but also can affect it from outside. A simple example: you use tiles technology, your jsp page is used as a component in a tiles template. Another component of this template uses getOutputstream() method and writes to this output stream. But an application can either call getOutputStream or getWriter on any given response, it's not allowed to do both. JSP engines use getWriter, and so you cannot call getOutputStream. And you get in your jsp page that works fine when it is alone:
java.lang.IllegalStateException: getOutputStream() has already been called for this response
getOutputStream() has already been called for this response
With a function you get explicitly input parameters. The input is always clear. Additionally you can use constants or, if your function has side effect use another service to get data for processing. But it is always WITHIN your function and more or less under control. With JSP pages you do not have such control at all. Input data can be put into session with different servlets/web components, input data can be put into request scope via servlet with a lot of if statements. You must first investigate a logic of this servlet. It is additional complexity that is not obvious when you create “Hello World!” program, but that really makes you crazy when you maintain such pages, written several years ago.
I think you have already read that mixing both output and logic is not a good idea. JSP allows people to do that. Cause it is “so convenient”.
You cannot test logic within your jsp pages. Or it makes it more difficult.
You can say that correct usage of jsp technology and applying best practices resolve most of issues. Yes. Agree. But it will never get rid of its internal drawbacks and complexity. You always have to check, really developers followed best practices or not? There are better, much better technologies our days.
Note: the only exception, or use case, when I’d personally would use it: for localisation. You do not have get all messages from server. You do not want to ask a server to get a localized string one by one. You do want to get a batch of values, that will be used on your web form, for instance. With JSP + JS you can do that very easily and explicite.

What is the best variable scope I should use in servlet operation

I am working on workflow management system.
Have one separate java class which contains logic method. One of this is:
public static in get_nxt_stg(int current_stg,int action)
{
}
and define static variable cur_stg and nxt_stg. used in servlet. call this method.
When multiple users log in and do some action these variables get not proper value. It seems like it is shared between all user requests.
What is best way to use variable in servlet, which is remain specific for that request?
You should not use static in such a way. If you need to share state, consider using the singleton pattern; but try to avoid static. Unwise use of "static" can turn into a nightmare (for example regarding unit testing).
In addition: it seems that you are a beginner with the Java language. But creating servlets is definitely a "advanced" java topic. I really recommend you to start learning more about Java as preparation for working on servlets. Otherwise the user of your server might have many unpleasant experiences ...
What you are doing is wrong. You should use Servlets only for the purpose of reading request parameters and sending responses. What you are trying to do, should be implemented in the Business layer of your application and if you have it implemented with EJBs, then your problem can easily be solved with an Stateful EJB.

Java servlets vs Java class in webapp

I am quite new to Java/Servlets/Tomcat etc. but have a fairly good understanding of web apps from my days as a CGI/PHP developer.
I have a JSP index.jsp that presents a table from a database.
I have a Results.class that is a normal Java class (not a servlet) that queries a database and returns a string from a method: public static String displayAllResults()
The String being returned is an html table.
So in my index.jsp there is a line that says something like:
String table = Result.displayAllResults();
And then the table is displayed as I'd hoped - All good!
My question is this: is there any advantage/disadvantage to using normal Java classes instead of Java servlets in this manner or should I port all of my classes to servlets for added functionality??
You should really be using MVC frameworks like Spring MVC or struts2. You should always have clear abstractions:
Dao Layer
Service Layer
Business Layer
Model Objects
DTO's
Helpers/Utils
Whenever possible use EL languages like JSTL/OGNL on JSP pages. Never ever use scriptlets. If you use any of the above MVC frameworks, you'd probably never need to use Servlets directly!
Displaying grids with data from database use something like DisplayTag or Jqgrid (with Ajax calls)
It's generally considered poor practice to be invoking Java from a scriptlet in a JSP page. JSP is intended to do HTML formatting, with some extra intelligence around using the Locale and things like that. A better PHP, if you will. Database processing should be handled by a servlet.
I think understanding the purpose of Servlet, JSP, and normal classes will answer your question.
As per my understanding, JSP is used for View purpose, that is, rendering UI to the screen is role of jsp.
whereas, Servlets are used as a controller, whose role is to act as a bridge between your Views and Models.
Normal java classes can act as a Model, here you can perform some core business logic.

It is possible to call a servlet from a Java class?

I'm using IBM WebSphere as my servlet container. My application has several servlets and Java classes. My intent is to call one of those servlets directly from a Java class. Doing some research I figured out that is possible to use the RequestDispatcher interface to achieve this. But it is necessary to pass the objects ServletRequest and ServletResponse as arguments to the method forward(). There is some way to bypass this safely and "nicely"? By "nicely" I meant to say preserving good programming and design patterns.
The only way to do this nicely is to decouple the desired logic from the servlets. This requirement is a sign that the servlets are too tight coupled with business/domain code logic which apparently needs to be used as well outside the webapplication context.
Refactor the original servlet code into reuseable Java class(es) and method(s) (which in turn does not use anything from the javax.servlet package) so that you can finally import and invoke it from both the servlet class and the "plain vanilla" Java class.
It would help to get some more background as to why you are trying to do this. I am assuming you want to invoke some piece of business logic in the servlet. This is a sign that the application is poorly designed.
Are you familiar with MVC architecture? If your "model" code was loosely coupled, you would be able to call it directly.
You could write a filter that stores the current request and response in static ThreadLocal, so that you can use them later from within the same request. You can then implement your own static method forward that uses them and dispatch to another page.
This is somehow the approach taken in JSF where FacesContext.getCurrentInstance can be accessed anytime.
But I wouldn't qualify that as an elegant design. Rather try to follow #BalusC advice and refactor your logic.

Categories