Sei sulla pagina 1di 27

Q What does web server do?

ANS A web server takes a client request,which is done by the web browser at the client side,process the request and return the required resources back to the client.This resource can be the html page,picture,text file,sound file any thing. Q What does web client do? ANS A web client lets the user request something on the server, and show the user the result of the request. Client is the piece of the software called as browser that knows how to communicate with the server,it interprets the html code and show the web page to the user. Q What is HTML and HTTP? ANS HTTP is the protocol client and server use on web to communicate .It allows simple request and response conversation.The client sends the an HTTP requests and server answers with an HTTP response.HTTP runs on the tCP/IP port no 80. HTTP tells the browser how to display content to the user.

Q What is get and post method of html? ANS Get is the simplest method its main job is to ask the server to get a resource and send it back,that resource may be anything.Total no of characters in get is limited.The data

that is sent with get is appended to the url so it is exposed.so get request can be bookmarked."?" separate the path and paramenter in the url in case of get method.It is used for just getting things. Get method is called in following cases when address is typed in the url. when user is requsting the page by clicking hyperlink. when method written is get in the method attribute of the form tag. when you forgot to write the method attribute in the form tag,it is default method. Post is more powerful request.With post you can request something and at the same time send form data to the server.It is designed to make the complex request to the server.For sending large data to the server post method is used.post has the body.It can not be bookmarked.It is used for posting things on the server. Post method is called in following cases when method written is post in the method attribute of the form tag. when data sent is too big then automatically get method becomes post. Q What is url? ANS http://www.yahoo.com:80/project/resource/index.html httpprotocol-tells the server which protocol it is. www.yahoo.com- server-unique name of server,it is mapped into the ip address of that server 80port no-it is optional and default,each server

supports multiple ports,it identified the server application project/resourcethe path to the location on the server. index.htmlthe name of content being requested,it can be of any type. and optional query string in case of get method Q What is MIME type? ANS MIME type tells the browser what kind of data browser is about to receive. Q What is CGI script? ANS Most cgi programs are written in perl language and many other languages for generating dynamic web pages and for processing the user request of any resources at the server side. Q Comparision of cgi and servlet? ANS Cgi program is written in perl language servlet is written in java. In cgi server launch a heavy weight process for each request. In servlet server launch a new thread for each request. Efficient Powerful Convienient Portable Secure Inexpensive

Q What is request and response header? ANS Request field in case of both get and post 1 Request Line-get/post/index.html http1.0 2 Requset header-name:value empty line in case of post 3 Requst body-encrypted data Response field 1 Response Line-http1.2 status code description http1.2 404 ok 2 Response header-response format,server version,size,cookie 3 Response body-response data Q what is container? ANS Server dont have main method.They are under the control of another java application called a container.When a web server gets a request for the servlet the server hands the request not directly to the servlet but to the container in which the servlet is deployed.Its the container that gives the servlet HTTP request and response and calls the service method. container performs following functions Communication support Life cycle management Multithreading support

Declarative security Jsp support Q How the container handles the request? ANS User clicks to the link that has a url to a servlet. Container sees that the request is for servlet,so the container creates two objects-HttpServletResponse and HttpServletRequest. The container finds correct servlet based on the url in the request,creates or allocates a thread for that request and passes the request and response object to the servlet thread. The container calls the servlet service method,then service method depending on the type of request calls the doGet or doPost method. Respective method generates the dynamic page and stuffs the page into the response object. After the thread completes, the container converts the response object into an HTTP response,sends it back to the client,then delete the request and response object. Q What is servlet? ANS Servlet is simply a java program which runs on server. servlet performs the following task Read the explicit data sent by the client. Read the implicit HTTP request data sent by the

browser. Generate the results. Send the explicit data (i.e., the document) to the client. Send the implicit HTTP response data. A servlet can have 3 names Deployment name-known by who deploy the server Actual File name{classpath/filename.class}-known by the original developer URL name-the name the client knows about. Q what is deployment descriptor? ANS When you deploy your servlet into web container,you will create a fairly simple XML document called the deployment descriptor to tell the container how to run your jsp.It use to XML element to map url to servlet -one to map client known public url name to your own internal name and one to map your internal name to a fully qualified class name. They are <servlet>---maps your internal name to a fully qualified class name. <servlet-mapping>---map client known public url name to your own internal name <web-app> <servlet> <servlet-name>internal name{logical}</servletname>

<servlet-class>actual file name</servlet-class> </servlet> <servlet-mapping> <servlet-name>internal name{logical}</servletname> <url-pattern>/public name</url-pattern> </servlet-mapping> </web-app> Q what are servlet debugging methods? ANS Use print statements. Use an integrated debugger in your IDE. Use the log file. Use Apache Log4J Write separate classes. Q what is MVC architecture?working of MVC architecture? ANS 69 Q what is the servlet hierarchy and servlet life cycle? ANS Servlet Interface-----level 0 javax.servlet.Servlet It has declared 5 methods

service(ServletReaquest,ServetResponse) init(ServletConfig) destroy() getServletConfig() getServletInfo() Generic Servlet Class-----level 1 javax.servlet.GenericServlet It is abstract class service(ServletReaquest,ServetResponse) init(ServletConfig) destroy() getServletConfig() getServletInfo() init() getInitParemeter(String) getInitParameterNames() getServletContext() log(String) log(String,throwable) HttpServlet class----level 2 javax.servlet.http.HttpServlet It is an abstract class service(ServletReaquest,ServetResponse)

service(HttpServletReaquest,HttpServetResponse) doGet(HttpServletReaquest,HttpServetResponse) doPost(HttpServletReaquest,HttpServetResponse)

Life cycle Initially servlet is in does not exist state At the first request the container looks for the deployed webapps and start searching the servlet class file. Then servlet moves from the does not exist to the initialized state beginning with the default constructor provided by the jvm but the constructor makes only an object not servlet. Then container makes the object of ServletConfig When an object becomes the servlet,it gets all unique privilages like ability to use its ServletContext reference to get info from container. Then container calls init method it initializes your servlet before your servlet handles any client request.This method calls only once in a life time of any servlet. When the clients request comes servlet creates a new thread and calls the servlets service method,this method looks the request and calls the respective get or post method. Then after completing the clients request container destroy the thread. At last servlet calls the servlets destroy method. Q what is difference between ServletConfig and ServletContext ? ANS

ServletConfig-One servlet config object per servlet Used to pass the deploy time information to the servlet Use it to access ServletContext parameters are configured in deployment descriptor ServletContext-One servletContext object per web application Use it to access the web application parameters Use it to put a message that other parts of application can access Use it to get servet info. Q Methods of HttpServletRequest and HttpServletResponse? ANS Request String param=request.getParameter("parameter name"); String[] paramlist=request.getParameterValues("parameter name"); String client=request.getHeader("User agent"); Cookie[] cookie=request.getCookies(); Session session=request.getSession();

String theMethod=request.getMethod(); InputStream input=request.getInputStream(); Response response.setContentType("String"); Printwriter out= response.getWriter(); out.println("")// write text data to character stream ServletOutputStream out=response.getOutputStream(); out.write("");//write anything Q what is redirecting and forwarding? ANS Both invites other servlet or other resource for handling your request response.sendRedirect("resource servlet"); When servlet does a redirect its like asking client to call someone else instead.In this case client is browser not the user.The browser makes new call on the user's behalf.The user can see the new url in the browser. RequestDispatcher view=response.getRequestDispatcher("resource servlet"); view.forward(request,response) when servlet does a request dispatch its like asking a coworker to take over working with a client then coworker responds to the client.The client never knows some one else

took over because url in the browser never changes. Q how to access the init parameter? ANS <servlet> <init-param> <param-name>param 1</param-name> <param-value>value 1</param-value> </init-param> </servlet> getServletConfig().getInitParameter("param name"); you can not use init parameters untill the servlet is initialized. <context-param> <param-name>param 1</param-name> <param-value>value 1</param-value> </context-param> getServletContext().getInitParameter("param name"); used by the whole application. Q what is ServetContextListener? ANS we can make a separate class that can listen for two key events in servlet contexts life initialization and destruction

this class implements javax.servlet.ServletContextListener this class get notified when the context is initialized get the context init parmeter from the ServletContext Use the init parameter look up names to create the database connection store the database connection as a attribute so that all parts of webapp can access it get notified when context is destroyed close the database connection import javax.servlet.ServletContextListener class MyServetContextListener implements ServetContextListener{ public void contextInitialized(ServletContextEvent event){ } public void contextDestroyed(ServletContextEvent event){ } } <Listener> <listener-class> package.MyServletContextListener </listener-class> </Listener>

Q what is session?Why it is needed?How it works? ANS An HttpSessionObjects hold conversational state across multiple requset from the same client. In other words it persist for an entire session with a specific client. An http protocol uses stateless connection.The client browser makes a connection to the server,sends a request,gets the response and closes the connection,because the connection does not persist the container doesnt recognize that the client making a second request is the same client from previous request for container each request is from a new client. On the clients first request,the container generates a unique session id and gives it back to the client with the response.The client sends back the id with every subsiquent request.The container sees the id finds the matching session and associates the session with the request.This exchange of id or info is done through cookie. That is you do have to tell the container that you want to create or use a session,but the container takes care of generating the session into the cookie as a part of response,And on the subsequent request ,container gets the session id from a cookie in the request,matches the session id with the existing session and associate that session with the current request.

HttpSession session=request.getSession(); if (session.isNew()) { // new session } else { // welcome back } HttpSession session=request.getSession(false); passing false means it always returns preexisting session otherwise null <web-app> <session-timeout>20</session-timeout>{min} </web-app> or session.setMaxInactiveInterval(20*60){sec} Q What is jsp?What is its life cycle? ANS Jsp is a full fledged servlet running in your application,Its lot like any other servlet,except that the servlet class is written for you by the container. The container takes what you have written in your jsp,translates it into a servlet class source file and then compiles that into a java servlet class

Need of Jsp It is hard to write and maintain the HTML You cannot use standard HTML tools. The HTML is inaccessible to non-Java developers. Life cycle Scriptlets <% java code service method Expressions <%= java code %> service method in System.out.println Declarations // enter into the %> // enter into the

<%! declared varibles and methods %>// enter into the class outside the service method Directives <%@ directive name attributes=values %> Q what is a directive? ANS A directive is a way for you to give a special instructions to the container at page translation time. directive are of 3 types page ,include, taglib written between <%@ directive name attributes=values %>

page directive It defines the page specific properties such as character encoding,the content type for this page's response and wheather this page should have the implicit object.A page directive can use up to 13 different attributes <%@ page import="java.util.*,java.sql.*" isThreadSafe="true/false" contentType="MIME type" isELIgonred="true/false" isErrorPage="false/true" errorPage="path" language="java" extends="class name" session="true/false" buffer=50 autoflush="true/false" pageEncoding="character encoding" info="" %> tag lib directive Defines a tag libraries available to jsp. <%@ taglib tagdir="" prefix=""%> include directive defines text and code that gets added into the current page at translation time. The include directive. This construct lets you insert JSP code into the main page before that main page is translated into a servlet. Its main advantage is that it is powerful: the included code can contain JSP constructs such as field definitions and content-type settings that affect the main

page as a whole. Its main disadvantage is that it is hard to maintain: you have to update the main page whenever any of the included pages change. <%@ include file="Relative URL" %> Think of the include directive as a preprocessor: the included file is inserted character for character into the main page, then the resultant page is treated as a single JSP page. So, the fundamental difference between jsp:include and the include directive is the time at which they are invoked: jsp:include is invoked at request time, whereas the include directive is invoked at page translation time. What does basic syntax look like? <jsp:include page="..." /> <%@ include file="..." %> When does inclusion occur? Request time Page translation time What is included? Actual content of file Output of page

How many servlets result? Two (main page and included page each become a separate servlet) One (included file is inserted into main page, then that page is translated into a servlet) Can included page set response headers that affect the main page? No Yes Can included page define fields or methods that main page

uses? No Yes Does main page need to be updated when included page changes? No What is the equivalent servlet code? include method of RequestDispatcher None Yes

jsp actions useBean Bean law the bean class must have public zero argument constructor. public getter and setter method must be named starting with set and get followed by the same word. the setter argument type and getter return type must be same. <jsp:useBean id="instance name" class="class name" scope="application/request/session/page" / > it will create the object if object does not exist otherwise return the existed one.

<jsp:getProperty name="instance name" property="property name" /> <jsp:setProperty name="instance name" property="property name" value="parameter" /> if you put your setter code<jsp:setProperty> inside the body of <jsp:useBean> the property setting is conditional that is property will only set when new bean is created. <jsp:useBean id="instance name" type="class name" class="class name" scope="application/request/session/page" > <jsp:setProperty name="instance name" property="property name" value/param="parameter" /> </jsp:useBean> type attribute is optional if we want that object reference should belong to some other class type. default value of scope attribute is page. param attribute is for passing the request parameter to the bean. if both value and param attribute is not specified then you are telling the container to get the value from a request parameter with a matching name of property name. if property="*" is used then all the set property match get their attribute by matching name with request parameter. <jsp:useBean ... scope="page" /> This is the default value; you get the same behavior if you omit the scope attribute entirely. The page scope indicates that, in addition to being bound to a local variable, the bean object should be placed in the PageContext object for the duration of the current request. Storing the object there means that servlet code can access it by calling getAttribute on the

predefined pageContext variable. Since every page and every request has a different PageContext object, using scope="page" (or omitting scope) indicates that the bean is not shared and thus a new bean will be created for each request. <jsp:useBean ... scope="request" /> This value signifies that, in addition to being bound to a local variable, the bean object should be placed in the HttpServletRequest object for the duration of the current request, where it is available by means of the getAttribute method. Although at first glance it appears that this scope also results in unshared beans, two JSP pages or a JSP page and a servlet will share request objects when you use jsp:include, jsp:forward , or the include or forward methods of RequestDispatcher . Storing values in the request object is common when the MVC (Model 2) architecture is used. <jsp:useBean ... scope="session" /> This value means that, in addition to being bound to a local variable, the bean will be stored in the HttpSession object associated with the current request, where it can be retrieved with getAttribute. Thus, this scope lets JSP pages easily perform the type of session tracking . <jsp:useBean ... scope="application" /> This value means that, in addition to being bound to a local variable, the bean will be stored in the ServletContext available through the predefined

application variable or by a call to getServletContext. The ServletContext is shared by all servlets and JSP pages in the Web application. Values in the ServletContext can be retrieved with the getAttribute method. include The jsp:include action. The jsp:include action lets you include the output of a page at request time. Its main advantage is that it saves you from changing the main page when the included pages change. Its main disadvantage is that since it includes the output of the secondary page, not the secondary page's actual code as with the include directive, the included pages cannot use any JSP constructs that affect the main page as a whole. The advantages generally far outweigh the disadvantages, and you will almost certainly use it much more than the other inclusion mechanisms. <jsp:include page="path" flush="true/false"/>

The included page uses the same request object as the originally requested page. As a result, the included page normally sees the same request parameters as the main page. If, however, you want to add to or replace those parameters, you can use the jsp:param element (which has name and value attributes) to do so. For example, consider the following snippet.
<jsp:include page="/fragments/StandardHeading.jsp">

<jsp:param name="bgColor" value="YELLOW" /> </jsp:include> plugin The jsp:plugin element is used to insert applets that use the Java Plug-in into JSP pages. Its main advantage is that it saves you from writing long, tedious, and error-prone OBJECT and EMBED tags in your HTML. Its main disadvantage is that it applies to applets, and applets are relatively infrequently used. <jsp:plugin type="applet" code="SomeApplet.class" width="300" height="200"> </jsp:plugin> jsp forward You use jsp:include to combine output from the main page and the auxiliary page. Instead, you can use jsp:forward to obtain the complete output from the auxiliary page. For example, here is a page that randomly selects either page1.jsp or page2.jsp to output. <% String destination; if (Math.random() > 0.5) { destination = "/examples/page1.jsp"; } else { destination = "/examples/page2.jsp"; } %> <jsp:forward page="<%= destination %>" /> To use jsp:forward, the main page must not have any output. This brings up the question, what benefit does JSP provide, then? The answer is, none! In fact, use of JSP is a hindrance in this type of situation because a real situation would be

more complex, and complex code is easier to develop and test in a servlet than it is in a JSP page. We recommend that you completely avoid the use of jsp:forward. If you want to perform a task similar to this example, use a servlet and have it call the forward method of RequestDispatcher.

Q what is translation process? ANS Look at the directives,for information it might need during translation. Creates an HttpServlet subclass it extends HttpJspBase If their is a page directive with an import attribute,it writes the import statement at the top of the class file,just below the package statement If there are declarations,it writes them into the class file,just below the class declaration and before the service method Builds the service method.The service method's actual name is _jspService then the container declares and initializes all the implicit objects combine all the html,scriptlet ,and expressions into the service method formating and writting into the response output Implicit objects JspWriter-out This variable is the Writer used to send output to the client. However, to make it easy to set response headers at

various places in the JSP page, out is not the standard PrintWriter but rather a buffered version of Writer called JspWriter. HttpServletRequest-request This variable is the HttpServletRequest associated with the request; it gives you access to the request parameters, the request type (e.g., GET or POST), and the incoming HTTP headers (e.g., cookies). HttpServletResponse-response This variable is the HttpServletResponse associated with the response to the client. Since the output stream (see out) is normally buffered, it is usually legal to set HTTP status codes and response headers in the body of JSP pages, even though the setting of headers or status codes is not permitted in servlets once any output has been sent to the client. HttpSession-session This variable is the HttpSession object associated with the request. Recall that sessions are created automatically in JSP, so this variable is bound even if there is no incoming session reference. The one exception is the use of the session attribute of the page directive to disable automatic session tracking. ServletContext-appliction This variable is the ServletContext as obtained by getServletContext. Servlets and JSP pages can store persistent data in the ServletContext object rather than in instance variables. ServletContext has setAttribute and

getAttribute methods that let you store arbitrary data associated with specified keys. The difference between storing data in instance variables and storing it in the ServletContext is that the ServletContext is shared by all servlets and JSP pages in the Web application, whereas instance variables are available only to the same servlet that stored the data. ServletConfig-config This variable is the ServletConfig object for this page. In principle, you can use it to read initialization parameters, but, in practice, initialization parameters are read from jspInit, not from _jspService. JspException-exception PageContext-context JSP introduced a class called PageContext to give a single point of access to many of the page attributes. The PageContext class has methods getRequest, getResponse, getOut, getSession, and so forth. The pageContext variable stores the value of the PageContext object associated with the current page. If a method or constructor needs access to multiple page-related objects, passing pageContext is easier than passing many separate references to request, response, out, and so forth. Object-page This variable is simply a synonym for this and is not very useful. It was created as a placeholder for the time when the scripting language could be something other than Java.

in web.xml <jsp-file>file.jsp</jsp-file> Scripting element can be made invalid for the jsp file <web-app> <jsp-config> <jsp-property-group> <url-pattern>*.jsp</url-pattern>{disable scripting element for all jsp} <scripting-invalid> true </scripting-invalid> <el-ignored> true </el-ignored> </jsp-property-group> </jsp-config> </web-app> 339

Potrebbero piacerti anche