#ServletRequest Interface
Explore tagged Tumblr posts
Text
300+ TOP SERVLET Interview Questions and Answers
SERVLET Interview Questions for freshers experienced :-
1. What is Servlet? A servlet is a Java technology-based Web component, managed by a container called servlet container or servlet engine, that generates dynamic content and interacts with web clients via a request & response paradigm. 2. Why is Servlet so popular? Because servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server. 3. What is servlet container? The servlet container is a part of a Web server or application server that provides the network services over which requests and responses are sent, decodes MIME-based requests, and formats MIME-based responses. A servlet container also contains and manages servlets through their lifecycle. 4.When a client request is sent to the servlet container, how does the container choose which servlet to invoke? The servlet container determines which servlet to invoke based on the configuration of its servlets, and calls it with objects representing the request and response. 5.If a servlet is not properly initialized, what exception may be thrown? During initialization or service of a request, the servlet instance can throw an UnavailableException or a ServletException. 6.Given the request path below, which are context path, servlet path and path info? /bookstore/education/index.html context path: /bookstore servlet path: /education path info: /index.html 7.What is filter? Can filter be used as request or response? A filter is a reusable piece of code that can transform the content of HTTP requests,responses, and header information. Filters do not generally create a response or respond to a request as servlets do, rather they modify or adapt the requests for a resource, and modify or adapt responses from a resource. 8.When using servlets to build the HTML, you build a DOCTYPE line, why do you do that? I know all major browsers ignore it even though the HTML 3.2 and 4.0 specifications require it. But building a DOCTYPE line tells HTML validators which version of HTML you are using so they know which specification to check your document against. These validators are valuable debugging services, helping you catch HTML syntax errors. 9.What is new in ServletRequest interface ? (Servlet 2.4) The following methods have been added to ServletRequest 2.4 version: public int getRemotePort() public java.lang.String getLocalName() public java.lang.String getLocalAddr() public int getLocalPort() 10.Request parameter How to find whether a parameter exists in the request object? 1.boolean hasFoo = !(request.getParameter("foo") == null || request.getParameter("foo").equals("")); 2. boolean hasParameter = request.getParameterMap().contains(theParameter); (which works in Servlet 2.3+)
SERVLET Interview Questions 11. How can I send user authentication information while making URL Connection? You'll want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization. 12.Can we use the constructor, instead of init(), to initialize servlet? Yes , of course you can use the constructor instead of init(). There's nothing to stop you. But you shouldn't. The original reason for init() was that ancient versions of Java couldn't dynamically invoke constructors with arguments, so there was no way to give the constructur a ServletConfig. That no longer applies, but servlet containers still will only call your no-arg constructor. So you won't have access to a ServletConfig or ServletContext. 13.How can a servlet refresh automatically if some new data has entered the database? You can use a client-side Refresh or Server Push 14.The code in a finally clause will never fail to execute, right? Using System.exit(1); in try block will not allow finally code to execute. 15.What mechanisms are used by a Servlet Container to maintain session information? Cookies, URL rewriting, and HTTPS protocol information are used to maintain session information 16.Difference between GET and POST In GET your entire form submission can be encapsulated in one URL, like a hyperlink. query length is limited to 260 characters, not secure, faster, quick and easy. In POST Your name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the form's output. It is used to send a chunk of data to the server to be processed, more versatile, most secure. 17.What is session? The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests. 18.What is servlet mapping? The servlet mapping defines an association between a URL pattern and a servlet. The mapping is used to map requests to servlets. 19.What is servlet context ? The servlet context is an object that contains a servlet's view of the Web application within which the servlet is running. Using the context, a servlet can log events, obtain URL references to resources, and set and store attributes that other servlets in the context can use. (answer supplied by Sun's tutorial). 20.Which interface must be implemented by all servlets? Servlet interface. 21.Explain the life cycle of Servlet. Loaded(by the container for first request or on start up if config file suggests load-on-startup), initialized( using init()), service(service() or doGet() or doPost()..), destroy(destroy()) and unloaded. 22.When is the servlet instance created in the life cycle of servlet? What is the importance of configuring a servlet? An instance of servlet is created when the servlet is loaded for the first time in the container. Init() method is used to configure this servlet instance. This method is called only once in the life time of a servlet, hence it makes sense to write all those configuration details about a servlet which are required for the whole life of a servlet in this method. 23.Why don't we write a constructor in a servlet? Container writes a no argument constructor for our servlet. 24.When we don't write any constructor for the servlet, how does container create an instance of servlet? Container creates instance of servlet by calling Class.forName(className).newInstance(). 25.Once the destroy() method is called by the container, will the servlet be immediately destroyed? What happens to the tasks(threads) that the servlet might be executing at that time? Yes, but Before calling the destroy() method, the servlet container waits for the remaining threads that are executing the servlet’s service() method to finish. 26.What is the difference between callling a RequestDispatcher using ServletRequest and ServletContext? We can give relative URL when we use ServletRequest and not while using ServletContext. 27.Why is it that we can't give relative URL's when using ServletContext.getRequestDispatcher() when we can use the same while calling ServletRequest.getRequestDispatcher()? Since ServletRequest has the current request path to evaluae the relative path while ServletContext does not. 28. Whats the advantages using servlets over using CGI? CGI programs run outside the webserver. So a new process must be started to execute a CGI program. CGI programs are designed to handle a single request at a time. After that they return the result to the web server and exit. On the other hand servlets can handle multiple requests concurrently. They run within web servers. They generate dynamic content that is easier to write and faster to run. 29. What is Servlets and explain the advantages of Servlet life cycle? Servlets are the programs that run under web server environment. A copy of Servlet class can handle numerous request threads. In servlets, JVM stays running and handles each request using a light weight thread. Servlets life cycle involve three important methods, i.e. init, service and destroy. Init() Init method is called when Servlet first loaded in to the web server memory. Service() Once initialized, Servlets stays in memory to process requests. Servlets read the data provided in the request in the service() method. Destroy() When server unloads servlets, destroy() method is called to clean up resources the servlet is consuming. 30. What are different Authentication options available in Servlets. There are four ways of Authentication options available in servlets HTTP basic authentication In this, server uses the username and password provided by the client and these credentials are transmitted using simple base64 encoding. HTTP digest authentication This option is same the basic authentication except the password is encrypted and transmitted using SHA or MD5. HTTPS client authentication This options is based on HTTP over SSL. Form-based authentication Form-based authentication uses login page to collect username and password. 31. What is the GenericServlet class? GenericServlet makes writing servlets easier. To write a generic servlet, all you need to do is to override the abstract service method. 32. What is the difference between an Applet and a Servlet? Applets: Applets are applications designed to be transmitted over the network and executed by Java compatible web browsers. An Applet is a client side java program that runs within a Web browser on the client machine. An applet can use the user interface classes like AWT or Swing. Applet Life Cycle Methods: init(), stop(), paint(), start(), destroy() Servlets: Servlets are Java based analog to CGI programs, implemented by means of servlet container associated with an HTTP server. Servlet is a server side component which runs on the web server. The servlet does not have a user interface. Servlet Methods: doGet(), doPost() 33. List out the difference between ServletConfig and ServletContext? Both are interfaces in the package javax.servlet: ServletConfig is a servlet configuration object. It is used by a servlet container to pass information to a servlet during initialization. The ServletConfig parameters are specified for a particular servlet and are unknown to other servlets. The ServletContext object is contained within the ServletConfig object. It is provided by the web server to the servlet when the servlet is initialized. ServletContext is an interface which has a set of methods like getServletName(), getServletContext(), getInitParameter(), getInitParameterNames(). The servlet uses to interact with its servlet container. ServletContext is common to all servlets within the same web application. So, servlets use ServletContext to share context information. 35. What is the difference between using getSession(true) and getSession(false) methods? getSession(true) will check whether a session already exists for the user. If yes, it will return that session object else it will create a new session object and return it. getSession(false) will check existence of session. If session exists, then it returns the reference of that session object, if not, this methods will return null. 36. List out difference between a JavaBean from a Servlet? Servlets are Java based analog to CGI programs, implemented by means of a servlet container associated with an HTTP server. Servlets run on the server side. Beans are reusable code components written in Java that one can use in a variety of programming environments. JavaBeans are to Java what ActiveX controls are to Microsoft. Javabeans can run on server side, client side, within an applet etc. So, both have nothing in common except Java. 37. Define servlet mapping? Servlet mapping controls how you access a servlet. It is recommended that you don’t use absolute URLs. Instead usage of relative URLs should be done. If you try to deploy the application with a different context root, you might have to change all the urls used in all the JSP programs. Relative URLs is the solution so that you can deploy your application with different context root with out changing the URLs. 38. What is Servlets and explain the advantages of Servlet life cycle? Servlets are modules that run within the server and receive and respond to the requests made by the client. Servlets retrieve most of the parameters using the input stream and send their responses using an output stream. Servlets are used to extend the server side functionality of a website. They communicate with various application on the server side and respond to the request made by the client. 39. What is the difference between Difference between doGet() and doPost()? A doGet() method is limited with 2k of data to be sent, and doPost() method doesn't have this limitation. A request string for doGet() looks like the following: http://www.allapplabs.com/svt1?p1=v1&p2=v2&...&pN=vN doPost() method call doesn't need a long text tail after a servlet name in a request. All parameters are stored in a request itself, not in a request string, and it's impossible to guess the data transmitted to a servlet only looking at a request string. 40. What is the difference between ServletContext and ServletConfig? 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. ServletConfig: The object created after a servlet is instantiated and its default constructor is read. It is created to pass initialization information to the servlet. 41. What are all the protocols supported by HttpServlet? HttpServlet supports HTTP and HTTPS protocol. 42. Which exception is thrown if servlet is not initialized properly? Servlet Exception or Unavailable Exception is thrown if servlet is not initialized properly. 43. Who is responsible for writing a constructor? Container is responsible for writing constructor without arguments in servlet. 44. What are all the advantages of Servlet over CGI? Following are the advantages of Servlet over CGI: Cannot be run in an individual process. Servlet stays in the memory while requests. For every CGI request, you must load and start a CGI program. web.xml conveniences 45. What are the different mode that servlets can be used? Following are the modes that servlets can be used: Filter chains can be used to collect servlets together Support HTTP protocol Used for CGI based applications Dynamic generation of servlets 46. What are the uses of servlets? Servlets are used to process and store data submitted by HTML form, dynamic content, handle multiple request concurrently and manage state information on top of stateless HTTP. 47. Whether we can get deadlock situation in Servlets? Yes, it can be achieved by writing doGet method in doPost method and writing doPost method in doGet method. 48. What is the default HTTP method in the servlet? Default method is GET method for HTTPservlet. 49. Whether thread can be used in Servlets? Yes, Single thread can be used in servlets. 50. What exception should be thrown when servlet is not properly initialized? Servlet exception or an Unavailable exception is thrown when it is not properly initialized. 51. What is a filter? A filter is nothing but a piece of code which can be reusable that will be transforming the content of HTTP requests, response and header information. 52. What are the features added in Servlet 2.5? Following are the features added in Servlet 2.5: Dependency on J2SE 5.0 Support for annotations Loading the class Several web.xml Removed restrictions Edge case clarifications 53. When servlet is loaded? A servlet can be loaded when: First request is made Auto loading and Server starts up There is a single instance that answers all requests concurrently which saves memory Administrator manually loads. 54. When Servlet is unloaded? A servlet is unloaded when: Server shuts down Administrator manually unloads 55. What is life cycle of Servlet? Following is life cycle of Servlet: Loaded Initialized Destroy Unloaded SERVLET Questions and Answers Pdf Download Read the full article
0 notes
Text
What is httpservletRequest and Response? tccicomputercoaching.com
What is HTTP servlet in Java?
Servlets are Java classes which service HTTP requests and implement the javax.servlet.Servlet interface. Web application developers typically write servlets that extend javax.servlet.http.HttpServlet, an abstract class that implements the Servlet interface and is specially designed to handle HTTP requests.

What is httpservletRequest and Response?
httpservletRequest:
Blueprint of an object to provide client request information to a servlet. The servlet container creates a ServletRequest object and sends it as an argument to the servlet's service method.
httpservletResponse
Defines an object to assist a servlet in sending a response to the client. The servlet container creates a ServletResponse object and passes it as an argument to the servlet's service method.
To learn more about Java, Advance Java , Programming Language
Visit us @ http://tccicomputercoaching.com/blog/
Call us @ 9825618292
0 notes
Text
JSP Interview questions
What is JSP?
Java Server Pages technology (JSP) is used to create dynamic web page. It is an extension to the servlet technology. A JSP page is internally converted into servlet.
What are advantages of using JSP?
JSP has several advantages as listed below
JSP Performance is significantly better because JSP allows embedding Dynamic Elements in HTML Pages itself. JSP are always compiled before it’s processed by the server unlike CGI/Perl which requires the server to load an interpreter and the target script each time the page is requested. JSP are built on top of the Java Servlets API, so like Servlets, JSP also has access to all the powerful Enterprise Java APIs, including JDBC, JNDI, EJB, JAXP etc. JSP pages can be used in combination with servlets that handle the business logic, the model supported by Java servlet template engines.
What are the life-cycle methods for a jsp?
JSP life cycle methods are listed below :
public void jspInit() : It is invoked only once, same as init method of servlet. public void _jspService(ServletRequest request,ServletResponse) throws ServletException,IOException : It is invoked at each request, same as service() method of servlet. public void jspDestroy() : It is invoked only once, same as destroy() method of servlet.
What are the advantages of JSP over Active Server Pages (ASP)?
The advantages of JSP are twofold.
First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use.
Second, it is portable to other operating systems and non-Microsoft Web servers.
What are the advantages of JSP over Pure Servlets?
It is more convenient to write (and to modify!) regular HTML than to have plenty of println statements that generate the HTML. Other advantages are:
Embedding of Java code in HTML pages. Platform independence. Creation of database-driven Web applications. Server-side programming capabilities.
What are the advantages of JSP over JavaScript?
JavaScript can generate HTML dynamically on the client but can hardly interact with the web server to perform complex tasks like database access and image processing etc.
What is difference between hide comment and output comment?
The jsp comment is called hide comment whereas html comment is called output comment. If user views the source of the page, the jsp comment will not be shown whereas html comment will be shown.
Explain lifecycle of a JSP.
A JSP Lifecycle consists of following steps:
Compilation: When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the page. If the page has never been compiled, or if the JSP has been modified since it was last compiled, the JSP engine compiles the page.
The compilation process involves three steps:
Parsing the JSP.
Turning the JSP into a servlet.
Compiling the servlet.
Initialization: When a container loads a JSP it invokes the jspInit() method before servicing any requests Execution: Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method in the JSP.The _jspService() method of a JSP is invoked once per a request and is responsible for generating the response for that request and this method is also responsible for generating responses to all seven of the HTTP methods ie. GET, POST, DELETE etc. Cleanup: The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a container.The jspDestroy() method is the JSP equivalent of the destroy method for servlets.
What are the JSP implicit objects?
JSP provides 9 implicit objects by default. They are as follows:
out : the out is type of JspWriter request : the request is type of HttpServletRequest response : the response is type of HttpServletResponse config : the config is type of ServletConfig session : the session is type of HttpSession application : the application is type of ServletContext pageContext : the pageContext is type of PageContext page : the page is type of Object, it refer to this exception : the exception is type of Throwable
What is a sciptlet in JSP and what is its syntax?
A scriptlet can contain any number of JAVA language statements, variable or method declarations, or expressions that are valid in the page scripting language.
Following is the syntax of Scriptlet: ? 1
<% some java code %>
What are JSP declarations?
A declaration declares one or more variables or methods that you can use in Java code later in the JSP file. You must declare the variable or method before you use it in the JSP file. ? 1
<%! some variable declaration; %>
What are JSP expressions?
A JSP expression element contains a scripting language expression that is evaluated, converted to a String, and inserted where the expression appears in the JSP file.
The expression element can contain any expression that is valid according to the Java Language Specification but you cannot use a semicolon to end an expression.
Its syntax is: ? 1
<%= expression %>
What are JSP comments?
JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or “comment out” part of your JSP page.
Following is the syntax of JSP comments: ? 1
<%-- This is JSP comment --%>
What are JSP Directives?
A JSP directive affects the overall structure of the servlet class. It usually has the following form: ? 1
<%@ directive attribute="value" %>
What are the types of directive tags?
The types directive tags are as follows:
<%@ page ... %> : Defines page-dependent attributes, such as scripting language, error page, and buffering requirements. <%@ include ... %> : Includes a file during the translation phase. <%@ taglib ... %> : Declares a tag library, containing custom actions, used in the page.
What are JSP actions?
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You can dynamically insert a file, reuse JavaBeans components, forward the user to another page, or generate HTML for the Java plugin.
Its syntax is as follows: ? 1
Name some JSP actions.
Some of the JSP Actions : jsp:include, jsp:useBean,jsp:setProperty,jsp:getProperty, jsp:forward,jsp:plugin,jsp:element, jsp:attribute, jsp:body, jsp:text
What are JSP literals?
Literals are the values, such as a number or a text string, that are written literally as part of a program code. The JSP expression language defines the following literals:
Boolean: true and false Integer: as in Java Floating point: as in Java String: with single and double quotes; ” is escaped as \”, ‘ is escaped as \’, and \ is escaped as \\. Null: null
What is a page directive?
The page directive is used to provide instructions to the container that pertain to the current JSP page. You may code page directives anywhere in your JSP page.
What is difference between include directive and include action?
include directive
The include directive includes the content at page translation time. The include directive includes the original content of the page so page size increases at runtime. It’s better for static pages.
include action
The include action includes the content at request time. The include action doesn’t include the original content rather invokes the include() method of Vendor provided class. It’s better for dynamic pages.
Is JSP technology extensible?
Yes. JSP technology is extensible through the development of custom actions, or tags, which are encapsulated in tag libraries.
How can I implement a thread-safe JSP page? What are the advantages and Disadvantages of using it?
You can make your JSPs thread-safe by having them implement the SingleThreadModel interface. This is done by adding the directive <%@ page isThreadSafe="false" %> within your JSP page.
How can we handle the exceptions in JSP ?
There are two ways to perform exception handling, one is by the errorPage element of page directive, and second is by the error-page element of web.xml file.
What are the two ways to include the result of another page. ?
There are two ways to include the result of another page:
By include directive By include action
Can we use the exception implicit object in any jsp page?
No. The exception implicit object can only be used in the error page which defines it with the isErrorPage attribute of page directive.
How is JSP used in the MVC model?
JSP is usually used for presentation in the MVC pattern (Model View Controller ) i.e. it plays the role of the view. The controller deals with calling the model and the business classes which in turn get the data, this data is then presented to the JSP for rendering on to the client.
What are the different scope values for the tag?
There are 4 values:
page request session application
What is the difference between ServletContext and PageContext?
ServletContext gives the information about the container whereas PageContext gives the information about the Request.
What is the difference in using request.getRequestDispatcher() and context.getRequestDispatcher()?
request.getRequestDispatcher(path) is used in order to create it we need to give the relative path of
the resource whereas context.getRequestDispatcher(path) in order to create it we need to give the absolute path of the resource.
What is EL in JSP?
The Expression Language(EL) is used in JSP to simplify the accessibility of objects. It provides many objects that can be used directly like param, requestScope, sessionScope, applicationScope, request, session etc.
What is basic differences between the JSP custom tags and java beans?
Custom tags can manipulate JSP content whereas beans cannot. Complex operations can be reduced to a significantly simpler form with custom tags than with beans. Custom tags require quite a bit more work to set up than do beans. Custom tags are available only in JSP 1.1 and later, but beans can be used in all JSP 1.x versions.
Can an interface be implemented in the jsp file?
No.
What is JSTL?
JSP Standard Tag Library is library of predefined tags that ease the development of JSP.
How many tags are provided in JSTL?
There are 5 type of JSTL tags.
core tags sql tags xml tags internationalization tags functions tags
Which directive is used in jsp custom tag?
The jsp taglib directive.
What are the 3 tags used in JSP bean development?
jsp:useBean jsp:setProperty jsp:getProperty
How to disable session in JSP?
<%@ page session="false" %>
What are various attributes Of page directive?
Page directive contains the following 13 attributes.
language extends import session isThreadSafe info errorPage isErrorpage contentType isELIgnored buffer autoFlush isScriptingEnabled
What is a include directive?
The include directive is used to includes a file during the translation phase. This directive tells the container to merge the content of other external files with the current JSP during the translation phase. You may code include directives anywhere in your JSP page.
The general usage form of this directive is as follows: ? 1
<%@ include file="relative url" >
What is a taglib directive?
The taglib directive follows the following syntax: ? 1
<%@ taglib uri="uri" prefix="prefixOfTag">
uri : attribute value resolves to a location the container understands
prefix : attribute informs a container what bits of markup are custom actions.
The taglib directive follows the following syntax: ? 1
<%@ taglib uri="uri" prefix="prefixOfTag" >
what is the function of action?
This action lets you insert files into the page being generated. The syntax looks like this: ? 1
Where page is the the relative URL of the page to be included.
Flush is the boolean attribute the determines whether the included resource has its buffer flushed before it is included.
What is Action?
The plugin action is used to insert Java components into a JSP page. It determines the type of browser and inserts the ? 1
or
tags as needed.
If the needed plugin is not present, it downloads the plugin and then executes the Java component. The Java component can be either an Applet or a JavaBean.
What is difference between GET and POST method in HTTP protocol?
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? Character.
The POST method packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ? in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing.
0 notes