getWriter() : returns PrintWriter Object that is used for writing character text.
getOutputStream() : returns ServletOutputStream Object used for writing binary data in response.
Welcome Message
Hi, welcome to my website. This is a place where you can get all the questions, puzzles, algorithms asked in interviews and their solutions. Feel free to contact me if you have any queries / suggestions and please leave your valuable comments.. Thanks for visiting -Pragya.
Top Navigation Menu
Showing posts with label Servlets. Show all posts
Showing posts with label Servlets. Show all posts
October 31, 2010
August 26, 2010
RequestDispatcher : forward()
The argument to forward method is the name of the resource we want the request to be forwarded to. This can be a jsp file or a Servlet. In case it is a servlet, the argument should be whatever we have specified in the url-pattern for that servlet declaration in web.xml.
So, the point to be noted here is that in case we want to forward the request to some other servlet, the argument to forward method should be the url-pattern of that servlet.
Also, as we (probably) already know, the URL in the browser is not changed in case of forward. i.e. the client does not get to know that internally the request has been forwarded to some other resource.
So, the point to be noted here is that in case we want to forward the request to some other servlet, the argument to forward method should be the url-pattern of that servlet.
Also, as we (probably) already know, the URL in the browser is not changed in case of forward. i.e. the client does not get to know that internally the request has been forwarded to some other resource.
August 2, 2010
Response : sendRedirect()
sendRedirect() method takes String as an argument. This string can start with a forward slash.
E.g.
Lets say the current URL we are accessing is : http://localhost:8080/MyApp/MyServlet/welcome.do
Now in our Servlet, we can do either :
response.sendRedirect("thanks.jsp");
OR
response.sendRedirect("/thanks.jsp");
Both of these would hit differnet URLs
In first case, i.e. response.sendRedirect("thanks.jsp");
The server will hit URL that is relative to the original URL, i.e http://localhost:8080/MyApp/MyServlet/thanks.jsp
and in second case,
the server builds the complete URL, relative to the web application itself.(instead of relative to original URL)
i.e. http://localhost:8080/MyApp/thanks.jsp
One more thing to note here is that the argument to sendRedirect() is a String only and not an object and the URL should be something that the server can generate a complete URL from the relative. i.e. it should be relative to something (be it relative to current URL or to the web-app).
So, any argument like "www.pragyarawal.tk/welcome.jsp" would not work as the server would try to create a complete URL from it. and in this case, the server would throw an "IllegalStateException".
E.g.
Lets say the current URL we are accessing is : http://localhost:8080/MyApp/MyServlet/welcome.do
Now in our Servlet, we can do either :
response.sendRedirect("thanks.jsp");
OR
response.sendRedirect("/thanks.jsp");
Both of these would hit differnet URLs
In first case, i.e. response.sendRedirect("thanks.jsp");
The server will hit URL that is relative to the original URL, i.e http://localhost:8080/MyApp/MyServlet/thanks.jsp
and in second case,
the server builds the complete URL, relative to the web application itself.(instead of relative to original URL)
i.e. http://localhost:8080/MyApp/thanks.jsp
One more thing to note here is that the argument to sendRedirect() is a String only and not an object and the URL should be something that the server can generate a complete URL from the relative. i.e. it should be relative to something (be it relative to current URL or to the web-app).
So, any argument like "www.pragyarawal.tk/welcome.jsp" would not work as the server would try to create a complete URL from it. and in this case, the server would throw an "IllegalStateException".
PrintWriter : print() vs write()
Today while reading Servlets, I came across the class PrintWriter.
I found that there we have two methods (both with various overloaded versions) : write() and print()
and I saw that print() internally calls write() only. So I was wondering that why there are different methods although they are doing the same thing. So, this seemed to be kind of redundancy to me.
Then I realized that print() is actually used as a utility method there, to which u can pass any literal value say whether it is boolean/char/int/float/double (to its overloaded versoins), but in write u have a limitaion of using only int /char array or string.So print() is just encapsulating the implementation of write() method by providing number of overlaoded method by which u can call the write().
I found that there we have two methods (both with various overloaded versions) : write() and print()
and I saw that print() internally calls write() only. So I was wondering that why there are different methods although they are doing the same thing. So, this seemed to be kind of redundancy to me.
Then I realized that print() is actually used as a utility method there, to which u can pass any literal value say whether it is boolean/char/int/float/double (to its overloaded versoins), but in write u have a limitaion of using only int /char array or string.So print() is just encapsulating the implementation of write() method by providing number of overlaoded method by which u can call the write().
Labels:
Servlets
August 1, 2010
HttpServletRequest
Some not very frequently used methods :
getServerPort(): Returns the port number to which the request was sent. (8080 in my case)
getServerName(): Name of the server (I used localhost)
getLocalAddr(): I got 0.0.0.0
getLocalPort() : This returns the port at which the request actually ends up. This is as the requests are made to the same port, but the server forwards them to different ports so that the application it can handle multiple threads.
getRemotePort(): Since the server asks for remote port, it is the client that is remote for the server. So, it returns the port number on the client on which the request was sent.
getServerPort(): Returns the port number to which the request was sent. (8080 in my case)
getServerName(): Name of the server (I used localhost)
getLocalAddr(): I got 0.0.0.0
getLocalPort() : This returns the port at which the request actually ends up. This is as the requests are made to the same port, but the server forwards them to different ports so that the application it can handle multiple threads.
getRemotePort(): Since the server asks for remote port, it is the client that is remote for the server. So, it returns the port number on the client on which the request was sent.
July 27, 2010
Overriding both doGet() and doPost() in a Servlet
We can override either doGet() or doPost() or both in a Servlet and based upon whether the request is GET or POST, the corresponding method will be called.
The Servlet would compile and run fine.
The Servlet would compile and run fine.
November 6, 2009
JSP and SERVLET
difference between JSP and SERVLET
Servlets and Java Server Pages are complementary APIs both providing a means for generating dynamic Web content. Infact JSP's are extensions to servlets which are mainly intended for presentation and to separate presentation from business logic. Functionality wise both are equally good and same.
In Servlets the dynamic content is generated by writing the HTML code embedded in Java code where as in JSP the dynamic content is generated by writing the Java code embedded in HTML code and JSP scriptlets. Finally JSPs are best suit for presentation and servlets are best suit for Controlling purpose
Q : Why is that we deploy servlets in a webserver.What exactly is a webserver?
A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page. To process a request, a Web server may respond with a static HTML page or image, send a redirect, or delegate the dynamic response generation to some other program such as CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScripts, or some other server-side technology. Whatever their purpose, such server-side programs generate a response, most often in HTML, for viewing in a Web browser. Understand that a Web server's delegation model is fairly simple. When a request comes into the Web server, the Web server simply passes the request to the program best able to handle it. The Web server doesn't provide any functionality beyond simply providing an environment in which the server-side program can execute and pass back the generated responses
Why is that we deploy servlets in a webserver.What exactly is a webserver?
When you increase the buffer size in jsp using the buffer tag then it means that you are increasing the data holding capacity of the buffer. When you access the jsp(incresed buffer size) then the user will observe that the page is loaded with data slowly.I means the user can actually see that the page content is being loaded. Its a good practise to use that way coz the user will be at ease.
Syntactically we can a write a constructor in a servlet. But if u write parameterized constructors ensure that u also add zero-arg constructor.If u dont add a zero-arg const. servlet instantiation fails. Infact a constructor doesnt serve any purpose in a servlet except for the zero-arg const. which is used at the time of instantiation of the servlet object.
what is the importance of deployment descriptor in servlet?
The deployment descriptor is not confined to servlets. It belongs to the application. The deployment descriptor basically tell the container where to look out for the resources which patterns to follow how are the resources mapped etc
you can customize web application configuration via the deployment descriptor These configuration include context and servlet initialization parameters servlet loading welcome page session timeout period error page init parameters mime types and can make application distributable.
Servlets and Java Server Pages are complementary APIs both providing a means for generating dynamic Web content. Infact JSP's are extensions to servlets which are mainly intended for presentation and to separate presentation from business logic. Functionality wise both are equally good and same.
In Servlets the dynamic content is generated by writing the HTML code embedded in Java code where as in JSP the dynamic content is generated by writing the Java code embedded in HTML code and JSP scriptlets. Finally JSPs are best suit for presentation and servlets are best suit for Controlling purpose
Q : Why is that we deploy servlets in a webserver.What exactly is a webserver?
A Web server handles the HTTP protocol. When the Web server receives an HTTP request, it responds with an HTTP response, such as sending back an HTML page. To process a request, a Web server may respond with a static HTML page or image, send a redirect, or delegate the dynamic response generation to some other program such as CGI scripts, JSPs (JavaServer Pages), servlets, ASPs (Active Server Pages), server-side JavaScripts, or some other server-side technology. Whatever their purpose, such server-side programs generate a response, most often in HTML, for viewing in a Web browser. Understand that a Web server's delegation model is fairly simple. When a request comes into the Web server, the Web server simply passes the request to the program best able to handle it. The Web server doesn't provide any functionality beyond simply providing an environment in which the server-side program can execute and pass back the generated responses
Why is that we deploy servlets in a webserver.What exactly is a webserver?
When you increase the buffer size in jsp using the buffer tag then it means that you are increasing the data holding capacity of the buffer. When you access the jsp(incresed buffer size) then the user will observe that the page is loaded with data slowly.I means the user can actually see that the page content is being loaded. Its a good practise to use that way coz the user will be at ease.
Syntactically we can a write a constructor in a servlet. But if u write parameterized constructors ensure that u also add zero-arg constructor.If u dont add a zero-arg const. servlet instantiation fails. Infact a constructor doesnt serve any purpose in a servlet except for the zero-arg const. which is used at the time of instantiation of the servlet object.
what is the importance of deployment descriptor in servlet?
The deployment descriptor is not confined to servlets. It belongs to the application. The deployment descriptor basically tell the container where to look out for the resources which patterns to follow how are the resources mapped etc
you can customize web application configuration via the deployment descriptor These configuration include context and servlet initialization parameters servlet loading welcome page session timeout period error page init parameters mime types and can make application distributable.
servlet is a piece of code which resides at server side and job is to generate dynamic responces.
Which code line must be set before any of the lines that use the PrintWriter?
setContentType() method must be set before transmitting the actual document.
When a servlet accepts a call from a client, it receives two objects. What are they?
ServeltRequest: which encapsulates the communication from the client to the server.
ServletResponse: which encapsulates the communication from the servlet back to the client.
ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.
What information that the ServletResponse interface gives the servlet methods for replying to the client?
It Allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.
What information that the ServletRequest interface allows the servlet access to?
Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. The input stream, ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods.
What are the uses of Servlets?
A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task.
What are Java Servlets?
Servlets are generic extensions to Java-enabled servers. Their most common use is to extend Web servers providing a very secure portable and easy-to-use replacement for CGI. A servlet is a dynamically loaded module that services requests from a Web server. It runs entirely inside the Java Virtual Machine. Because the servlet is running on the server side it does not depend on browser compatibility.
Can we call destroy() method on servlets from service method?
destroy() is a servlet life-cycle method called by servlet container to kill the instance of the servlet.
The answer to your question is "Yes". You can call destroy() from within the service(). It will do whatever logic you have in destroy() (cleanup, remove attributes, etc.) but it won't "unload" the servlet instance itself. That can only be done by the container
RE: What is difference between sendRedirect() and forward()..? Which one is faster then other and which ...
When you invoke a forward request the request is sent to another resource on the server without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container. When a sendRedirtect method is invoked it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
RE: do we have a constructor in servlet ? can we explictly provide a constructor in servlet programme as...
Cetainly we can have a constructor in servlet class but only default constructor. We can not have parametrized constructor in servlet because the servlet gets instantiated by the container dynamically and java does not allow to call parametrized constuctor for dynamically loaded clases.
setContentType() method must be set before transmitting the actual document.
When a servlet accepts a call from a client, it receives two objects. What are they?
ServeltRequest: which encapsulates the communication from the client to the server.
ServletResponse: which encapsulates the communication from the servlet back to the client.
ServletRequest and ServletResponse are interfaces defined by the javax.servlet package.
What information that the ServletResponse interface gives the servlet methods for replying to the client?
It Allows the servlet to set the content length and MIME type of the reply. Provides an output stream, ServletOutputStream and a Writer through which the servlet can send the reply data.
What information that the ServletRequest interface allows the servlet access to?
Information such as the names of the parameters passed in by the client, the protocol (scheme) being used by the client, and the names of the remote host that made the request and the server that received it. The input stream, ServletInputStream.Servlets use the input stream to get data from clients that use application protocols such as the HTTP POST and PUT methods.
What are the uses of Servlets?
A servlet can handle multiple requests concurrently, and can synchronize requests. This allows servlets to support systems such as on-line conferencing. Servlets can forward requests to other servers and servlets. Thus servlets can be used to balance load among several servers that mirror the same content, and to partition a single logical service over several servers, according to task.
What are Java Servlets?
Servlets are generic extensions to Java-enabled servers. Their most common use is to extend Web servers providing a very secure portable and easy-to-use replacement for CGI. A servlet is a dynamically loaded module that services requests from a Web server. It runs entirely inside the Java Virtual Machine. Because the servlet is running on the server side it does not depend on browser compatibility.
Can we call destroy() method on servlets from service method?
destroy() is a servlet life-cycle method called by servlet container to kill the instance of the servlet.
The answer to your question is "Yes". You can call destroy() from within the service(). It will do whatever logic you have in destroy() (cleanup, remove attributes, etc.) but it won't "unload" the servlet instance itself. That can only be done by the container
RE: What is difference between sendRedirect() and forward()..? Which one is faster then other and which ...
When you invoke a forward request the request is sent to another resource on the server without the client being informed that a different resource is going to process the request. This process occurs completely with in the web container. When a sendRedirtect method is invoked it causes the web container to return to the browser indicating that a new URL should be requested. Because the browser issues a completely new request any object that are stored as request attributes before the redirect occurs will be lost. This extra round trip a redirect is slower than forward.
RE: do we have a constructor in servlet ? can we explictly provide a constructor in servlet programme as...
Cetainly we can have a constructor in servlet class but only default constructor. We can not have parametrized constructor in servlet because the servlet gets instantiated by the container dynamically and java does not allow to call parametrized constuctor for dynamically loaded clases.
November 5, 2009
Servlets n JSPs
1. How do u difine an error page?
2.What r the methods called in servlet life cycle?
3.How can u make session variables un available?
4. How to change the port no of agiven application server?
5.Why and in wat kind of requirments we need to use EJBs?
1. Create one jsp page and there is tag called IsErrorPage True it means this is an error page . I u need to call this error page in ur application u can decalre errorpage "give realtive url"
2. Init(). For intilizing the servlet.
Service(). For servicing the request .
Destroy(). TO destroy the resource allocated by Init().
3. In Jsp There having an attribute like Session false.
4. Inside the appication server(jBoss) u just go to server /default/deploy/tomacat5.5.rar/server.xml. Inside server.xml u can see Tag
8080 . give some other name apart from 8080.
Restart the server and try with new port.
5. EJB is mainly for distributed application. It is following the RMI concept.
In RMI we are binding the Remote name and keep in the RMiregistry.
In Ejb We have a container it will provide lot of service like
1.persistance
2.Security
3.concurrency control.
4.Load balancing Etc
It will make our transction more powerful.
2.What r the methods called in servlet life cycle?
3.How can u make session variables un available?
4. How to change the port no of agiven application server?
5.Why and in wat kind of requirments we need to use EJBs?
1. Create one jsp page and there is tag called IsErrorPage True it means this is an error page . I u need to call this error page in ur application u can decalre errorpage "give realtive url"
2. Init(). For intilizing the servlet.
Service(). For servicing the request .
Destroy(). TO destroy the resource allocated by Init().
3. In Jsp There having an attribute like Session false.
4. Inside the appication server(jBoss) u just go to server /default/deploy/tomacat5.5.rar/server.xml. Inside server.xml u can see Tag
Restart the server and try with new port.
5. EJB is mainly for distributed application. It is following the RMI concept.
In RMI we are binding the Remote name and keep in the RMiregistry.
In Ejb We have a container it will provide lot of service like
1.persistance
2.Security
3.concurrency control.
4.Load balancing Etc
It will make our transction more powerful.
Invoking JSP Error page
Can I invoke a JSP error page from a servlet?
Yes, you 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();
}
}
}
Reference : http://www.geekinterview.com/question_details/2410
Yes, you 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();
}
}
}
Reference : http://www.geekinterview.com/question_details/2410
November 1, 2009
SCWCD Questions
Which of the following combinations regarding Design Patterns are correct?
A Business Delegate - Reduces the coupling between presentation-tier clients and business services.
B Data Access Object - Allows for Multiple Views using the same model
C MVC - Enables easier migration to different persistence storage implementations.
D Value Object - Reduces Network Traffic
Answer
A and D
Choices A and D are correct. In a normal scenario, presentation-tier components (e.g. a JSP) interact directly with business services. As a result, the presentation-tier components are vulnerable to changes in the implementation of the business services: when the implementation of the business services change, the code in the presentation tier must change. The goal of the Business Delegate object design pattern is to minimize the coupling between presentation-tier clients and the business service API, thus hiding the underlying implementation details of the service. Thus choice A is correct. Choice B is incorrect as it's the MVC design pattern rather than the DAO (Data Access Object), which provides Multiple Views using the same model. Choice C is incorrect as it's the DAO (Data Access Object) pattern, which enables easier migration to different persistence storage implementations. The Value Object is used to encapsulate the business data. A single method call is used to send and retrieve the Value Object. When the client requests business data from an enterprise bean, the enterprise bean can construct the Value Object, populate it with its attribute values, and pass it by value to the client. Thus choice D is also correct.
Which of these is true about deployment descriptors. Select one correct answer.
A The order of elements in deployment descriptor is important. The elements must follow a specific order.
B The elements of deployment descriptor are not case insensitive
C The servlet-mapping element, if defined, must be included within the servlet element.
D The web-app element must include the servlet element
Answer
A
The servlet specifications specifies a specific order of deployment descriptor. b is incorrect because elements are case-sensitive. The servlet-mapping element should be included within theelement. So c is incorrect. All the elements within the web-app element are optional. So d is incorrect.
Which of these is true about deployment descriptors. Select one correct answer.
A The order of elements in deployment descriptor is important. The elements must follow a specific order.
B The elements of deployment descriptor are not case insensitive
C The servlet-mapping element, if defined, must be included within the servlet element.
D The web-app element must include the servlet element
Answer
A
The servlet specifications specifies a specific order of deployment descriptor. b is incorrect because elements are case-sensitive. The servlet-mapping element should be included within theelement. So c is incorrect. All the elements within the web-app element are optional. So d is incorrect.
Which element of the deployment descriptor of a web application includes the welcome-file-list element as a sub element.
A
B
C
A Business Delegate - Reduces the coupling between presentation-tier clients and business services.
B Data Access Object - Allows for Multiple Views using the same model
C MVC - Enables easier migration to different persistence storage implementations.
D Value Object - Reduces Network Traffic
Answer
A and D
Choices A and D are correct. In a normal scenario, presentation-tier components (e.g. a JSP) interact directly with business services. As a result, the presentation-tier components are vulnerable to changes in the implementation of the business services: when the implementation of the business services change, the code in the presentation tier must change. The goal of the Business Delegate object design pattern is to minimize the coupling between presentation-tier clients and the business service API, thus hiding the underlying implementation details of the service. Thus choice A is correct. Choice B is incorrect as it's the MVC design pattern rather than the DAO (Data Access Object), which provides Multiple Views using the same model. Choice C is incorrect as it's the DAO (Data Access Object) pattern, which enables easier migration to different persistence storage implementations. The Value Object is used to encapsulate the business data. A single method call is used to send and retrieve the Value Object. When the client requests business data from an enterprise bean, the enterprise bean can construct the Value Object, populate it with its attribute values, and pass it by value to the client. Thus choice D is also correct.
Which of these is true about deployment descriptors. Select one correct answer.
A The order of elements in deployment descriptor is important. The elements must follow a specific order.
B The elements of deployment descriptor are not case insensitive
C The servlet-mapping element, if defined, must be included within the servlet element.
D The web-app element must include the servlet element
Answer
A
The servlet specifications specifies a specific order of deployment descriptor. b is incorrect because elements are case-sensitive. The servlet-mapping element should be included within the
Which of these is true about deployment descriptors. Select one correct answer.
A The order of elements in deployment descriptor is important. The elements must follow a specific order.
B The elements of deployment descriptor are not case insensitive
C The servlet-mapping element, if defined, must be included within the servlet element.
D The web-app element must include the servlet element
Answer
A
The servlet specifications specifies a specific order of deployment descriptor. b is incorrect because elements are case-sensitive. The servlet-mapping element should be included within the
Which element of the deployment descriptor of a web application includes the welcome-file-list element as a sub element.
A
B
C
D
E
Answer
D
The
Which of the following is legal JSP syntax to print the value of i. Select the one correct answer
A <<%int i = 1;%>
<%= i; %>
B <%int i = 1;
i; %>
C <%int i = 1%>
<%= i %>
D <%int i = 1;%>
<%= i %>
E <%int i = 1%>
<%= i; %>
Answer
D
When using scriptlets (that is code included within <% %>), the included code must have legal Java syntax. So the first statement must end with a semi-colon. The second statement on the other hand is a JSP expression. So it must not end with a semi colon.
Question
11 What will be the output of the following JSP code?
<%! int a = 20; %> <% int a = 10; %> <%! int b = 30; %> Now b = <%= b * a %>
A Now b = 300
B Now b = 600
C The code will not compile
D Now b = 30
E Now b = 0
Answer
A
In the first declaration <%! int a = 20; %>, the variable "a" will be declared as an instance variable. In the second declaration <% int a = 10; %>, the variable "a" will be declared as a local variable inside the service method. And at the time of multiplication it will use the local variable.
Consider the following code snippet of servlet code:
public void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
String value = getValue ();
if (value == null) response.sendError (HttpServletResponse.SC_NOT_FOUND, "Failed");
response.sendRedirect ("test.jsp");
}
If the getValue () method returns null , which of the following statements are true?
A The code will work without any errors or exceptions
B An IllegalStateException will be thrown
C An IOException will be thrown
D A NullPointerException will be thrown
Answer
B
Since the response is already committed by calling the sendError() , we cannot redirect it once again.
Nice Servlets and Jsp questions
What is session?
A : The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests. The session is stored on the server.
What is servlet context ?
A: The servlet context is an object that contains a information about the Web application and container. 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.
What is a servlet ?
A: servlet is a java program that runs inside a web container.
Can we use the constructor, instead of init(), to initialize servlet?
A: Yes. But you will not get the servlet specific things from constructor. 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 constructor 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.
How do I include static files within a JSP page?
A: Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase.
How can I implement a thread-safe JSP page?
A :You can make your JSPs thread-safe adding the directive <%@ page isThreadSafe="false" % > within your JSP page.
What is a Expression?
A: Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed. This will be included in the service method of the generated servlet.
Reference : http://www.javacertificate.net/jsp_iqns.htm
A : The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests. The session is stored on the server.
What is servlet context ?
A: The servlet context is an object that contains a information about the Web application and container. 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.
What is a servlet ?
A: servlet is a java program that runs inside a web container.
Can we use the constructor, instead of init(), to initialize servlet?
A: Yes. But you will not get the servlet specific things from constructor. 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 constructor 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.
How do I include static files within a JSP page?
A: Static resources should always be included using the JSP include directive. This way, the inclusion is performed just once during the translation phase.
How can I implement a thread-safe JSP page?
A :You can make your JSPs thread-safe adding the directive <%@ page isThreadSafe="false" % > within your JSP page.
What is a Expression?
A: Expressions are act as place holders for language expression, expression is evaluated each time the page is accessed. This will be included in the service method of the generated servlet.
Reference : http://www.javacertificate.net/jsp_iqns.htm
October 27, 2009
More on Servlets
Context parameters can not be anything other tham String. If we want to set init parameter to be sth else, we need to add a listener which would convert the String value to the desired value.
coz we can not put the code in Servlet as the servlet would have got the parameter value as String only by then.
This is done by implementing "ServletContextListener" interface which has two methods - contextInitialized(ServletContextEvent) and contextDestroyed(ServletContextEvent)
Difference between Attribute and Parameter
Attribute :
1. Type : Application / context , Request , Session
2. Method to set : setAttribute(String name , Object value)
3. Return type : Object
4. Method to get : getAttribute(String name)
Parameter :
1. Type : Application /context , Request , Servlet init parameters
2. Method : These can be set only in Deployment descriptor (web.xml)
3 . Return type : String
4. Method to get : getInitParameter(String name)
Context scope isnt thread safe. We can make them thread safe by using : synchronized(getServletContext())
Session persists across multiple requests from same client.
Its also not thread safe. We can makr it thread safe as we did to Context : synchronized(session)
Only requesr attributes and local variables are thread safe. Instance variables arnt.
we generally do not declare non final instance variables in Servlets.
We also have a "SingleThreadModel" interface, which can be used to make servlet thread safe. But this interface should better not be used as it effects performance a lot.
RequestDispatcher has two methods : forward(request , response) and include(request , response)
include() sends the request to do sth and it then comes back to the sender.
Difference b/w RequestDispatcher from context and from request
In the one from context, you can not specify relative path. u must specify absolute path.
coz we can not put the code in Servlet as the servlet would have got the parameter value as String only by then.
This is done by implementing "ServletContextListener" interface which has two methods - contextInitialized(ServletContextEvent) and contextDestroyed(ServletContextEvent)
Difference between Attribute and Parameter
Attribute :
1. Type : Application / context , Request , Session
2. Method to set : setAttribute(String name , Object value)
3. Return type : Object
4. Method to get : getAttribute(String name)
Parameter :
1. Type : Application /context , Request , Servlet init parameters
2. Method : These can be set only in Deployment descriptor (web.xml)
3 . Return type : String
4. Method to get : getInitParameter(String name)
Context scope isnt thread safe. We can make them thread safe by using : synchronized(getServletContext())
Session persists across multiple requests from same client.
Its also not thread safe. We can makr it thread safe as we did to Context : synchronized(session)
Only requesr attributes and local variables are thread safe. Instance variables arnt.
we generally do not declare non final instance variables in Servlets.
We also have a "SingleThreadModel" interface, which can be used to make servlet thread safe. But this interface should better not be used as it effects performance a lot.
RequestDispatcher has two methods : forward(request , response) and include(request , response)
include() sends the request to do sth and it then comes back to the sender.
Difference b/w RequestDispatcher from context and from request
In the one from context, you can not specify relative path. u must specify absolute path.
October 25, 2009
Servlets and JSPs
GET requests can be bookmarked but POST can not be.
GET is idempotent(Its used for getting things from the server, its not supposed to change anything ) , POST is not
addHeader() and setHeader() methods of response : Both will add a header and value to response if the header is not already present. The difference between these two occurs when the header is already there.
setHeader() overwrites the existing value
addHeader() adds an additional value
We can not do a send redirect after writing to the response. If we try to do so, it will throw an llegal state exception
Difference b/w redirect and a request dispatch : redirect makes the client do the work and sendRedirect makes sth on the server do the work.
we can not use Servlet init param unless the servlet is initialised.
sendredirect is called on response and request dispatcher is called on request
response.sendRedirect() and request.getRequestDispatcher() and then dispatcher.forward()
Also, in case of request dispatcher, the URL is not changed, so the user does not get to know about that.
GET is idempotent(Its used for getting things from the server, its not supposed to change anything ) , POST is not
addHeader() and setHeader() methods of response : Both will add a header and value to response if the header is not already present. The difference between these two occurs when the header is already there.
setHeader() overwrites the existing value
addHeader() adds an additional value
We can not do a send redirect after writing to the response. If we try to do so, it will throw an llegal state exception
Difference b/w redirect and a request dispatch : redirect makes the client do the work and sendRedirect makes sth on the server do the work.
we can not use Servlet init param unless the servlet is initialised.
sendredirect is called on response and request dispatcher is called on request
response.sendRedirect() and request.getRequestDispatcher() and then dispatcher.forward()
Also, in case of request dispatcher, the URL is not changed, so the user does not get to know about that.
Subscribe to:
Posts (Atom)