answersLogoWhite

0

JSP and Servlets

JSP (JavaServer Pages) are Java programs encoded within webpages that research and generate pertinent results. Servlets, on the other hand, are objects (programs) that handle requests from users and provide results based on these requests.

500 Questions

What is the difference between applet and jsp?

User Avatar

Asked by Wiki User

Applet is an executable file that is automatically downloaded when we open a browser. Swing applications can operate on local data when the network is not there.

Generic Servlet and HTTP Servlet?

User Avatar

Asked by Wiki User

javax.servlet.GenericServlet

Signature: 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.

javax.servlet.http.HttpServlet

Signature: 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.

How can a Servlet call a JSP error page?

User Avatar

Asked by Wiki User

Declare That a JSP Page Is an Error Page

The isErrorPage attribute tells the container if the current page is available to be an error page for another JSP page (the current page is the URL in another page's errorPage attribute). Ex:

<%@ page isErrorPage="true" %>

If this attribute is set to "true" then the variable "exception" is available to you. Otherwise (default is "false"), if you try to reference the exception, you will get a fatal error.

So, when a Servlet request being forwarded to a JSP Page faces an exception/error this error page would get called.

Can variable declared in one scriplet access in another scriplet?

User Avatar

Asked by Wiki User

No. Variables declared inside a scriptlet are like method local variables which are not accessible outside the scriptlet/method.

How do you run servlet in tomcat?

User Avatar

Asked by Wiki User

You Run a Servlet by deploying it on the server, which in this case is tomcat. We need to deploy the servlet in the Web Applications context.

When we talk of a Web application's context, we are referring to that Web application's root directory or path within a particular server. A special directory exists within the application hierarchy named WEB-INF. This directory contains all things related to the application that aren't in the document root of the application. It is this WEB-INF directory that is the Web application's root directory, also referred to as the context. The most important file here is web.xml, the name of the WebApp deployment descriptor.

Let us take a look at the various contents (files & folders) that will be present inside this WEB-INF directory:

1. /WEB-INF/web.xml - This is the Deployment Descriptor file

2. /WEB-INF/classes/ - This is the directory where all your java class files will be placed

3. /WEB-INF/lib/ - This is the folder where all your JAR files go.

my tomcat is installed in c:\dev\java\Jakarta-tomcat-4.0.1. This is my TOMCAT_HOME. Remember that, this path that is referred by TOMCAT_HOME might vary from PC to PC depending on the installation preferences of the user.

To Deploy the Servlet, you need to place the .class file corresponding to your servlet in the /WEB-INF/classes/ folder

Is jsp is platform independents?

User Avatar

Asked by Wiki User

Yes. JSP is a java based technology and hence it is platform independent. So, you can run it in any environment. The same JSP that can run in a windows box can always run in a Linux box.

What is generic servlet class?

User Avatar

Asked by Wiki User

GenericServlet defines a generic, protocol-independent servlet whereas HttpServlet Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site that uses the Http Protocol.

Which method invalidate session of a jsp page?

User Avatar

Asked by Wiki User

session.invalidate()

What is the purpose of page directive in JSP?

User Avatar

Asked by Wiki User

The Page Directive is one of the important components of any JSP Page. It can help us define page specific properties like Buffer size or location of an error page etc

A JSP page, and any files included via the include directive, can contain one or more page directives but no duplicates. The JSP container will apply all the attributes to the page. The position of these page directives is irrelevant, but it is good practice to keep them together at the top of the page. (So that we can identify them easily)

What does servlet session API means?

User Avatar

Asked by Wiki User

The Servlet Session API refers to the documentation on the list of methods available in the HttpSession class that is used for Session Management

The HttpSession object is very powerful and has many features. Before we dig deep into the world of Sessions, let us take a look at the important methods they have so that we can use them effectively.

• getAttribute(java.lang.String name) - Returns an Object associated with that name that was stored in the session object.

• getAttributeNames() - Returns an Enumeration object that lists the names of the objects stored in the session object.

• getCreationTime() - Returns a long containing the date stamp of creation.

• getId() - Returns the id of the session as a String representing the unique identifier assigned to this session.

• getLastAccessedTime() - Returns a long containing the date stamp of the last time the session was accessed.

• getMaxInactiveInterval() - Returns an integer representing the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.

• invalidate() - This destroys a session. It can't be referenced after this method has been called.

• isNew() - This tells you whether the client knows about the session. In other words, the has session been created by the server, but the client hasn't acknowledged receiving the session ID yet.

• removeAttribute(java.lang.String name) - This removes an attribute. It deletes it from the session object.

• setAttribute(java.lang.String name, java.lang.Object value) - You use this method to add objects to a session.

• setMaxInactiveInterval(int interval) - Specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

• getValue(java.lang.String name) - Returns an Object associated with that name that was stored in the session object. As of Version 2.2, this method is replaced by getAttribute(). The getAttribute() method will be on the exam, not this one, but it is here for completeness.

• getValueNames() - Returns a String array with a list of names associated with the objects added to a given session. As of Version 2.2, this method is replaced by getAttributeNames(). The getAttributeNames() method will be on the exam, not this one, but it is here for completeness.

• putValue(java.lang.String name, java.lang.Object value) - You use this method to add objects to a session. This has been deprecated. As of Version 2.2, this method is replaced by setAttribute(java.lang.String, java.lang.Object). The setAttribute() method will be on the exam, not this one, but it is here for completeness.

• removeValue(java.lang.String name) - This removes a value, but retains an attribute name in the session. The name is valid but the object is null. This has been deprecated. As of Version 2.2, this method is replaced by removeAttribute(). The removeAttribute() method will be on the exam, not this one, but it is here for completeness.

How do you compile servlet in java using tomcat?

User Avatar

Asked by Wiki User

Tomcat is a server. It is used to deploy and run Servlets and not compile them. A Servlet is a java file and has to be compiled just like any other Java Class.

What are jsp actions?

User Avatar

Asked by Wiki User

JSP actions are XML tags that direct the server to use existing components or control the behavior of the JSP engine. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters.

There are six JSP Actions:

< jsp : include / >

< jsp : forward / >

< jsp : plugin / >

< jsp : usebean / >

< jsp : setProperty / >

< jsp : getProperty / >

What is servlet API in java?

User Avatar

Asked by Wiki User

Overview of the Servlet API

The Servlet 2.3 API consists of two packages: javax.servlet and javax.servlet.http. The base functionality is defined in the javax.servlet package whose classes and interfaces outline a generic, protocol-independent implementation. This means you can use it for non-Web applications, too. Of course, the exam targets the Web, so the HTTP protocol is the only one discussed in this blog. The javax.servlet.http interface defines classes and interfaces that are specific to the Hypertext Transfer Protocol (HTTP).

The javax.servlet Package

The javax.servlet package defines 12 interfaces, 7 classes, and 2 exceptions. These interfaces, classes, and exceptions are as follows.

Interfaces

• Filter:- Preprocessor of the request before it reaches a servlet. It can also be a postprocessor of the response leaving a servlet. It can modify a request or response (for example, change headers), the request to a resource (a servlet or static content), or the response from a resource.

• RequestDispatcher:- This is the servlet version of a redirect. It enables requests to be processed and then forwarded to other components of a Web application, such as another servlet, HTML file, or JSP file.

• Servlet:- Defines the life-cycle methods that are implemented by all servlets.

• ServletConfig:- This class has the methods for accessing the servlet configuration information such as the servlets name (from the web.xml file), the initialization parameters, and the ServletContext object.

• ServletContext:- These methods enable your servlet to communicate with its servlet container. This is how you get the MIME type of a file, dispatch requests, or write to a log file. Notice that this information has application scope. The most important features of the ServletContext are application-scope attributes access, logging, and context initialization parameters.

• ServletContextAttributeListener:- Implementations of this interface receive notifications of changes to the attribute list on the servlet context of a Web application. Supports the handling of the ServletContextAttributeEvent class.

• ServletContextListener:- An interface that supports the handling of the ServletContextEvent class. Defines a set of methods that a servlet uses to communicate with its servlet container. It can get the MIME type of a file, dispatch requests, or write to a log file. Notice that there is one context per "Web application" per Java Virtual Machine. The specification defines a "Web application" as a collection of servlets and content installed under a specific subset of the server's URL namespace, such as /catalog, and possibly installed via a .war file.

• ServletRequest:- This interface forms the base for the class that provides client request information to a servlet. It is protocol-independent.

• ServletResponse:- This interface forms the base for the class that represents the response sent from the servlet to the client.

• SingleThreadModel:- An interface that ensures a given servlet handles only one request at a time.

Classes

• GenericServlet:- An abstract class that implements ServletConfig. It defines a generic, protocol-independent servlet.

• ServletContextAttributeEvent:- This is the event class for notifications about changes to the attributes of the servlet context of a Web application.

• ServletContextEvent:- This is the event class for notifications about changes to the servlet context of a Web application (parent of ServletContextAttributeEvent).

• ServletInputStream:- Provides an input stream for reading binary data from a client request. You can modify it; it already has the readLine method for reading data one line at a time.

• ServletOutputStream:- An abstract class providing an output stream for sending binary data to the client. You print HTML, XML, or other output to the client using ServletOutputStream's print() and println() methods.

• ServletRequestWrapper:- Provides a convenient implementation of the ServletRequest interface that can be subclassed by developers wishing to adapt the request to a Servlet. This is where you can modify the behavior of request objects.

• ServletResponseWrapper:- Provides a convenient implementation of the ServletResponse interface that can be subclassed by developers wishing to adapt the response from a Servlet. This is where you can modify the behavior of response objects.

Exceptions

• ServletException:- Extends java.lang.Exception to provide a base class for defining servlet-related extensions.

• UnavailableException:- Extends ServletException to indicate that a servlet is temporarily or permanently unavailable.

The javax.servlet.http Package

The javax.servlet.http package defines eight interfaces and seven classes. These interfaces and classes are as follows:

Interfaces

The interfaces include the following:

• HttpServletRequest:- Extends javax.servlet.ServletRequest to support HTTP.

• HttpServletResponse:- Extends javax.servlet.ServletResponse to support HTTP.

• HttpSession:- Defines methods that provide access to persistent session-state information.

• HttpSessionActivationListener:- Implemented to handle the HttpSessionActivationEvent.

• HttpSessionAttributeListener:- Implemented to handle the HttpSessionAttributeEvent.

• HttpSessionBindingListener:- Implemented by objects that listen for HttpSessionBindingEvent events.

• HttpSessionListener:- Implemented to handle the HttpSessionEvent.

Classes

The classes include the following:

• Cookie:- Encapsulates HTTP cookies.

• HttpServlet:- An abstract class that extends javax.servlet.GenericServlet to provide support for HTTP.

• HttpServletRequestWrapper:- Provides the capability to wrap and modify incoming HttpServletRequest objects.

• HttpServletResponseWrapper:- Provides the capability to wrap and modify outgoing HttpServletResponse objects.

• HttpSessionBindingEvent:- Extends java.util.EventObject to define an event that is sent to an HttpSessionBindingListener when an object is bound or unbound from the current HttpSession.

• HttpSessionEvent:- Parent class of HttpSessionBindingEvent.

Is jsp thread safe by default?

User Avatar

Asked by Wiki User

No. JSPs are not thread safe by default

What does template contain in web application?

User Avatar

Asked by Wiki User

It contains instruction examples, text, and checkpoint standards for individual phase in the activity.

You must be able to review and update the output document created from the template at regular intervals throughout the application life cycle. After developing the application design, you can easily add more details step by step in the output document.

Differentiate Java applet and Java servlet?

User Avatar

Asked by Wiki User

Java Applet is an application designed to transmit on internet to execute on java compatible browsers. Java Servlet is a server side program used to provide services to clients.

How do you create object of javabeen in servlet?

User Avatar

Asked by Wiki User

A JavaBean is nothing but a regular Java Class and hence it can be instantiated using the new keyword and invoking the bean constructor

How do you refresh a JSP page?

User Avatar

Asked by Wiki User

by using the meta tag <meta HTTP-EQUIV="Refresh" CONTENT="5(duration in sec)">

Why is PHP better than JSP?

User Avatar

Asked by Wiki User

in the past ive found jsp to be much slower than PHP (correct me if im wrong) PHP is a solid stable web language and much faster in my opinion :D

How do JSP methods get translated to Servlet methods?

User Avatar

Asked by Wiki User

A JSP gets converted into a Servlet for execution and hence the methods in a JSP are similar to the ones in a Servlet.

  • Scriptlets and Expressions will end up in the body of doGet or doPost
  • Declarations will end up as instance variables
  • jspInit() and jspDestroy() will get translated to Servlet's init() and destroy() methods

Can you override the life cycle methods of a JSP?

User Avatar

Asked by Wiki User

You cannot override the jspService() method but you can override the jspInit() and jspDestroy() methods

Write a program using servlet and JDBC for developing an onine application to create a database?

User Avatar

Asked by Wiki User

// You can use this sample servlet as a starting point to connect to

// your database included with useractive account.

//

// Portions copied from Sun's HelloWorldServlet.java

// You are free to use this code in any way you chose

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

import java.sql.*;

public

class HelloWorldServlet extends HttpServlet {

public void doGet (HttpServletRequest req, HttpServletResponse res)

throws ServletException, IOException {

res.setContentType("text/html");

ServletOutputStream out = res.getOutputStream();

out.println("<html>");

out.println("<head><title>Hello World</title></head>");

out.println("<body>");

try {

// The newInstance() call is a work around for some

// broken Java implementations

out.println("asdf");

Class.forName("org.gjt.mm.mysql.Driver").newInstance();

}

catch (Exception E) {

out.println("Unable to load driver.");

E.printStackTrace();

}

out.println("<br><hr>");

try {

Connection Conn =

DriverManager.getConnection("jdbc:mysql://sql.useractive.com/USERNAME?user=USERNAME&password=PASSWORD");

// Do something with the Connection

Statement Stmt = Conn.createStatement();

ResultSet RS = Stmt.executeQuery("SELECT * from SOMETABLE");

while (RS.next()) {

out.println(RS.getString(1));

}

// Clean up after ourselves

RS.close();

Stmt.close();

Conn.close();

}

catch (SQLException E) {

out.println("SQLException: " + E.getMessage());

out.println("SQLState: " + E.getSQLState());

out.println("VendorError: " + E.getErrorCode());

}

out.println("<h1>Hello World. Sun... 1.4</h1>");

out.println("</body></html>");

}

public String getServletInfo() {

return "Create a page that says <i>Hello World</i> and send it back";

}

}