Sevlets Example In Java
In Previous Example, We Developed Direct Live Program, without Explaining Any Methods, Now we discuss step to step working the Servlets in Java.
Before, we are going to start , click on the advertisement available on this blog. Now , we discuss the methods.
Three Methods use in Serevlet's
- init() : Initialize The Object.
- Service() : It's work on the request and response paradigms.
- Destroy() : Destroy the object when created on the servlets.
The init() method: A servlet's init method is called by the server immedfiately after the server constructs the servlet's instance. Depending on the server and its configuration, this can be at any of these times :
when the server start, when the servlet's is first request,
Just before service() method is invoked.
At the request of the server administrator
init() : method is typically used to perform servlet's initialization, creating or loading objects that are used by the servlet in the handling of its requests.
service(): The Service() then reads the request , and generates the response which is send back to the client.
destroy(): destroy the method.
Example Program:
//Required Java Libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
//Extend HttpServlet class
public class HelloWorld extends HttpServlet
{
private String message;
//use init method
public void init() throws ServletException
{
//Do required initialization
message = "Welcome to Our First Servlet's Programs";
}
//use Service Method (Request, Response)
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//Set the response to content type
response.setContentType("text/html");
//Actual Logic On this Place
PrintWriter out = response.getWriter();
out.println("<p>" + message + "</p>");
}
//Use Destroy Method
public void destroy()
{
// Do Nothing......
}
}
Now, Creating web.xml under WEB-INF folder, it's very useful , b'coz declare the mapping on our servlet.
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
That's it , Now Compile and Run On this Program for better understanding, if you have any question about this program feel free to comment below. And don't forget to follow our blog.
If this information is important to you , and you want to , I will continue writing some more details About Java, Servlet's, Android Programming Language, so click on the advertising, available on this page. This is motivate me for writing some more useful stuff, Thank's
Comments
Post a Comment