[READ: Why-JAVA][Start-Learning-JAVA][Why-Java's-Hot][Start-Using-LINUX][Java-Q-&-A][Question][Java-SE-6-Doc][Struts-Doc][Java-Tutorial-Index] [Java-Certification]
[Tech.][Struts.][Servlet.][JSP.][EJB.][JNDI-JMS][SQL.][JDBC.]
CORE-JAVA: [OOP][CLASS][ABSTRACT][EXCEPTIONS][THREADS][UTILS][PACKAGES][JVM][CASTING][NETWORKING][RMI-XML]
[Tech.][Struts.][Servlet.][JSP.][EJB.][JNDI-JMS][SQL.][JDBC.]
CORE-JAVA: [OOP][CLASS][ABSTRACT][EXCEPTIONS][THREADS][UTILS][PACKAGES][JVM][CASTING][NETWORKING][RMI-XML]
Explain the life cycle methods of a Servlet. (Sun Tutor)
A: The javax.servlet.Servlet interface defines the three methods known as life-cycle methods.
public void init(ServletConfig config) throws ServletException
public void service( ServletRequest req, ServletResponse res) throws ServletException, IOException
public void destroy()
First the servlet is constructed, then initialized with the init() method. Any request from client are handled initially by the service() method before delegating to the doXxx() methods in the case of HttpServlet. The servlet is removed from service, destroyed with the destroy() method, then garbage collected and finalized.
What is the difference between the getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface and javax.servlet.ServletContext interface?
A: The getRequestDispatcher(String path) method of javax.servlet.ServletRequest interface accepts parameter path to the resource included or forwarded, which can be relative to the request of the calling servlet. In order to create it we need to give the relative path of the resource.
The getRequestDispatcher(String path) method of javax.servlet.ServletContext interface cannot accept "relative paths". All path must sart with a "/" and are interpreted as "relative to the current context root". In order to create it we need to give the absolute path of the resource.
What is the difference between Interfaces ServletContext and ServletConfig?
A: 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. The ServletContext interface provides information to servlets regarding the environment in which they are running. It also provides standard way for servlets to write events to a log file.
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.
The servlet engine implements the ServletConfig interface in order to pass configuration information to a servlet. The server passes an object that implements the ServletConfig interface to the servlet's init() method.
Explain the directory structure of a web application.
A: The directory structure of a web application consists of two parts.
A private directory called WEB-INF consists of "web.xml" "classes directory" and "lib directory".
A public resource directory which contains public resource folder.
What are the common mechanisms used for session tracking? (Cookies) (Session)
A: Cookies SSL sessions and URL- rewriting. (Geek Interview)
Explain ServletContext.
A: ServletContext interface is a window for a servlet to view it's environment. A servlet can use this interface to get information such as initialization parameters for the web application or servlet container's version. Every web application has one-and-only-one ServletContext and is accessible to all active resource of that application. The ServletContext object is contained within the ServletConfig object: ServletConfig.getServletContext() OR Servlet.getServletConfig().
init() method provides a config object:
public void init(ServletConfig config) throws ServletException {
super.init(config);
paramName = config.getInitParameter("paramName"); }
What is pre-initialization of a servlet? (Ex: Web.xml)
A: A container does not initialize the servlets as soon as it starts up, it initializes a servlet when it receives a request for the first time. This is called lazy loading. The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in, is called preloading or preinitializing a servlet. Specify "1" in between the tag "load-on-startup".
What is the difference between doGet() and doPost()? (Servlets)
Client HTML FORM Ex: <.FORM ACTION="/servlet/RedirectServlet" METHOD="POST".>
<.SELECT NAME="url" ONCHANGE="goFunction()" ONBLUR="return options[0].selected=true".>
<.OPTION VALUE="/developer/products/j2me/".> Consumer <./OPTION.> ... many more Options ...
When you select a destination and click the Go button, the menu form invokes the servlet by through the Action line. NAME attributes describes the information that is entered into the values. NAME and its values must be meaningful so if the data is written to email messages, log files, or databases the information makes sense to the user viewing them (writing servlet code). When a client calls a servlet by typing the URL in the browser, submitting a form, or clicking a button on a menu, the servlet's service method checks the HTTP request type, such as POST or GET. This in turn calls doGet, doPOST, doPUT, or doDelete as needed. A servlet must override doGet or doPost, depending on whether data is sent by POST or GET in the HTML form.
public void init(ServletConfig config) throws ServletException { super.init(config);
-------String paramName = config.getInitParameter("paramName"); }
public void doPost(HttpServletRequest request, HttpServletResponse response) { doGet(req, res) {
-------response.sendRedirect(request.getParameter(paramName));
HttpServletRequest has methods such as getParameter that takes the value of a NAME attribute as a string Object.
sendRedirect, sends a temporary redirect response to the client using the specified redirect location URL.
The doGet method calls the getParameter method through the request object, passing in the paramName String Object and its value as a string pair, in this case url(NAME) and the actual URL(/developer/products/j2me/). A special sendRedirect method then passes the string to the browser and redirects the user to the desired destination. The doPost or doGet methods instruct the server about what it must do, whether printing information back to the client's browser, writing to a database, or simply redirecting the client to a requested URL. Within these methods you will use Java programming syntax to give specific instructions for the servlet to interact between the client and the server.
A: 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. (HttpServlet)
HTML FORM GET request is a request to get a resource from the server. Choosing GET as the "method" will append all of the data to the URL and it will show up in the URL bar of your browser. The amount of information you can send back using a GET is restricted as URLs can only be 1024 characters. A POST request is a request to post (to send) form data to a resource on the server. A POST on the other hand will (typically) send the information through a socket back to the webserver and it won't show up in the URL bar. You can send much more information to the server this way - and it's not restricted to textual data either. It is possible to send files and even binary data such as serialized Java objects!
In the Servlet 2.4 specification SingleThreadModel has been deprecated, why? (SERVLET)
Because it is not practical to have such model. Whether you set isThreadSafe to true or false, you should take care of concurrent client requests to the JSP page by synchronizing access to any shared objects defined at the page level.
Can we use the constructor, instead of init(), to initialize a servlet? (SERVLET)
Its possible but not recommended. The original reason for init() was that, in ancient versions of Java couldn’t dynamically invoke constructors with arguments, so there was no way to give the constructor a ServletConfig. That no longer applies, but still, the servlet containers call the no-arg constructor. Thus we do not have access to a ServletConfig or ServletContext. (GenericServlet has two methods init() and init(ServletConfig config)
How many cookies can one set in the response object of the servlet? Are there any restrictions on the size of cookies? (SERVLETS)
If the client is using Netscape, the browser can receive and store 300 total cookies
4 kilobytes per cookie (including name)
20 cookies per server or domain
What's the difference between sendRedirect( ) and forward( ) methods?
A HttpServletResponse.sendRedirect method creates a new request (it's also reflected in browser's URL ).
Where as RequestDispatcher.forward method forwards the same request to the new target(hence the change is NOT reflected in browser's URL).
The sendRedirect request scope objects are no longer available after a redirect because it results in a new request, but it's available in forward.
SendRedirect is slower compared to forward.
Is there some sort of event that happens when a session object gets bound or unbound to the session?
HttpSessionBindingListener will hear the events When an object is added and/or remove from the session object, or when the session is invalidated, in which case the objects are first removed from the session, whether the session is invalidated manually or automatically (timeout).
What do the differing levels of bean storage (page, session, app) mean?
page life time - NO storage. This is the same as declaring the variable in a scriptlet and using it from there.
session life time - request.getSession(true).putValue("myKey", myObj);
application level - getServletConfig().getServletContext().setAttribute("myKey ",myObj ). Application level objects can be used by multiple servlets.
request level - The storage exists for the lifetime of the request, which may be forwarded between jsp's and servlets
Is it true that, servlet containers, service each request, by creating a new thread? If that is true, how does a container handle a sudden dramatic surge, in incoming requests, without significant performance degradation?
The implementation depends on the Servlet engine. For each request generally, a new Thread is created. But to give performance boost, most containers, create and maintain a thread pool at the server startup time. To service a request, they simply borrow a thread from the pool and when they are done, return it to the pool.
For this thread pool, upper bound and lower bound is maintained. Upper bound prevents the resource exhaustion problem associated with unlimited thread allocation. The lower bound can instruct the pool not to keep too many idle threads, freeing them if needed.
What is URL Encoding and URL Decoding?
URL encoding is the method of replacing all the spaces and other extra characters into their corresponding Hex Characters.
Decoding is the reverse process converting all Hex Characters back their normal form.
For Example consider this URL, /ServletsDirectory/Hello'servlet/
When Encoded using URLEncoder.encode("/ServletsDirectory/Hello'servlet/")
the output is: http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F This can be decoded back using:
URLDecoder.decode("http%3A%2F%2Fwww.javacommerce.com%2FServlets+Directory%2FHello%27servlet%2F")
the output is: "/ServletsDirectory/Hello'servlet/"
Do objects stored in a HTTP Session need to be serializable? Or can they store any object?
Yes, the objects need to be serializable, but only if our servlet container supports persistent sessions. Most lightweight servlet engines (like Tomcat) do not support this. However, many EJB-enabled servlet engines do. Even if our engine does support persistent sessions, it is usually possible to disable this feature.
What is the difference between session and cookie?
The difference between session and a cookie is two-fold.
1) Session should work regardless of the settings on the client browser. Even if users decide to forbid the cookie (through browser settings) session still works. There is no way to disable sessions from the client browser.
2) Session and Cookies differ in types and amount of information they are capable of storing.
Javax.servlet.http.Cookie class has a setValue() method that accepts Strings. javax.servlet.http.HttpSession has a setAttribute() method which takes a String to denote the name and java.lang.Object which means that HttpSession is capable of storing any java object. Where as Cookie can only store String objects.
What is HttpTunneling?
HTTP tunneling is used to encapsulate other protocols within the HTTP or HTTPS protocols. Normally the intra-network of an organization is blocked by a firewall and the network is exposed to the outer world only through a specific web server port , that listens for only HTTP requests. To use any other protocol, that by passes the firewall, the protocol is embedded in HTTP and send as HttpRequest. (Applet Tunneling) (Implement HTTPS tunneling) (JavaTunnelService Examples)
How can a servlet refresh automatically if some new data has been entered the database? (SERVLET)
You can use a client-side Refresh or Server Push. (Comet API)
What is Server Side Push and how is it implemented and when is it useful?
Server Side push is useful when data needs to change regularly on the clients application or browser, without intervention from client. Standard examples might include apps like Stock's Tracker, Current News etc. As such server cannot connect to client's application automatically. The mechanism used is, when client first connects to Server, (Either through login etc..), then Server keeps the TCP/IP connection open.
It's not always possible or feasible to keep the connection to Server open. So another method used is, to use the standard HTTP protocols ways of refreshing the client page, which is normally supported by all browsers.
<.meta http-equiv='Refresh' content='5;URL=/servlet/stockquotes/'.>
This will refresh the page in the browser automatically and loads the new data every 5 seconds.
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+)
What is the Max amount of information that can be saved in a Session Object?
As such there is no limit on the amount of information that can be saved in a Session Object. Only the RAM available on the server machine is the limitation.
The only limit is the Session ID length(Identifier) , which should not exceed more than 4K. If the data to be store is very huge, then it's preferred to save it to a temporary file onto hard disk, rather than saving it in session. Internally if the amount of data being saved in Session exceeds the predefined limit, most of the servers write it to a temporary cache on Hard disk. (Tutor)
How can we send user authentication information while makingURLConnection?
We may want to use HttpURLConnection.setRequestProperty and set all the appropriate headers to HTTP authorization.
What is the difference between GenericServlet and HttpServlet?
A: A GenericServlet has a service() method aimed to handle protocol-independent requests.
GenericServlet is for servlets that might not use HTTP, like for instance FTP service. As of only Http is implemented completely in HttpServlet.
The GenericServlet has a service() method that gets called when a client request is made. This means that it gets called by both incoming requests and the HTTP requests are given to the servlet as they are.
HttpServlet extends GenericServlet and adds support for doGet(), doPost(), doHead() methods (HTTP 1.0) plus doPut(), doOptions(), doDelete(), doTrace() methods (HTTP 1.1). Both these classes are abstract.
Can we invoke a JSP error page from a servlet?
Yes, we can invoke the JSP error page and pass the exception object to it from within a servlet. The trick is to create a request dispatcher for the JSP error page, and pass the exception object as a javax.servlet.jsp.jspException request attribute. However, note that you can do this from only within controller servlets. If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following translation error:
java.lang.IllegalStateException: Cannot forward as OutputStream or Writer has already been obtained
The following code snippet demonstrates the invocation of a JSP error page from within a controller servlet:
protected void sendErrorRedirect(HttpServletRequest request, HttpServletResponse response, String errorPageURL, Throwable e) throws ServletException, IOException {
request.setAttribute ("javax.servlet.jsp.jspException", e);
getServletConfig().getServletContext(). getRequestDispatcher(errorPageURL).forward(request, response); }
public void doPost(HttpServletRequest request, HttpServletResponse response) {
try { // do something
} catch (Exception ex) { try { sendErrorRedirect(request,response,"/jsp/MyErrorPage.jsp",ex);
} catch (Exception e) { e.printStackTrace(); } } }
How can I run multiple instances of the same servlet class in the same WebLogic Server instance?
If you want to run multiple instances, your servlet will have to implement the SingleThreadModel interface. An instance of a class that implements the SingleThreadModel interface is guaranteed not to be invoked by multiple threads simultaneously. Multiple instances of a SingleThreadModel interface are used to service simultaneous requests, each running in a single thread.
When designing your servlet, consider how you use shared resources outside of the servlet class such as file and database access. Because there are multiple instances of servlets that are identical, and may use exactly the same resources, there are still synchronization and sharing issues that must be resolved, even if you do implement the SingleThreadModel interface.
Java Platform, Micro Edition (Java ME) here a application MIDlet, is designed for the Mobile Information Device Profile, MIDP is one of the Java ME specifications.
Wireless Development. How to write and deploy a servlet, and then how to hook up a MIDlet with the servlet.
*[ He is the one!]
Life is Beautiful.
Creating successful constructive personality. Why God Gave Us Friends? Way-to-Paradise. Creating-the-Beautiful-World. Doing-the-job-of-goodness. Life-is-Meaningful. The-A-to-Z-for-Goodness. Life-is-full-of-Tests. History-Proves-That. Love-in-different-forms. True-to-the-heart.
No comments:
Post a Comment