- Briefly explain any seven JSP implicit objects.
To simplify code in JSP expressions and scriplets, servlet creates several objects to be used by the JSP engine. These objects are called as implicit objects. Implicit objects are also known as predefined variables. Developers can call them directly without being explicitly declared. Some of the implicit objects are :
- The out object
- The request object
- The response object
- The pageContext object
- The session object
- The application object
- The config Object
- The page Object
- The exception Object
The out object :
The out implicit object is an instance of a javax.servlet.jsp.JspWriter and is used to send content in a response.
The initial JspWriter object is instantiated differently depending on whether the page is buffered or not. Buffering can be easily turned off by using the buffered = ‘false’ attribute of the page directive.By default, every JSP page has buffering turned on, which almost always improves performance.
A buffered out object collects and sends data in blocks, typically providing the best
total throughput. With buffering the PrintWriter is created when the first block is sent,
actually the first time that flush() is called. With unbuffered output the PrintWriter object will be immediately created and
referenced to the out object. In this situation, data sent to the out object is immediately sent to the output stream. The PrintWriter will be created using the default settings and header information determined by the server.
In the case of a buffered out object the OutputStream is not established until the first time that the buffer is flushed. When the buffer gets flushed depends largely on the autoFlush and bufferSize attributes of the page directive. It is usually best to set the
header information before anything is sent to the out object It is very difficult to set page headers with an unbuffered out object. When an unbuffered page is created the OutputStream is established almost immediately.
The request object :
The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a client requests a page the JSP engine creates a new object to represent that request. The request object provides methods to get the HTTP header information including form data, cookies, HTTP methods etc. It provides means to identify both the client and the server, e.g., it uses
request.getRequestURI() and request.getServerName() to identify the server.
The response object :
The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the server creates the request object, it also creates an object to represent the response to the client. The response object defines the interfaces that deal with creating new HTTP headers. The response object deals with the stream of data back to the client.Through this object the JSP programmer can add new cookies or date stamps, HTTP status codes, etc.
The session object :
The session object is used to track client session between client requests.The session object is an instance of javax.servlet.http.HttpSession. Sessions can be used to store arbitrary
information between client requests.It behaves exactly the same way that session objects behave under Java Servlets.
The Config object :
The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around the ServletConfig object for the generated servlet. This object allows the JSP programmer access to the Servlet or JSP engine initialization parameters such as the paths or file locations etc.
The page Object :
This object is an actual reference to the instance of the page. It can be thought of as an object that represents the entire JSP page.. When the JSP page is first instantiated the page object is created by obtaining a reference to this object.
The application Object:
The application object is direct wrapper around the ServletContext object for the generated Servlet and in reality an instance of a javax.servlet.ServletContext object. This object is a representation of the JSP page through its entire lifecycle. This object is created when the JSP page is initialized and will be removed when the JSP page is removed by the jspDestroy() method.
2. What are Cookies ? Briefly explain the following methods of Cookie
class:
(i) setMaxAge
(ii) setVersion
(iii) setDomain
(iv) setPath
Cookies are text files stored on the client computer and they are kept for various information tracking purposes. A cookie is a bit of information sent by a web server to a browser is stored it on a client machine that can later be read back from that browser. cookies offer an elegant, efficient, easy way to implement session tracking. Cookies provide as automatic introduction for each request as you could hope for. For each request, a cookie can automatically provide a client’s session ID or perhaps a list of the client’s preferences. JSP transparently supports HTTP cookies using underlying servlet technology.
i) setMaxAge : This method sets how much time (in seconds) should elapse before the cookie expires. If you don’t set this, the cookie will last only for the current session. A negative value indicates the default, that the cookie should expire when the browser exits. A zero value tells the browser to delete the cookie immediately.
Syntax : public void Cookie.setMaxAge(int expiry)
ii) setVersion : This method sets the version of a cookie.
Syntax : public void Cookie.setVersion(int v)
iii)setDomain: This method returns the domain of this cookie, or null if not defined.
Syntax : public String getDomain();
iv)setPath: It indicates to the user agent that this cookie should only be sent via secure channels (such as HTTPS). This should only be set when the cookie’s originating server used a secure protocol to set the cookie’s value.
Syntax : public void Cookie.setPath(String uri)
3. What is the need of web security ? Explain data integrity and system integrity in the context of web security.
Web Security is defined as technological and managerial procedures applied to computer systems to ensure the availability, integrity, and confidentiality of information. It means protection of intergrity, availability and confedentiality of computer assets and services from threats and vulnerabilites.
Web security is divided into two :
- Computer security
- network security
Computer security : It is defined as the technology and managerial procedures applied to computer systems to ensure the availability, integrity, and confidentiality of the data managed by the computer. It is the process of securing a standalone computer.
Network security : It is defined as the protection of networks and their services from unauthorised
modification destruction, or disclosure and provision of assurance that the network performs its critical functions correctly and that are nor harmful side effects. It is the process of securing an entire network of computers.
Integrity has two sides :
- Data integrity
- System integrity
Data integrity : This property is the the assuarance of that data has not been altered in an unauthorised manner while in storage, during processing or while in transit. Another side of data integrity is the assuarance that data can only be accessed and altered by those authorised to do so. This is done by using a number called Message Integrity Code(MIC) or Message Authentication Code(MAC).
System integrity : This is the quality that a system has when performing the intended function in an unimpaired manner, free from deliberate or inadvertent unauthorized manipulation of the system.
4. Create a LOGIN page using JSP and JDBC. Database is created in Oracle.
index.jsp
|<a href= “login.jsp”>login</a>
<%@ include file=”index.jsp” %><hr/>
<h3>Login Form</h3>
<% String profile_msg=(String)request.getAttribute(“profile_msg”); if(profile_msg!=null){ out.print(profile_msg); }
String login_msg=(String)request.getAttribute(“login_msg”); if(login_msg!=null){ out.print(login_msg); } %>
<br/>
<form action=”loginprocess.jsp” method=”post”>
Email:<input type=”text” name=”email”/><br/><br/>
Password:<input type=”password” name=”password”/><br/><br/>
<input type=”submit” value=”login”/>
</form>
loginprocess.jsp
<%@page import=”bean.LoginDao”%>
<jsp:useBean id=”obj” class=”bean.LoginBean”/>
<jsp:setProperty property=”*” name=”obj”/>
<% boolean status=LoginDao.validate(obj); if(status){ out.println(“You r successfully logged in”); session.setAttribute(“session”,”TRUE”); }
else { out.print(“Sorry, email or password error”);
%> <jsp:include page=”index.jsp”><jsp:include>
<%
} %>
LoginBean.java
package bean;
public class LoginBean {
private String email,pass;
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
}
Provider.java
package bean;
public interface Provider {
String DRIVER=”oracle.jdbc.driver.OracleDriver”;
String CONNECTION_URL=”jdbc:oracle:thin:@localhost:1521:xe”;
String USERNAME=”system”;
String PASSWORD=”oracle”;
}
ConnectionProvider.java
package bean;
import java.sql.; import static bean.Provider.*;
public class ConnectionProvider {
private static Connection con=null;
static{
try{
Class.forName(DRIVER);
con=DriverManager.getConnection(CONNECTION_URL,USERNAME,PASSWORD);
}catch(Exception e){}
}
public static Connection getCon(){
return con;
}
}
LoginDao.java
package bean;
import java.sql.*;
public class LoginDao {
public static boolean validate(LoginBean bean){
boolean status=false;
try{
Connection con=ConnectionProvider.getCon();
PreparedStatement ps=con.prepareStatement(
“select * from user432 where email=? and pass=?”);
ps.setString(1,bean.getEmail());
ps.setString(2, bean.getPass());
ResultSet rs=ps.executeQuery();
status=rs.next();
}catch(Exception e){}
return status;
}
}
5. Define a scriplet and expressions in JSP ? Create a simple JSP page which includes declaration, scriplets, expressions and comments tag in it.
JSP expression : Expression tag is one of the scripting elements in JSP.A JSP expression is used to insert the value of a scripting language expression, converted into a string, into the data stream returned to the client. Printing the output of a Java fragment is one of the most common tasks utilized in JSP pages. For this purpose, we can use the out.println() method. But having several
out.println() method tends to be cumbersome. In this case, JSP expressions are used.
Syntax :
JSP Syntax: <%= code %>
XML Syntax: <jsp:expression>code</jsp:expression>
Example:
<html>
<body>
<%= “welcome to jsp” %>
</body>
</html>
Above is a JSP expression tag to display a welcome message.
JSP scriplet :Scriptlets are the most common JSP syntax element.Scriptlet is a portion of regular Java code embedded in the JSP content within <% … %> tags
A scriptlet tag is used to execute java source code in JSP.
JSP Syntax: <% code %>
XML Syntax: <jsp:scriplet>code</jsp:scriplet>
Example :
<html>
<body>
<% out.print(“welcome to jsp”); %>
</body>
</html>
Above is an JSP scriplet to display a welcome message.
<%@ page language=”java” contentType=”text/html; charset=ISO-8859-1″ pageEncoding=”ISO-8859-1″%>
<html>
<head>
<meta http-equiv=”Content-Type” content=”text/html”; charset=ISO-8859-1″>
<title>Scriplet and Expression example</title>
</head>
<body>
<%– This is a JSP example with declaration, scriplet, comment and expression –%>
<% out.println(“This is the example”);%>
<% out.println(“The number is”);%>
<%! int num1=12;int num2=12;%>
<%=num1*num2 %>
Today’s date: <%=(new java.util.Date()).toLocaleString()%>
</body>
</html>
In the above JSP page,
<%– This is a JSP example with scriplets, comments , expressions –%> : this line is a comment
<% out.println(“This is guru JSP Example”); %> :this line is a jsp scriplet
<%! int num1 = 12; int num2 = 12; %>: this line is declaration of variables num12 and num32 initializing with 12
<%= num1*num2 %>: In this line are using an expression where we are multiplying two numbers num12 and num32.
6. Define authentication mechanism? Explain any two basic mechanisms through which a web client can authenticate a user to a web server using http authentication.
Authentication is proving that a user is whom s/he claims to be. That proof may be something the user knows(password),something the user has(smartcard),or something about the user that proves his identity(fingerprint).
A web client can authenticate a user to a we server using one of the following authentication mechanism:
1.HTTP Basic Authentication
2.HTTP Digest Authentication
3.HTTPS Client Authentication
4.Form Based Authentication
1.HTTP Basic Authentication:
HTTP Basic Authentication is the default when you do not specify an authentication mechanism.HTTP Basic Authentication, which is based on a username and password.It is the authentication mechanism defined in the HTTP/io specification.
A web server requests a web client to authenticate the user.As a part of the request, the web server passes the realm (a string) in which the user is to be authenticated. The realm string of basic authentication does not have to reflect any particular security policy domain.The web client obtains the username and the password from the user and transmits them to the web server. The web server then authenticates the user in the specified realm.
Basic authentication is not a secure authentication as user passwords are sent in simple base64 encoding, and there is no provision for target server authentication.
When basic authentication is used, the following actions occur:
1.A client requests access to a protected resource.
2.The web server returns a dialog box that requests the usernamr and password.
- The client submits the username and password to the server.
- The server validates the candidates and, if successful, returns the requested resource.
Form Based Authentication:
The look and feel of the login screen cannot be varied using the web browser’s built in authentication mechanisms. Form based authentication mechasim allows a developer to Control the look and feel of the login screen.
The web application deployment descriptor, contains entries for a login form and error page. The login form must contain fields for entering a username and a password. These fields must be named j_username and j_password, respectively.
When a user attempts to access a protected web resource, the container checks the user authentication. If the user is authenticated and has the authority to access the resource, the requested web resource is activated and a reference to it is returned. If the user is not authenticated, all of the following steps occur:
1) The login form associated with the security constraint is sent to the client and the URL path triggering the authentication stored by the container.
2)The user is asked to fill out the form, including the username and password fields.
3) The client posts the form back to the server.
4) The container attemts to authenticate the user using the username and password fields.
5)If authentication succeeds, the authenticated user’s principal is checked to see if it ia in an authorised role for accessing the resource.
6)If authentication fails, the error page is returned using either a forward or a redirect message. The status code of the response is set to 200.
7) If the user is authorised, the client is redirected to the resource using the stored URL path.
The error page returned to the user who is not authenticated contains information about the failure.
Form Based Authentication is less secure, because the user password is transmitted as a plain text and the target server is not authenticated.
7. Write a servlet program to fetch and display all the fields of student table having 10 records with field names as student name, enrollment number, email ID and grades achieved in TEE.
import java.io.;
import java.sql.;
import javax.servlet.Servlet.;
import javax.servlet.http.;
public class DisplayField extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws servletException, IOException
{
Connection con=null;
Statement stmnt=null;
ResultSet rs=null;
response.setContentType(“text/html”);
PrinterWriter out=response.getWriter();
try{
//loading the Oracle Driver
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
//getting connection to the database
Connection con=DriverManager.getConnection(jdbc:odbc:Access);
//Creating a statement Object
Statement stmnt=con.createStatement();
//xecuting an SQL query and get a resultSet
rs = stmnt.executeQuery(“SELECT * FROM student”);
// Displaying the result in the form of a table
//Printing column names
out.println(“<center><p><table border=’3′ cellpadding=’5′>”);
out.println(“<tr>”);
out.println(“<th>Student name</th>”);
out.println(“Enrollment number”);
out.println(“Email ID”);
out.println(“Grade”);
out.println(“</tr>”);
while(rs.next())
{
out.println(“<tr>”); out.println(“<td>” + rs.getString(“s_name”) + “</td>”); out.println(“<td>” + rs.getString(“enrolment_no”) + “</td>”); out.println(“<td>” + rs.getString(“email_id”) + “</td>”); out.println(“<td>” + rs.getString(“grade”) + “</td>”); out.println(“</tr>”);
}
catch(ClassNotFoundException e){
out.println(“Couldn’t load database driver:”+e.getMessage());
}
finally{
//closing database connection
try{
if(con!=null)
con.close();
out.println(“</table></p></center>”);
}
catch(Exception e) { e.printStackTrace(); }
}
}
8. Define DTD. What is its use in XML?Write the DTD of an XML document that describe the bank account which has the following attributes :
Account number (mandatory)
Customer_id (can be multiple)
First name (mandatory)
Middle name (optional)
Last name (optional)
Account type (mandatory)
Balance (mandatory)
DTD stands for document type definition.A DTD defines the structure of the content of an XML document, thereby allowing you to store data in a consistent format. Document type definition lists the elements, attributes, entities, and notations that can be used in a document, as well as their possible relationships to one another. DTD specifies, a set of rules for the structure of a document. If present, the document type declaration must be the first, in the document after optional processing instructions and comments. The document type declaration identifies the root element of the document and may contain additional declarations. All XML documents must have a single root element that contains all the contents of the document. Additional declarations may come from an external definition (a DTD) or be included directly in the document. Creating DTD is just like creating a table in a database. In DTDs, you specify the structure of the data by declaring the element to denote the data. You can also specify
whether providing a value for the element is mandatory or optional.
After identifying the elements that can be used for storing structured data, they can be declared in a DTD. The XML document can be checked against the DTD. We can declare Element with the following syntax:
elementname specifies the name of the element and content-type or content-model specifies whether the element contains textual data or other elements. For e.g. #PCDATA which specifies that element can store parsed character
data(i.e. text). An element can be empty, unrestricted or container example.
<!bankcustomer.xml–>
<! represent the information of customer in XML documents>
<!DOCTYPE bankcustomer SYSTEM bankcustomer.dtd”>
<information>
<account>
<account_number>HVC1678</account_number>
<account_type>Savings</account_type>
<balance>25000</balance>
</account>
<customer>
<customer_id>104567</customer_id>
<first_name>Ram</first_name>
<last_name>Narayan</last_name>
</customer>
</information>
<content> This is information of customer of a bank.</content>
</bankcustomer>
<?XML version=”1.0″ rmd=”internal”?>
<!ELEMENT bank(account,customer)>
<!ELEMENT account(account_number,account_type,balance)>
<!ELEMENT customer(customer_id,first_name,last_name,middle_name)>
<!ELEMENT customer_id(#PCDATA)+>
<!ELEMENT first_name(#PCDATA)#REQUIRED>
<!ELEMENT middle_name(#PCDATA)#REQUIRED>
<!ELEMENT last_name(#PCDATA)#implied>
<!ELEMENT account_number(#PCDATA)#REQUIRED>
<!ELEMENT account_type(#PCDATA)#REQUIRED>
<!ELEMENT balance(#PCDATA)#REQUIRED>
10. What are the advantages of using Java’s multiple layer security implementation ? Explain with the help of an example program.
Implementation without knowledge of inner working of the Operating System, platform independence, enhancing security with multiple security features, In addition, a J2EE server without much customization may support the EJB mapping that was described earlier in the article. Java also provides some other additional methods of security ranging from digital signatures to the JAAS specification that can be used to protect the class files against unauthorized access.
The first step is to create delegate classes to wrap the security functionality contained in the Java Access Control Model classes. By wrapping the method calls and interfaces, the developer can ensure that the majority of the code in the system can
function independently of the security implementation through the delegation pattern, the remainder of the code can perform security functionality without obtaining specific knowledge of the inner workings of security model.
The first main component is the User. The code that implements the interface can delegate calls to the java.security.Principal interface. For example, to retrieve a user’s telephone number, implement a method called getPhoneNumber(). Another approach to obtaining this user data involves the use of XML. Convert data stored in the database into an XMLDocument from which data
could be accessed by walking the tree.
The second main component is interface. The classes that implement this interface use the implementation of the java.security.acl.Permission interface to execute their functionality. In a Web-based system, there is a need to identify both the name of the action and the URL related to that action.
The last major component is the WebSecurityManager object and this is responsible for performing the duties related to user management, features management, and the access control lists that establish the relationships between users and desired features.
WebSecurityManager can be implemented in many ways including, but not limited to, a Java bean used by JSP, a servlet, an EJB, or a CORBA/RMI service.
Public void service (HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
// check if a session has already been created for this user don’t create a new session.
HttpSession session = request.getSession( false);
String sRequestedFeature = request.getParameter(Constants.FEATURE);
if ( session != null)
{
// retrieve User object
User currentUser = (User) session.getValue(Constants.USER);
Feature featureRequested = null;
try {
// get the page from Web Security Manager
featureRequested = WebSecurityManager.getFeature(
sRequestedFeature);
} catch ( WebSecurityManagerException smE)
{
smE.printStackTrace();
}
if ( WebSecurityManager.isUserAuthenticated( currentUser,
featureRequested) )
{
// get page from feature
String sRequestedPage = featureRequested.getFeaturePath();
// redirect to the requested page
response.sendRedirect( Constants.LOGIN2 + sRequestedPage);
} else {
// redirect to the error page
response.sendRedirect( Constants.ERROR + sRequestedFeature);
}
} else {
// redirect to the login servlet (passing parameter)
response.sendRedirect( Constants.LOGIN2 + sRequestedFeature);
}
}
10. What is the purpose of message-driven beans and define its structure? Explain the various circumstances under which a message-driven bean should be used. What makes message driven beans different from session beans?
A message-driven bean is an enterprise bean that allows Java EE applications to process messages asynchronously. This type of bean normally acts as a JMS message listener, which is similar to an event listener but receives JMS messages instead of events. The messages can be sent by any Java EE component (an application client, another enterprise bean, or a web component) or by a JMS application or system that does not use Java EE technology. Message-driven beans can process JMS messages or other kinds of messages.
A message-driven bean acts as a consumer of asynchronous messages. It cannot be called for, directly by clients, but is activated by the container when a message arrives. Clients interact with these EJBs by sending messages to the queues or topics to which they are listening. Although a message-driven EJB cannot be called for, directly by clients, it can call other EJBs itself.
A message driven bean has 2 states:
1) Does not exist: In this state, the bean instance simply does not exist. Initially, the bean exists in the does not exist state.
2)Pooled state: After invoking the ejbCreate() method, the MDB instance is in the ready pool, waiting to consume incoming messages. Since, MDBs are stateless, all instances of MDBs in the pool are identical; they’re allocated to process a message
and then return to the pool.
Message-driven beans have the following characteristics.
- They execute upon receipt of a single client message.
- They are invoked asynchronously.
- They are relatively short-lived.
- They do not represent directly shared data in the database, but they can access and update this data.
- They can be transaction-aware.
- They are stateless.
Session beans allow you to send JMS messages and to receive them synchronously but not asynchronously. To avoid tying up server resources, do not to use blocking synchronous receives in a server-side component; in general, JMS messages should not be sent or received synchronously. To receive messages asynchronously, use a message-driven bean.
Bean developers should consider using message-driven beans under certain
circumstances:
• To have messages automatically delivered.
• To implement asynchronous messaging.
• To integrate applications in a loosely coupled but reliable manner.
• To have message delivery drive other events in the system workflow.
• To create message selectors, whereby specific messages serve as triggers for
subsequent actions.
The most visible difference between message-driven beans and session beans is that clients do not access message-driven beans through interfaces. Interfaces are described in the section Accessing Enterprise Beans. Unlike a session bean, a message-driven bean has only a bean class.
In several respects, a message-driven bean resembles a stateless session bean.
A message-driven bean’s instances retain no data or conversational state for a specific client.
All instances of a message-driven bean are equivalent, allowing the EJB container to assign a message to any message-driven bean instance. The container can pool these instances to allow streams of messages to be processed concurrently.
A single message-driven bean can process messages from multiple clients.
The instance variables of the message-driven bean instance can contain some state across the handling of client messages, such as a JMS API connection, an open database connection, or an object reference to an enterprise bean object.
Leave a comment