Sunday, January 19, 2014

Java JSP - Servlet Tutorial -- Part 4























[Enter
Post Title Here]


JSP - Servlet


Now you know how to configure Tomcat, How to run JSP alone, How to run Servlet alone.  And here we are going to see all these in a single project..I.e  Communicating a JSP to Servlet through Tomcat.

Create a dynamic web project



 Create the JSP file



  • In the "Project Explorer" view, R-click
    "WebContent" / New / JSP.
  • Name your JSP - to be consistent with the example, name
    it "Home.jsp"
  • place the JSP the following code:




Paste this in Home.jsp


<%@pagelanguage="java"contentType="text/html;
charset=ISO-8859-1"
      pageEncoding="ISO-8859-1"%>
<!DOCTYPEhtmlPUBLIC"-//W3C//DTD
HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;
charset=ISO-8859-1"
>
<title>My
first JSP
</title>
</head>
<body>
      <formaction="FirstServlet">
            Please
enter a color 
<br>
<inputtype="text"name="color"size="20px">
<inputtype="submit"value="submit">
      </form>
</body>
</html>






Create the Servlet 










  • place the following code in the class:


package
com.cgs.controller;

import
java.io.IOException;
import
java.io.PrintWriter;

import
javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import
javax.servlet.http.HttpServlet;
import
javax.servlet.http.HttpServletRequest;
import
javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class
HelloWorldServlet
 */
@WebServlet("/FirstServlet")
public class
HelloWorldServlet extends HttpServlet {
        private static final long
serialVersionUID = 1L;


        /**
         * @see HttpServlet#doGet(HttpServletRequest
request, HttpServletResponse response)
         */
        protected void
doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
                        // reading the user
input
                        String color=
request.getParameter("color");
                        PrintWriter out =
response.getWriter();
                        out.println (
                        "<!DOCTYPE
html PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\"
\"http://www.w3.org/TR/html4/loose.dtd\">\n" +
"<html> \n" +
                         "<head> \n" +
                         "<meta
http-equiv=\"Content-Type\" content=\"text/html;
charset=ISO-8859-1\"> \n" +
                         "<title> My first
jsp</title> \n" +
                        "</head>
\n" +
                         "<body> \n" +
                         "<font size=\"12px\"
color=\"" +
                        color +
"\">" +
                        "Hello
World" +
                         "</font> \n" +
                         "</body> \n" +
                         "</html>" );

        }

}



Define your servlet in
"web.xml"


<?xmlversion="1.0"encoding="UTF-8"?>
<web-appid="WebApp_ID"version="2.4"
      xmlns="http://java.sun.com/xml/ns/j2ee"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

      <servlet>
            <servlet-name>Hello</servlet-name>
            <servlet-class>com.cgs.controller.HelloWorldServlet</servlet-class>
      </servlet>
      <servlet-mapping>
            <servlet-name>Hello</servlet-name>
            <url-pattern>/FirstServlet</url-pattern>
      </servlet-mapping>
      <welcome-file-list>
            <welcome-file>Home.jsp</welcome-file>
      </welcome-file-list>
</web-app>

Select  CGS-JSPServletproject explorer, right click  Run As à Run On Server à select Tomcat 7


 What has happened under the hood?


While we run servlet project,
1)      First it will look into WebContent/WEB-INF/web.xml  for the initial jsp file to be loaded under<welcome-file-list>. If its null, it will search for “index” or “default” html/jsp files are there.  Once it identify the file, iThis will compile our Servlet class and launch Home.jsp
2)      Once we enter a color on Input Box and click on “Submit” , the JSP file search for form à action . Here its <formaction="FirstServlet">. The control will come back to Web.XML ‘s<url-pattern>and will search for  <servlet-name>under</servlet-mapping>. Here “Hello” is the<servlet-name>.
3)      Once it identify the  <servlet-name>It will search for which servlet class to be loaded by looking into<servlet-class>under<servlet> . Here it’s<servlet-class>com.cgs.controller.HelloWorldServlet</servlet-class>andsimply generate an HTTP Get request.I.e"FirstServletis now mapped tocom.cgs.controller.HelloWorldServlet
4)      HelloWorldServlet will do some magic which we have written under doGet(), update the response object and finish processing. Tomcat will get notified and it will simply draw that response on screen.


The URL formation flow is as below




Friday, January 17, 2014

Java JSP - Servlet Tutorial -- Part 3


Hope you now familiar with JSP basis by going through my previous blog .Now we can study the basics of Servlet

Servlets


Introduction

In the early days, web servers deliver static contents that are indifferent to users' requests. Java servlets are server-side programs (running inside a web server) that handle clients' requests and return a customized or dynamic response for each request. The dynamic response could be based on user's input (e.g., search, online shopping, online transaction) with data retrieved from databases or other applications, or time-sensitive data (such as news and stock prices).
Java servlets typically run on the HTTP protocol. HTTP is an asymmetrical request-response protocol. The client sends a request message to the server, and the server returns a response message as illustrated.

Environment setup


Step 1)  Create Servlet project

Create the dynamic web project:

For creating a dynamic web project click on File Menu -> New -> Project..-> Web -> dynamic web project -> write your project name e.g. first -> Finish.






Create the servlet in eclipse IDE:

For creating a servlet, explore the project by clicking the + icon -> explore the Java Resources -> right click on src -> New -> servlet -> write your servlet name e.g. Hello -> uncheck all the checkboxes except doGet() -> next -> Finish.







Add jar file in eclipse IDE:

For adding a jar file, right click on your project -> Build Path -> Configure Build Path -> click on Libraries tab in Java Build Path -> click on Add External JARs button -> select the servlet-api.jar file under tomcat/lib -> ok.





 Now servlet has been created, Let's write the first servlet code.



4) Start the server and deploy the project:

For starting the server and deploying the project in one step, Right click on your project -> Run As -> Run on Server -> choose tomcat server -> next ->addAll -> finish.



 Now tomcat server has been started and project is deployed. To access the servlet write the url pattern name in the URL bar of the browser. In this case Hello then enter.

Now tomcat server has been started and project is deployed. To access the servlet write the url pattern name in the URL bar of the browser. In this case Hello then enter.







 Now tomcat7 server has been configured in eclipse IDE.

It is easy to manage the server instance. Right-click on the server and start and stop it to ensure its proper working.




 For test Tomcat is up and running , After starting the Tomcat, open browser and type http://localhost:8080. You should see the Apache Tomcat home page as shown below.


And here you go , Stop the server , if its already started and go to the above servlet project, right click  Run As à Run On Server .. Your servlet soup is ready to serve .. J