ChatGPT解决这个技术问题 Extra ChatGPT

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.

Servlets You can look on it. I think this is details and authentic.
Sticking to the last question: "What is difference between server-side programming and servlets". Servlet is a part of server that receives e.g. http request and then responds to that, e.g. sends html page back to the user. It is actually controller that builds the final view for the user (check MVC. So it is similar to technologies such as PHP or so, but this is just coming from Java.

J
Jon Skeet

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.


Servlets are snippets of java code called by the web server inside the web server itself. If you want something looking like PHP or ASP you need JSPs (which are a special kind of servlets)
Thanx for the answer but still i can't get the real use of servlets, it would be better if u can explain by example like sitution where we can use servlets. i didn't understand the use of servlet like what servlet can do that other server side programming languages can't do.
@Hardik: it's not that they can do anything that can't be done another way. Servlets are just a common technology for server-side Java work. Servlets aren't a language - and neither is ASPX. Both are platforms you use in conjunction with another language - usually Java in the case of servlets.
@Hardik: As I wrote in my post, servlets are classes which operate inside a servlet container. The servlet container can host several servlets at the same time.
@Hardik: Yes, exactly. The servlet can provide the HTML to display the form and also act on the submission. Servlets can also be used to implement web services. They can be used for other protocols aside from HTTP, but HTTP is overwhelmingly the most common transport handled by servlets.
J
Jianhui Liu

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.

Hope this helps, happy learning.

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.


Link-only answers are discouraged on Stack Overflow, because the resources that they link to may become unavailable in the future or may change. Consider summarizing the relevant content of the link in your answer to improve it.
@Cupcake appreciate your constructive feedback. I tried to add some meat to the answer. Thanks for making the community better.
How do servlets fit with Jax-RS and Springboot? Are they used with these 2 technologies?
@pixel ultimately it has to use the servlets. If you look through the source code of Jax-RS / springboot it would at some point be extending a standard java servlet to provide all the abstractions and features.
m
mike rodent

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.


Is it incorrect to view the servlet as analogous to a "controller" in a standard MVC framework?
Personally I can't see how that analogy holds. I'd also tend to think that people who think my answer is a useful one (helps clarify things for them) might well be confused by your suggestion.
I think this Answer is useful. But I also wondered (independent of this Answer, and before reading it) the same question that @user2490003 posed above. What is the difference between a Servlet and an MVC-framework Controller? Why does analogy by user2490003 not hold?
An MVC arrangement is more complicated and yet less complicated. It doesn't necessarily involving waiting for input. In defining the basic idea of a server-client setup, it is that simplicity which I seek to emphasise. Look at the basic MVC diagram here: en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller. In a simple client-server setup, the user interacts only with the client, not with two objects, namely a view and a controller. With MVC there can also be multiple views, multiple controllers and multiple models. And waiting for input is not (necessarily) involved.
In addition to the above, a server can serve multiple users, whereas there is no such requirement with an MVC setup. An MVC setup belongs to the world of classical computing, i.e. standalone apps. With servers we take our first step into the universe of interactive computing. It's not that that the analogy is 100% wrong, more 90% wrong, and above all that any analogy is simply of no use if it doesn't actually help anyone or anything in any way whatsoever. A server-client arrangement is so utterly simple as an idea no-one needs analogies, of any kind at all, to understand.
S
Sankalp

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

servlets Servlet-name Servlet-class

Servlet-name

Servlet-class

servlet-mappings- the path like /Login or /Notifications is mapped here in Servlet-name url-pattern

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.


A link to a solution is welcome, but please ensure your answer is useful without it: add context around the link so your fellow users will have some idea what it is and why it’s there, then quote the most relevant part of the page you're linking to in case the target page is unavailable. Answers that are little more than a link may be deleted.
Note that the world has moved on. In 2020 we use annotations on the code instead of central string based configurations file in XML.
N
Navnath Adsul

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..


S
Sandun Madola

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.


That's a really good tutorial that explains concepts from the basic
P
Poorna Senani Gamage

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.


k
kundus

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.


R
Roopam

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..


m
mtyson

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.


r
remudada

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.


B
BalusC

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