General session handling in java - java

I work with multiple languages like PHP, C, JAVA etc.
I am trying to fully understand how session is implemented in java.
Question : In php I can create a session and use the session in any class even utility classes. In Java why session is meant to be handled normally only in servlet classes? why not in any basic POJO classes without actually passing session or context object ? (I know other classes can, using complex techniques, but why not easily as servlet or as in other languages ).
I do know that the correct way to do things is use session in Servlet to retrieve object/values and pass object/values to other utility classes and get results.
Please let me know if there is in fact an easy way to get session in basic POJO classes.

I had flagged to delete this question as I found the answer in another SO link Retrieving Web Session from a POJO Outside the Web Container . Since it has not been deleted till now , I am answering my own question.
What are servlet and why we use them ?
A Java servlet is a Java program that extends the capabilities of a server.
Although servlets can respond to any types of requests, they most commonly implement applications hosted on Web servers.
Such Web servlets are the Java counterpart to other dynamic Web content technologies such as PHP and ASP.NET.
More information about java servlet at the link https://en.wikipedia.org/wiki/Java_servlet
Servlet vs POJO/normal Java classes ( why session access only in servlet ?)
A servlet class too is a java class. Servlet is a java class which comply servlet specification, so that it can be run in a server. Java class not required to comply Java Servlet API
A servlet container (e.g. Tomcat) is designed to be able to recognise servlet classes and, if configured correctly, treat them in a particular way. There's nothing magical about this - you can always write your own application that can treat any type of class in a specific way - but there's a standard that all servlet containers follow that means you can write a servlet class and know how it will be used.
Java was designed to be a platform independent language to create software to be embedded in various consumer
electronic devices. Soon it was apparent that the Java can be used in client/server programming environment because of its inherent portability. Hence servlet and applet were introduced in java. Java applets helped create dynamic, self-executing program on client side. Java servlet is a small program that executes on the server. Just as applets dynamically extend the functionality of a web browser, servlets dynamically extend the functionality of a web server.
Since servlet part of java is used in server side programming , this has access to session. POJO classes are also used in server side programming but code which uses session is usually written in servlet.
POJO Vs PHP classes(server side)
Java is used in many development environments like desktop,mobile,embedded and Web. PHP is a server-side scripting language designed for web development.It can also be used for general purpose programming but I am limiting the discussion to class used in php in server side programming(ie .php pages). So it is better to compare php classes in php pages with servlet/JSP - server side development part of JAVA.
Again servlet puts html code inside Java code. JSP puts java code inside html code. So JSP in java is more comparable to PHP .
If we understand this then we can infer that there is no good reason to compare POJO in java to PHP classes (server side). It is like comparing applies to oranges. if you are interested in comparison between php and jsp please visit http://www.withoutbook.com/DifferenceBetweenSubjects.php?subId1=57&subId2=2&d=Difference%20between%20PHP%20and%20JSP
In modern web development we use template engines ie instead of JSP we use servlet with template engine(Freemarker,Velocity). PHP has its own template engines.
How to access session in POJO classes ? Why it is hard / Is there any easy way ?
First of all it should not be done as it would be a bad programming practice. Secondly it can be done but there is hardly any scenario where this would be necessary. Since there is no need for the same the ways to implement it are not easy.
It should not be done , If you have to there are two ways.
We can pass session and request objects from servlet to POJO classes(via methods or constructors).
Store the request in a ThreadLocal in a Filter (and clean it afterwards)
Also look at the SO links for sample code
get HttpSession|Request from simple java class not servlet class
Retrieving Web Session from a POJO Outside the Web Container
I asked this question when I was stuck at a particular scenario . I used to program in PHP and wondered why I never had the issue there and got confused. People who usually move from php to java , also have a hard time understanding the how it all works , so attaching one more part to the answer.
Why servlets require servlet containers like tomcat while php runs on a http server/webserver (Apache).?
The question is incorrect in assumptions made but the answer will highlight why .
A web server is software that helps to deliver web content (web pages) to the clients (e.g. web browser)
through the Internet using HTTP protocol. HTTP is a simple request /response protocol underpinning most web
applications on the Internet, regardless of whether they are written in Java. An HTTP request can correspond to
one of the seven HTTP methods: GET, POST, HEAD, OPTIONS, TRACE, PUT and DELETE
The server side technologies like JSP/Servlets, ASP, and PHP etc. will require their software libraries to be installed
at the server. Without these libraries a web server won’t be able to execute those server technologies and is just an HTTP Server.
An HTTP server can handle HTML and other client side technologies which don’t require any server capability.
The Apache HTTP Server is an example of an HTTP server.
Regarding Servet/JSP : Servlet can be run on a servlet container.Tomcat is normally called a servlet container.A Servlet container is basically a web server for Java Servlets and JSP pages. Tomcat has an HTTP listener inside it, but in addition to that it has a servlet/JSP engine. A servlet, in the end, is a Java class. JSP files (which are similar to PHP, and older ASP files) are generated into Java code (Servlet), which is then compiled to .class files by the server and executed by the Java virtual machine.
Regarding PHP : PHP will not work in pure Apache or any HTTP server. We are able to run php in apache because it is linked to Apache(SAPI - server API) Using mod_php5.so(or similar) modules. We do not normally start any php daemon. Apache starts the php interpreter along with itself.
If oracle wants, it can develop a module similar to PHP module which will make it easier to host Java code on an HTTP server. But using a servlet container model has many benefits compared to the PHP interpreter model even with the disadvantage of increase in complexity.

From Servlet class pass session to any helper class(Create HTTPSession as helper class propertiy).
Now in your POJO class get session from helper class that you have set previously from servlet.

Question : In php I can create a session and use the session in any
class even utility classes. In Java why session is meant to be handled
normally only in servlet classes? why not in any basic POJO classes
without actually passing session or context object ? (I know other
classes can, using complex techniques, but why not easily as servlet
or as in other languages )
Every language has its own design & structure. There is no universal session handling protocol that it should be handled the same way in all the server side languages. In java if handling session in controllers i'e servlet setting & getting attributes serves your purpose why would anyone want to get a session object in a POJO. You can save a POJO in a session in a servlet.
Besides if there are exceptional out of the norm requirements you can always write custom code.

Related

PHP equivalent of Java Servlet

I am trying to understand what's the correspondent of servlets and applets in PHP but I don't have much experience in JAVA.
I want to know what is the equivalent of Java Servlets and JSP in PHP ?
In Java the Servlet delivers the web page to the client. In PHP there are multiple web server which delivers the same functionality:
Apache2
NginX
lighttpd
The PHP script is similar to JSP. It was designed to be used as template.
However overtime PHP was used more and more also not only for templates. In the last year there are appearing new approaches where PHP is used to write an entire web server. E.g.
appserver.io
reactphp
I think the equivalent of Java Servlets and JSP is PHP.
Taken from Wikipedia - https://en.wikipedia.org/wiki/Java_Servlet:
"The servlet is a Java programming language class used to extend the capabilities of a server. Although servlets can respond to any types of requests, they are commonly used to extend the applications hosted by web servers, so they can be thought of as Java applets that run on servers instead of in web browsers.[1] These kinds of servlets are the Java counterpart to other dynamic Web content technologies such as PHP and ASP.NET."

Sending an XML file to a seperate application; JSP or Servlet? JAVA

I have been researching into what type of Java web application I will need to create to carry out this use case activity:
Oracle CRM sends http request with GET variables
System uses GET variables in Oracle SQL query
System sends back XML file with SQL results to CRM via HTTP.
From what I have read so far there is two variations of JAVA that are web applications; those are JSP and Servlet.
Assuming I am not using any frameworks like Spring. What is the best way to implement this as a JSP application or Servlet.
Or is there other Java alternatives.
FYI: I am not a JAVA programmer, this is an introductory (in the deep end of the pool) project.
Thanks
Yes, in your case you only need a Servlet. And yes JSP is only for presentation layer. Although you can have business logic in JSP too because JSP ultimately gets converted to a Servlet in the backend but that's a bad practice not to be followed. :)

Java application vs web service vs web application

I am developing a multi-platform (Android, iPhone, Windows and Blacbberry) mobile application. The application needs to communicate with our server for several tasks, such as retrieving buddy lists etc. The server interacts with data that is stored in a MySQL database. I intend to code the server element in Java, however I am confused by all the different types. So far, I think I have narrowed it down to three options:
1) I code the application using Jetty to accept http posts. I post XML to the server, handle it, interact with the DB and post a XML response back. I would save the application as a jar and leave it running on my server.
2)I develop a Java web service. REST/JSON/SOAP?
3)I develop a Java web application.
Whilst there are many questions already out there asking what the differences is, I am struggling to find a clear explanation as to what is the best approach in which situation. I have previously used the first approach but am assuming the second approach is the better option, I'm just not sure what the advantage is.
your 1-3 options are all variants of a "Web application".
Jetty is a Java based http server/servlet container. If you want to communicate between client and server using http, you are using an http server (although not necessarily Jetty).
A Web Service is part of a web application that conforms to a standard around how clients communicate with the server, and how the server offers up information to the clients.
A web application is a Java application that makes it services available over http.
So if you want to have your clients communicate with a server, and store info in a db, you are using a web-application.
I would recommend going with option 2 as it is more lightweight and can be parsed directly in you're web application. XML got more overhead and must be translated, while you can just serialize objects directly to JSON from you're Java application and then parse them in javascript at frontend

What is Java Servlet?

I read many articles to understand Java servlet but I did not succeed.
Can you please give brief introduction of Java servlets (in easy language). What is a servlet? What are the advantages?
I can't understand the difference between server-side programming languages (PHP, ASP) and servlets.
A servlet is simply a class which responds to a particular type of network request - most commonly an HTTP request. Basically servlets are usually used to implement web applications - but there are also various frameworks which operate on top of servlets (e.g. Struts) to give a higher-level abstraction than the "here's an HTTP request, write to this HTTP response" level which servlets provide.
Servlets run in a servlet container which handles the networking side (e.g. parsing an HTTP request, connection handling etc). One of the best-known open source servlet containers is Tomcat.
A servlet at its very core is a java class; which can handle HTTP requests.
Typically the internal nitty-gritty of reading a HTTP request and response over the wire is taken care of by the containers like Tomcat. This is done so that as a server side developer you can focus on what to do with the HTTP request and responses and not bother about dealing with code that deals with networking etc. The container will take care of things like wrapping the whole thing in a HTTP response object and send it over to the client (say a browser).
Now the next logical question to ask is who decides what is a container supposed to do? And the answer is; In Java world at least It is guided (note I did not use the word controlled) by specifications. For example Servlet specifications (See resource 2) dictates what a servlet must be able to do. So if you can write an implementation for the specification, congratulations you just created a container (Technically containers like Tomcat also implement other specifications and do tricky stuff like custom class loaders etc but you get the idea).
Assuming you have a container, your servlets are now java classes whose lifecycle will be maintained by the container but their reaction to incoming HTTP requests will be decided by you. You do that by writing what-you-want-to-do in the pre-defined methods like init(), doGet(), doPost() etc. Look at Resource 3.
Here is a fun exercise for you. Create a simple servlet like in Resource 3 and write a few System.out.println() statements in it's constructor method (Yes you can have a constructor of a servlet), init(), doGet(), doPost() methods and run the servlet in tomcat. See the console logs and tomcat logs.
Resources
Look how the HTTP servlet looks here(Tomcat example).
Servlet Specification.
Simple Servlet example.
Start reading the book online/PDF
It also provides you download of the whole book. May be this will help.
if you are just starting servlets may be it's a good idea to read the material along with the servlet API. it's a slower process of learning, but is way more helpful in getting the basics clear.
In addition to the above, and just to point out the bleedin' obvious...
To many this is hyper obvious, but to someone used to writing apps which are just run and then end: a servlet spends most of its time hanging around doing nothing... waiting to be sent something, a request, and then responding to it. For this reason a servlet has a lifetime: it is initalised and then waits around, responding to anything thrown at it, and is then destroyed. Which implies that it has to be created (and later destroyed) by something else (a framework), that it runs in its own thread or process, and that it does nothing unless asked to. And also that, by some means or other, a mechanism must be implemented whereby this "entity" can "listen" for requests.
I suggest that reading about threads, processes and sockets will throw some light on this: it's quite different to the way a basic "hello world" app functions.
It could be argued that the term "server" or "servlet" is a bit of an overkill. A more rational and simpler name might be "responder". The reason for the choice of the term "server" is historical: the first such arrangements were "file servers", where multiple user/client terminals would ask for a specific file from a central machine, and this file would then be "served up" like a book or a plate of fish and chips.
What is a Servlet?
A servlet is simply a class which responds to a particular type of network request - most commonly an HTTP request.
Basically servlets are usually used to implement web applications - but there are also various frameworks which operate on top of servlets (e.g. Struts) to give a higher-level abstraction than the "here's an HTTP request, write to this HTTP response" level which servlets provide.
Servlets run in a servlet container which handles the networking side (e.g. parsing an HTTP request, connection handling etc). One of the best-known open source servlet containers is Tomcat.
In a request/response paradigm, a web server can serve only static pages to the client
To serve dynamic pages, a we require Servlets.
Servlet is nothing but a Java program
This Java program doesn’t have a main method. It only has some callback methods.
How does the web server communicate to the servlet? Via container or Servlet engine.
Servlet lives and dies within a web container.
Web container is responsible for invoking methods in a servlets. It knows what callback methods the Servlet has.
Flow of Request
Client sends HTTP request to Web server
Web server forwards that HTTP request to web container.
Since Servlet can not understand HTTP, its a Java program, it only understands objects, so web container converts that request into valid request object
Web container spins a thread for each request
All the business logic goes inside doGet() or doPost() callback methods inside the servlets
Servlet builds a Java response object and sends it to the container. It converts that to HTTP response again to send it to the client
How does the Container know which Servlet client has requested for?
There’s a file called web.xml
This is the master file for a web container
You have information about servlet in this file-
servlets
Servlet-name
Servlet-class
servlet-mappings- the path like /Login or /Notifications is mapped here in
Servlet-name
url-pattern
and so on
Every servlet in the web app should have an entry into this file
So this lookup happens like- url-pattern -> servlet-name -> servlet-class
How to "install" Servlets?
* Well, the servlet objects are inherited from the library- javax.servlet.* . Tomcat and Spring can be used to utilize these objects to fit the use case.
Ref- Watch this on 1.5x- https://www.youtube.com/watch?v=tkFRGdUgCsE . This has an awesome explanation.
Servlet is server side technology which is used to create dynamic web page in web application. Actually servlet is an api which consist of group of classes and interfaces, which has some functionality. When we use Servlet API we can use predefined functionality of servlet classes and interfaces.
Lifecycle of Servlet:
Web container maintains the lifecycle of servlet instance.
1 . Servlet class loaded
2 . Servlet instance created
3 . init() method is invoked
4 . service() method invoked
5 . destroy() method invoked
When request raise by client(browser) then web-container checks whether the servlet is running or not if yes then it invoke the service() method and give the response to browser..
When servlet is not running then web-container follow the following steps..
1. classloader load the servlet class
2. Instantiates the servlet
3. Initializes the servlet
4.invoke the service() method
after serving the request web-container wait for specific time, in this time if request comes then it call only service() method otherwise it call destroy() method..
If you are beginner, I think this tutorial may give basic idea about What Servlet is ...
Some valuable points are below from the given link.
Servlet technology is used to create web application which resides at server side and generates dynamic web page.
Servlet can be described in many ways, depending on the context.
Servlet is a technology i.e. used to create web application.
Servlet is an API that provides many interfaces and classes including
documentations.
Servlet is an interface that must be implemented for creating any
servlet.
Servlet is a class that extend the capabilities of the servers and
respond to the incoming request. It can respond to any type of
requests.
Servlet is a web component that is deployed on the server to create
dynamic web page.
Reference:Here.
Servlets are Java classes that run certain functions when a website user requests a URL from a server. These functions can complete tasks like saving data to a database, executing logic, and returning information (like JSON data) needed to load a page.
Most Java programs use a main() method that executes code when the program in run. Java servlets contain doGet() and doPost() methods that act just like the main() method. These functions are executed when the user makes a GET or POST request to the URL mapped to that servlet. So the user can load a page for a GET request, or store data from a POST request.
When the user sends a GET or POST request, the server reads the #WebServlet at the top of each servlet class in your directory to decide which servlet class to call. For example, let's say you have a ChatBox class and there's this at the top:
#WebServlet("/chat")
public class ChatBox extends HttpServlet {
When a user requests the /chat URL, your ChatBox class with be executed.
Java Servlets are server-side Java program modules that procedure and answer customer demands and actualize the servlet interface. It helps in improving Web server usefulness with negligible overhead, upkeep and support.
A servlet goes about as a mediator between the customer and the server. As servlet modules keep running on the server, they can get and react to demands made by the customer. Demand and reaction objects of the servlet offer a helpful method to deal with HTTP asks for and send content information back to the customer.
Since a servlet is coordinated with the Java dialect, it additionally has all the Java highlights, for example, high movability, stage autonomy, security and Java database availability.
Servlet is a java class to respond a HTTP request and produce a HTTP response...... when we make a page with the use of HTML then it would be a static page so to make it dynamic we use SERVLET {in simple words one can understand}
To make use of servlet is overcomed by JSP it uses the code and HTML tag both in itself..
As this article describes, a Servlet is a standardized way of extending a Java server, and accessing its capabilities.
Each Servlet can be seen as a tiny server (hence the name), that gets access to the request and response modelled in Java code, along with other context data, like the Session.
With these in hand, the Java code of the servlet can interface with whatever it needs to to render a response, including handing off to a JSP page for generating a HTML view.
I think servlet is basically a java class which acts as a middle way between HTTP request and HTTP response.Servlet is also used to make your web page dynamic. Suppose for example if you want to redirect to another web page on server then you have to use servlets. Another important thing is that servlet can run on localhost as well as a web browser.
You just got the answer for a normally servlet. However, I want to share you about something about Servlet 3.0
What is first a Servlet?
A servlet is a Web component that is managed by a container and
generates dynamic content. Servlets are Java classes that are compiled
to byte code that can be loaded dynamically into and run by a Java
technology-enabled Web server or Servlet container.
Servlet 3.0 is an update to the existing Servlet 2.5 specification.
Servlet 3.0 required API of the Java Platform, Enterprise Edition 6.
Servlet 3.0 is focussed on extensibility and web framework
pluggability. Servlet 3.0 bring you up some extensions such as Ease of
Development (EoD), Pluggability, Async Support and Security
Enhancements
Ease of Development
You can declare Servlets, Filter, Listeners, Init Params, and almost
everything can be configured by using annotations
Pluggability
You can create a sub-project or a module with a web-fragment.xml. It
means that it allows to implement pluggable functional requirements
independently.
Async Support
Servlet 3.0 provides the ability of asynchronous processing, for
example: Waiting for a resource to become available, Generating
response asynchronously.
Security Enhancements
Support for the authenticate, login and logout servlet security
methods
I found it from Java Servlet Tutorial

BlazeDS, Flex, and Java - Can I treat a RemoteObject like an instance of the Java class?

I'm sorry if this question is a bit obvious, but I'm new to BlazeDS and can't seem to find an answer. I'm running Java on a BlazeDS server with a Flex front-end. I'd like to be able to instantiate my Java class only once, then have the Flex use the setters and getters to play with the data in the Java class (in a sense, treating the RemoteObject as if it were an instance of the class). As far as I've read this seems to be the way BlazeDS works, but every time I call any Java method from Flex, it calls Java constructors again, resetting anything input by the setter methods. Is there a way to have the server hold the instance of the Java class between method calls? Thanks!
You seem to have a misunderstanding of how this is works.
Objects in the Flex client and Objects on your server are completely independent. In normal circumstances, The Flash Player/A Flex App only talks to the remote service using either a WebSerice, HTTPService, or RemoteObject. RemoteObject supports AMF and Flash Remoting with BlazeDS, LiveCycle Data Services, ColdFusion, and a ton of other server side software.
When you make remote calls to the server, that request is no different than a standard web page call. It exists in "isolation" and knows nothing about any other call. In traditional HTML development we use session cookies to keep track of server sessions in a 'stateless' client. The same can be true for Flex calls. If your server sets cookies on the client; then the Flash Player will include those cookies in each request; matching up the service call to a server side session.
Whether an object is created with each call depends on what your remote call does.
The benefit that AMF / RemoteObject offers is that it can easily translate server side objects (Java Classes) to client side objects (ActionSCript classes). This is primarily used for passing of data between the two different entities. Usually people make Value Objects/Data Transfer Objects for this; but the classes can have the same exact functionality. It is not like the same object exists in both Flex and Java.
Does that help?

Categories

Resources