• No results found

What is the difference between CGI and Servlet? SF

Logical/Functional Tiers and J2EE components

Q 09: What is the difference between CGI and Servlet? SF

A 09:

Traditional CGI

(Common Gateway Interface)

Java Servlet

Traditional CGI creates a heavy weight process to handle each http request. N number of copies of the same traditional CGI programs is copied into memory to serve N number of requests.

Spawns a lightweight Java thread to handle each http request. Single copy of a type of servlet but N number of threads (thread sizes can be configured in an application server).

Servlets (request/response paradigm)

Client Application Server

on host “localhost” port:8080

internet Presentation Tier Servlets W eb Container R M I/I IO P JN D I JT A JD BC JM S Ja va M ai l JA F W eb Browser-1

client-1 Deploment descriptorWEB-INF/web.xml

Deploment descriptor WEB-INF/jbossweb.xml

W eb Browser-3 client-2

CRMServlet

single instance of CRMServlet handles requests from multiple browser instances by assigning a thread

from the thread-pool for each request.

Client Tier HTML, CSS, JavaScript, images, etc. W eb Browser-2 client-2 Http response Http request request - 2 request -1 request - 3 response - 1 response - 2 response - 3 <html> <h1>Output to Browser</h1>

<body>W ritten as html from a Servlet<body> </html>

http://myserver:8080/myWebCtxt/crm.do

package com.devx;

//import statements

public class CRMServlet extends HttpServlet {

public void init(ServletConfig config) throws ServletException { super.init(config);

}

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

ServletOutputStream out = resp.getOutputStream(); out.setContentType(“text/html”);

out.println("<html><h1>Output to Browser</h1>");

out.println("<body>W ritten as html from a Servlet<body></html>");

}

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

doPost(req, resp); } } request response <?xml version="1.0" encoding="UTF-8"?> <web-app > <servlet> <servlet-name>CRMServlet</servlet-name> <servlet-class>com.devx.CRMServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>CRMServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app> <?xml version="1.0" encoding="UTF-8"?> <jboss-web> <context-root>myWebCtxt</context-root> </jboss-web>

A Servlet is a Java class that runs within a web container in an application server, servicing multiple client requests

concurrently forwarded through the server and the web container. The web browser establishes a socket connection to

the host server in the URL , and sends the HTTP request. Servlets can forward requests to other servers and servlets and can also be used to balance load among several servers.

Q. Which protocol is used to communicate between a browser and a servlet? A browser and a servlet communicate

using the HTTP protocol (a stateless request/response based protocol).

Q. What are the two objects a servlet receives when it accepts a call from its client? A “ServletRequest”, which

encapsulates client request from the client and the “ServletResponse”, which encapsulates the communication from the servlet back to the client.

In addition to both HTTP request and response, HTTP headers are informational additions that convey both essential and non-essential information. For example: HTTP headers are used to convey MIME (Multipurpose Internet Mail Extension) type of an HTTP request and also to set and retrieve cookies etc.

Content-Type: text/html

Set-Cookie:AV+USERKEY=AVSe5678f6c1tgfd;expires=Monday, 4-Jul-2006 12:00:00; path=/;domain=.lulu.com; response.setContentType(“text/html”);

response.addCookie(myCookie);

Q. How would you get the browser to request for an updated page in 10 seconds from the server?

response.setHeader(“Refresh”, 10);

Refresh does not stipulate continual updates. It just specifies in how many seconds the next update should take place. So, you have to continue to supply “Refresh” in all subsequent responses. The “Refresh” header is very useful because it lets the servlet display a partial list of items or an introductory image to be displayed while the complete results or real page is displayed later (say in 10 seconds). You can also specify another page to be reloaded as follows:

respose.setHeader(“Refresh”, “10;URL=http://localhost:8080/myCtxt/crm.do”);

The above setting can be directly set in the <HEAD> section of the HTML page as shown below as opposed to setting it in the servlet. This is useful for static HTML pages.

<META HTTP-EQUIV=”Refresh” CONTENT=”5; URL=http://localhost:8080/myCtxt/crm.do” />

Q. What can you do in your Servlet/JSP code to tell browser not to cache the pages? Another useful header is the

Cache-Control as shown below:

response.setHeader(“Cache-Control”,“no-cache”); //document should never be cached. HTTP 1.1 response.setHeader(“Pragma”, “no-cache”); //HTTP 1.0

response.setDateHeader(“Expires”, 0);

Q. What is the difference between request parameters and request attributes?

Request parameters Request attributes

Parameters are form data that are sent in the request from the HTML page. These parameters are generally form fields in an HTML form like:

<input type=”text” name=”param1” /> <input type=”text” name=”param2” />

Form data can be attached to the end of the URL as shown below for GET requests

http://MyServer:8080/MyServlet? param1=Peter&param2=Smith

or sent to the sever in the request body for POST requests. Sensitive form data should be sent as a POST request.

Once a servlet gets a request, it can add additional attributes, then forward the request off to other servlets or JSPs for processing. Servlets and JSPs can communicate with each other by setting and getting attributes.

request.setAttribute(“calc-value”, new Float(7.0)); request.getAttribute(“calc-value”);

You can get them but cannot set them.

request.getParameter("param1"); request.getParameterNames();

You can both set the attribute and get the attribute. You can also get and set the attributes in session and application scopes.

Q. What are the different scopes or places where a servlet can save data for its processing? Data saved in a request-scope goes out of scope once a response has been sent back to the client (i.e. when the request is completed).

//save and get request-scoped value

request.setAttribute(“calc-value”, new Float(7.0)); request.getAttribute(“calc-value”);

Data saved in a session-scope is available across multiple requests. Data saved in the session is destroyed when the session is destroyed (not when a request completes but spans several requests).

//save and get session-scoped value

HttpSession session = request.getSession(false); If(session != null) {

session.setAttribute(“id”, “DX12345”); value = session.getAttribute(“id”); }

Data saved in a ServletContext scope is shared by all servlets and JSPs in the context. The data stored in the servlet context is destroyed when the servlet context is destroyed.

//save and get an application-scoped value

getServletContext().setAttribute(“application-value”, “shopping-app”); value = getServletContext().getAttribute(“application-value”);

Q. Which code line should be set in a response object before using the PrintWriter or the OutputStream? You

need to set the content type using the setContentType(…) method.

//to return an html

response.setContentType(“text/html”); PrintWriter out = response.getWriter(); out.println(“…….”);

//to return an image

response.setContentType(“image/gif”);

How does a Servlet differ from an Applet?

Applet Servlet

Applets execute on a browser. Servlets execute within a web container in an Application Server.

Applets have a graphical user interface. Servlets do not have a graphical user interface.

Outline

Related documents