Sie sind auf Seite 1von 9

FAQ on Servlet and JSP What are Servlets?

A servlet is a Java programming language class used to extend the capabilities of servers that host applications accessed via a request-response programming model. Although servlets can respond to any type of request, they are commonly used to extend the applications hosted by Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes. The javax.servlet and javax.servlet.http packages provide interfaces and classes for writing servlets. All servlets must implement the Servlet interface, which defines life-cycle methods When implementing a generic service, you can use or extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet and doPost, for handling HTTPspecific services public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable Defines a generic, protocolindependent servlet. To write an HTTP servlet for use on the Web, extend HttpServlet instead. GenericServlet implements the Servlet and ServletConfig interfaces. GenericServlet may be directly extended by a servlet, although it's more common to extend a protocol-specific subclass such as HttpServlet. GenericServlet makes writing servlets easier. It provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet also implements the log method, declared in the ServletContext interface. To write a generic servlet, you need only override the abstract service method. What are advantages of servlets over CGI? Can you explain Servlet life cycle? The life cycle of a servlet is controlled by the container in which the servlet has been deployed. When a request is mapped to a servlet, the container performs the following steps. 1. If an instance of the servlet does not exist, the Web container a. Loads the servlet class. b. Creates an instance of the servlet class. c. Initializes the servlet instance by calling the init method. Initialization is covered in Initializing a Servlet. 2. Invokes the service method, passing a request and response object. Service methods are discussed in the section Writing Service Methods. If the container needs to remove the servlet, it finalizes the servlet by calling the servlet's destroy method. Finalization is discussed in Finalizing a Servlet. What are the two important API's in for Servlets? Package javax.servlet Package javax.servlet.http

Can you explain in detail "javax.servlet" package?

RequestDispatcher Servlet ServletConfig ServletContext ServletRequest ServletResponse SingleThreadModel

GenericServlet ServletException ServletInputStream ServletOutputStream UnavailableException

Interface javax.servlet.RequestDispatcher public interface RequestDispatcher Defines a object which serves as a wrapper around a server resource accessible via a particular URL path. This interface is primary used to access the functionality of one servlet from another. This class is not implemented by servlet programmers, but by servlet engine authors. Defines an object that receives requests from the client and sends them to any resource (such as a servlet, HTML file, or JSP file) on the server. The servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name. This interface is intended to wrap servlets, but a servlet container can create RequestDispatcher objects to wrap any type of resource. See Also: ServletContext.getRequestDispatcher(java.lang.String), ServletContext.getNamedDispatcher(java.lang.String), ServletRequest.getRequestDispatcher(java.lang.String) Method Summary forward(ServletRequest request, ServletResponse response) Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server. include(ServletRequest request, ServletResponse response) Includes the content of a resource (servlet, JSP page, HTML file) in the response. What's the use of ServletContext? public interface ServletContext Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. The ServletContext object is

contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized Servlet.getServletConfig(), ServletConfig.getServletContext() public ServletConfig getServletConfig() Returns a ServletConfig object, which contains initialization and startup parameters for this servlet. The ServletConfig object returned is the one passed to the init method. Implementations of this interface are responsible for storing the ServletConfig object so that this method can return it. The GenericServlet class, which implements this interface, already does this. Returns: the ServletConfig object that initializes this servlet init(javax.servlet.ServletConfig) How do we define an application level scope for servlet? ServletContext application = getServletConfig().getServletContext(); String somethingToStore = "test"; application.setAttribute("an_appilcation_level_variable", somethingToStore); String somethingToRetreive = (String) application.getAttribute("an_appilcation_level_variable"); What's the difference between GenericServlet and HttpServlet? generic servlet process the request using service() method. Httpservlet process the request using doGet() and doPost()method. public abstract class GenericServlet extends java.lang.Object implements Servlet, ServletConfig, java.io.Serializable GenericServlet defines a generic, protocol-independent servlet. GenericServlet gives a blueprint and makes writing servlet easier. GenericServlet provides simple versions of the lifecycle methods init and destroy and of the methods in the ServletConfig interface. GenericServlet implements the log method, declared in the ServletContext interface. To write a generic servlet, it is sufficient to override the abstract service method. public abstract class HttpServlet extends GenericServlet implements java.io.Serializable HttpServlet defines a HTTP protocol specific servlet. HttpServlet gives a blueprint for Http servlet and makes writing them easier. HttpServlet extends the GenericServlet and hence inherits the properties GenericServlet

Can you explain in detail javax.servlet.http package?

The javax.servlet.http package contains a number of classes and interfaces that describe and define the contracts between a servlet class running under the HTTP protocol and the runtime environment provided for an instance of such a class by a conforming servlet container Interface Summary HttpServletRequest HttpSession HttpSessionActivationListener HttpSessionAttributeListener HttpSessionBindingListener HttpSessionContext HttpSessionListener Class Summary Cookie HttpServlet HttpServletRequestWrapper HttpServletResponseWrapper HttpSessionBindingEvent HttpSessionEvent HttpUtils What's the architecture of a Servlet package?

Client Interaction When a servlet accepts a call from a client, it receives two objects:

A ServletRequest , which encapsulates the communication from the client to the server.

A ServletResponse , which encapsulates the communication from the servlet back to the client. ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.

Why is HTTP protocol called as a stateless protocol? HTTP Protocol stands for Hyper Text Transfer Protocol. It is the protocol used to convey information of World Wide Web (WWW). HTTP protocol is a

stateless and connectionless protocol. HTTP is called as a stateless protocol because each command is request is executed independently, without any knowledge of the requests that were executed before it. It is the protocol used for the web. It is based on a request/request paradigm. In this protocol the communication generally takes place over a TCP/IP protocol. HTTP Request Methods: 1) GET Method 2) POST Method 3) HEAD Method 4) TRACE Method 5) DELETE Method 6) OPTIONS Method 7) PUT 8) CONNECT What are the different ways we can maintain state between requests? 1) Session 2) URL rewriting 3) cookies 4) hiddenformfield What is URL rewriting? What are cookies? "cookie" is a small piece of information sent by a web server to store on a web browser so it can later be read back from that browser. This is useful for having the browser remember some specific information Cookie userCookie = new Cookie("user", "uid1234"); response.addCookie(userCookie); What are sessions in Servlets? Java Servlet framework provides a Session API. programming model for implementing sessions in your own servlets 1. Get the HttpSession object use the getSession method of the javax.servlet.http.HttpServletRequest object 2. Store and retrieve user-defined data in the session. 3. (Optional) Output an HTML response page containing data from the HttpSession object. HttpSession session = request.getSession(create); session.getAttribute ("sessiontest.counter"); session.setAttribute ("sessiontest.counter", ival);

What's the difference between getSession(true) and getSession(false)? When you say getSession(true), this method will check whether already a session is existing for the user. If a session is existing, it will return that session object, OTHERWISE WILL CREATE A SESSION OBJECT EXPLICITLY AND RETURN TO THE CLIENT. When you say getSession(false), this method will check whether a session is existing. If yes, then it returns the reference of that session object, OTHERWISE IT WILL RETURN 'null'. What's the difference between "doPost" and "doGet" methods? doGet is called in response to an HTTP GET request doPost is called in response to an HTTP POST request Which are the different ways you can communicate servlets? Request Dispatching HTTP Redirect Servlet Chaining HTTP request (using sockets or the URLConnection class) Shared session, request, or application objects (beans) Direct method invocation (deprecated) Shared static or instance variables (deprecated) between

What is functionality of "RequestDispatcher" object? e.g. ServletContext.getRequestDispatcher (HttpRequest, HttpResponse).forward("NextServlet") ; You can pass in the current request and response object from the latest form submission to the next servlet/JSP. You can modify these objects and pass them so that the next servlet/JSP can use the results of this servlet. There are some Servlet engine specific configurations for servlet chaining. Servlets can also call public functions of other servlets running in the same server. This can be done by obtaining a handle to the desired servlet through the ServletContext Object by passing it the servlet name ( this object can return any servlets running in the server). And then calling the function on the returned Servlet object. e.g. TestServlet test= (TestServlet)getServletConfig().getServletContext().getServlet("OtherServlet "); otherServletDetails= Test.getServletDetails(); How do we share data using "getServletContext ()"? ServletContext myContext = getServletContext(); String url = "/someWebAppPrefix"; ServletContext otherContext = myContext.getContext(url); Object someData = otherContext.getAttribute("someKey"); These two data-sharing approaches are illustrated by the SetSharedInfo and ShowSharedInfo servlets shown in Listings 4.6 and 4.7. The SetSharedInfo

servlet creates custom entries in the session object and the servlet context. It also sets two cookies: one with the default path, indicating that the cookie should apply only to URLs with the same URL prefix as the original request, and one with a path of "/", indicating that the cookie should apply to all URLs on the host. Finally, the Set-SharedInfo servlet redirects the client to the ShowSharedInfo servlet, which displays the names of all session attributes, all attributes in the current servlet context, all attributes in the servlet context that applies to URLs with the prefix /shareTest1, and all cookies. Explain the concept of SSI? What are filters in JAVA? A filter is an object than perform filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both Filters perform filtering in the doFilter method. Every Filter has access to a FilterConfig object from which it can obtain its initialization parameters, a reference to the ServletContext which it can use, for example, to load resources needed for filtering tasks Method Summary destroy() doFilter(ServletRequest request, ServletResponse response, FilterChain chain) init(FilterConfig filterConfig) Can you explain in short how do you go about implementing filters using Apache Tomcat? import java.io.IOException; import java.util.Date; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; public class LogFilter implements Filter { public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { } public void init(FilterConfig config) throws ServletException { } public void destroy() {

what's the difference between Authentication and authorization? Authentication Authentication verifies who you are. For e.g. login via ssh or access mail server using POP3 and SMTP protocols. Usually PAM (Pluggable authentication modules) are used as low-level authentication schemes into a high-level application programming interface (API), which allows programs that rely on authentication to be written independently of the underlying authentication scheme. Authorization Authorization verifies what you are authorized to do. For e.g. you are allowed to login via ssh but you are not authorized to browser / or any other file system. Authorization occurs after successful authentication. Authorization can be controlled at file system level or using various app level configuration options such as chroot(2). Explain in brief the directory structure of a web application? A web application has the directory structureas shown in below figure.

Can you explain JSP page life cycle? jspInit method _jspService method jspDestroy before this some faces come JSP page translation JSP page compilation load class create instance What is EL? how does EL search for an attribute? What are the implicit EL objects in JSP? How can we disable EL? what is JSTL?

Can you explain in short what the different types of JSTL tags are? How can we use beans in JSP? What is <jsp:forward> tag for ? What are JSP directives? what are Page directives? what are include directives? Can you explain taglib directives? How does JSP engines instantiate tag handler classes instances? what's the difference between JavaBeans and taglib directives? what are the different scopes an object can have in a JSP page? what are different implicit objects of JSP? what are different Authentication Options available in servlets? Can you explain how do we practically implement security on a resource? How do we practically implement form based authentication? How do we authenticate using JDBC? Can you explain JDBCRealm? Can you explain how do you configure JNDIRealm? How did you implement caching in JSP?

Das könnte Ihnen auch gefallen