Você está na página 1de 20

Answer 1a

<?xml version="1.0" encoding="UTF-8"?>


<phonebook xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="file:/Volumes/VST/XML/phonebook.xsd">
<department>
<deptname>Sales</deptname>
<deptphone>03351101110</deptphone>
<deptfax>7065423743</deptfax>
<deptemail>sales@thesfactory.com</deptemail>
<employee>
<empid>10001</empid>
<empfname>Raj</empfname>
<emplname>Khanna</emplname>
<empphone>9908520111</empphone>
<empemail>rjkh@thesfactory.com</empemail>
</employee>
<employee>
<empid>10002</empid>
<empfname>Disha</empfname>
<emplname>Pandit</emplname>
<empphone>9987415002</empphone>
<empemail>disha@thesfactory.com</empemail>
</employee>
<employee>
<empid>10003</empid>
<empfname>Mary</empfname>
<emplname>Hunt</emplname>
<empphone>8005005001</empphone>
<empemail>mhunt@thesfactory.com</empemail>
</employee>
<employee>
<empid>10004</empid>
<empfname>Irfan</empfname>
<emplname>Khan</emplname>
<empphone>9981255002</empphone>
<empemail>Irfkhn@thesfactory.com</empemail>
</employee>
<employee>
<empid>10005</empid>
<empfname>Mukesh</empfname>
<emplname>Agarwal</emplname>
<empphone>9002123456</empphone>
<empemail>mukeshag@thesfactory.com</empemail>
</employee>

</department>
<department>
<deptname>CustomerService</deptname>
<deptphone>03351101131</deptphone>
<deptfax>7065423823</deptfax>
<deptemail>service@thesfactory.com</deptemail>
<employee>
<empid>20001</empid>
<empfname>Mahesh</empfname>
<emplname>Jha</emplname>
<empphone>8908320121</empphone>
<empemail>mahesh@thesfactory.com</empemail>
</employee>
<employee>
<empid>20002</empid>
<empfname>Iqbal</empfname>
<emplname>Ansari</emplname>
<empphone>8004569101</empphone>
<empemail>iqbal@thesfactory.com</empemail>
</employee>
<employee>
<empid>20003</empid>
<empfname>Payal</empfname>
<emplname>Malhotra</emplname>
<empphone>8123457721</empphone>
<empemail>payal@thesfactory.com</empemail>
</employee>

<employee>
<empid>20004</empid>
<empfname>Salim</empfname>
<emplname>Malik</emplname>
<empphone>8922220121</empphone>
<empemail>salim@thesfactory.com</empemail>
</employee>
<employee>
<empid>20005</empid>
<empfname>Edward</empfname>
<emplname>Paul</emplname>
<empphone>9908320121</empphone>
<empemail>edp@thesfactory.com</empemail>
</employee>

</department>
</phonebook>

Xml vs dtd

Key Differences

You can guess from the XML Schemas that it must be written in the XML, while DTDs didnt
written is XML.
As compared to the DTD, the XML Schema is strongly typed.
You will not find the derived and built-in data types in the DTD as these are available in the
XML Schema only.
It is the functionality of the DTD to allow inline definitions that is not available in the XML
Schema.
The DTD is considered to be less powerful than XML schema.
With the help of the DTD, you can obtain the basic structure or grammar for the main aim of
defining a XML document. You will discover the methods to define the constraints on the data
contained in the document while using XML schema.
End of 1a

Answer 1b
An XML parser (or XML processor) is the software that determine
determiness the content and structure of an
XML document by combining XML document and DTD (if any present).
XML parser is the software that reads XML files and makes the information from those files available
to applications and other programming languages. The XML parser is responsible for testing whether
a document is well-formed
formed and, if, given a DTD or XML schema, whether will also check for validity
(i.e., it determines if the document follows the rules of the DTD or schema).

XML Parser builds tree structures from XML documents. For example, an XML parser would build the
tree structure shown in Figure 2 for the previously mentioned example ignou.xml. If, this tree
structure is created successfully without using a DTD, the XML document is considered well-formed.
If, the tree stucture is created successfully and DTD is used, the XML document is considered valid.
Hence, there can be two types of XML parsers : validating (i.e., enforces DTD rules) and non
non-validating
(i.e., ignores DTD rules).

End of answer 1b

Answer 2a

<%@ page language="java" contentType="text/html; charset=UTF


charset=UTF-8"

pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD


W3C//DTD HTML 4.01 Transitional//EN"

"http://www.w3.org/TR/html4/loose.dtd">

<html>

<head>

<meta http-equiv="Content-Type"
Type" content="text/html; charset=UTF
charset=UTF-8">

<title>JSP List Users Records</title>

</head>

<body>

<sql:setDataSource

var="myDS"
driver="com.mysql.jdbc.Driver"

url="jdbc:mysql://localhost:3306/mydb"

user="root" password="secret"

/>

Try{

<sql:query var="listUsers" dataSource="${myDS}">

SELECT * FROM users;

</sql:query>

<div align="center">

<table border="1" cellpadding="5">

<caption><h2>Info</h2></caption>

<tr>

<th>ID</th>

<th>First_Name</th>

<th>Last_Name</th>

<th>Balance</th>

<th>Profession</th>

</tr>

<c:forEach var="user" items="${listUsers.rows}">

<tr>

<td><c:out value="${user.id}" /></td>

<td><c:out value="${user.first_name}" /></td>

<td><c:out value="${user.last_name}" /></td>

<td><c:out value="${user.balance}" /></td>

</tr>

</c:forEach>

</table>
</div>

catch(SQLException ex){

out.print("<h1>No record found<h1>");

</body></html> [End of 2a]

Answer 2b

To connect to a MySQLW databaseW from JavaSW via JDBCW, you need a MySQL JDBC driver and
accompanying classes. The latest MySQL Connector/J driver library can be downloaded from
http://www.mysql.com/products/connector/j/.

After downloading the Connector/J library, you should add it to the classpath W of the project. In the
project below, the mysql-connector-java-5.0.4-bin.jar file has been added to the lib/ directory of the
project, and this jar W file was added to the project classpath.

The MySqlJdbcTest class is shown below. It first creates a com.mysql.jdbc.Driver object via the call to
Class.forName("com.mysql.jdbc.Driver").newInstance().

It's necessary to get a connection via DriverManager.getConnection. It's possible to specify the
database user and password on the URL string passed to the method, and this is shown commented
out in the example. The user and password can also be passed as separate parameters, and this is
shown in the example (the connectionUser and connectionPassword variables).

A statement is created and the "SELECT * FROM employees" query is executed, and the results are
returned as a result set. The result set it iterated over, and the results of each row are displayed

in the finally block, the result set, statement, and connection are all explicitly closed. This is a VERY
good practice so that database connections do not get leaked when you write JDBC code.

End of 2b

Answer 3a

CREATE TABLE "REGIST"

1. ( "FIRST_NAME" VARCHAR2(4000),
2. LAST_NAME VARCHAR2(4000),
3. CONTACT_NUMBER VARCHAR2(4000),
4. "EMAIL" VARCHAR2(4000),
5. "AGE" VARCHAR2(4000),
6. COURSE_NAME VARCHAR2(4000),
7.
8. )
9. /

index.jsp
function Validation()
{
for(var i=0; i < document.form1.ucourse.length; i++)
{
if(!document.form1.course[i].checked)
{
alert("Please Select course");
return false;
}
else if (document.form1.course.checked)>3
{
alert("only 3 allowed");
return false;

else
alert(Click OK to display selected courses);
return true;
}
}
}
</script>
function ajaxCall(){
var name = jQuery("#name").val();
var userName = jQuery("#userName").val();
var password= jQuery("#password").val();
alert(name);
alert(userName);
alert(password);

jQuery.ajax({
url : "GetUserServlet",
method: "GET",
type : "JSON",
data : "name="+name+"&userName="+userName+"&password="+password,// query parameters
1st
success : function(response){
$('#ajaxGetUserServletResponse').text(response);

}
});

<form action"/yourServlet" method ="post">


<input type="text" name="ufname"/>
<input type="text" name="ulname"/>
<input type="text" name="unumber"/>
<input type="text" name="uemail"/>
<input type="text" name="age"/>
<input type="text" name="ucourse"/>

<input type="SUBMIT" />


</form>
<form action="process.jsp">

<input type="text" name="funame" value="First_Name..." onclick="this.value=''"/><br/>

<input type="text" name="luname" value="First_Name..." onclick="this.value=''"/><br/>

<input type="number" name="unumber" value="Contact..." onclick="this.value=''"/><br/>

<input type="text" name="uemail" value="Email ID..." onclick="this.value=''"/><br/>

<input type=" number" name="uage" value="Age..." onclick="this.value=''"/><br/>

<input type="text" name="ucourse" value="Course..." onclick="this.value=''"/><br/>

<p><input type="checkbox" name="ucourse" value="MCS011"/>Math</p>


<p><input type="checkbox" name="ucourse" value="MCS012"/>Accounts</p>
<p><input type="checkbox" name="ucourse" value="MCS021"/>Discrete</p>
<p><input type="checkbox" name="ucourse" value="MCS022"/>Operating system</p>
<p><input type="checkbox" name="ucourse" value="MCS023"/>Assembly Language</p>
<p><input type="checkbox" name="ucourse" value="MCS031"/>Algorithm</p>
<p><input type="checkbox" name="ucourse" value="MCS032"/>Advanced Discreet</p>
<p><input type="checkbox" name="ucourse" value="MCS033"/>System Design</p>
<p><input type="checkbox" name="ucourse" value="MCS041"/>Database</p>
<p><input type="checkbox" name="ucourse" value="MCS042"/>Networking</p>
<p><input type="checkbox" name="ucourse" value="MCS051"/>Java</p>
<p><input type="checkbox" name="ucourse" value="MCS052"/>PHP</p>
<p><input type="checkbox" name="ucourse" value="MCS061"/>Numerical Techniques</p>

1. <input type="submit" value="register"/ onsubmit=returnvalidation()>


2. </form>

process.jsp

1. <%@page import="bean.RegisterDao"%>
2. <jsp:useBean id="obj" class="bean.Regist"/>
3.
4. <jsp:setProperty property="*" name="obj"/>
5.
6. <%
7. int status=RegisterDao.register(obj);
8. if(status>0)
9. out.print("You are successfully registered");
10. %>

User.java

1. package bean;
2.
3. public class User {
4. private String ufname,ulname,unumber,uemail,uage,ucourse;
5.
6. public String getUfname() {
7. return ufname;
8. }
9.
10. public void setUfname(String ufname) {
11. this.ufname = ufname;
12. }
13.
14. public String getUlname() {
15. return ulname;
16. }
17.
18. public void setUlname(String ulname) {
19. this.ulname = ulname;
20. }
21.
22.
23. public String getUnumber() {
24. return unumber;
25. }
26.
27. public void setUnumber(String unumber) {
28. this.unumber = unumber;
29. }
30.
31. public String getUemail() {
32. return uemail;
33. }
34.
35. public void setUemail(String uemail) {
36. this.uemail = uemail;
37. }
38.
39. public String getUage() {
40. return uage;
41. }
42.
43. public void setUage(String uage) {
44. this.uage = uage;
45. }
46.
47.
48. public String getUcourse() {
49. return ucourse;
50. }
51.
52. public void setUcourse(String ucourse) {
53. this.ucourse = ucourse;
54. }
55. }
Provider.java

1. package bean;
2.
3. public interface Provider {
4. String DRIVER="oracle.jdbc.driver.OracleDriver";
5. String CONNECTION_URL="jdbc:oracle:thin:@localhost:1521:xe";
6. String USERNAME="system";
7. String PASSWORD="oracle";
8.
9. }

ConnectionProvider.java

1. package bean;
2. import java.sql.*;
3. import static bean.Provider.*;
4.
5. public class ConnectionProvider {
6. private static Connection con=null;
7. static{
8. try{
9. Class.forName(DRIVER);
10. con=DriverManager.getConnection(CONNECTION_URL,USERNAME,PASSWORD);
11. }catch(Exception e){}
12. }
13.
14. public static Connection getCon(){
15. return con;
16. }
17.
18. }

Regist.java

package bean;

import java.sql.*;

1. public class Regist {


2.
3. public static int register(User u){
4. int status=0;
5. try{
6. Connection con=ConnectionProvider.getCon();
7. PreparedStatement ps=con.prepareStatement("insert into regist values(?,?,?,?,?,?)");
8. ps.setString(1,u.getUfname());
9. ps.setString(2,u.getUlname());
10. ps.setString(3,u.getUnumber());
11. ps.setString(4,u.getUemail());
12. ps.setString(5,u.getUage());
13. ps.setString(6,u.getUcourse());
14.
15. status=ps.executeUpdate();
16. }catch(Exception e){}
17.
18. return status;
19. }
20.
21. }

1. <script>
2. function validateform(){
3. var name=document.myform.name.value;
4. var password=document.myform.password.value;
5.
6. if (ufname==null || ulname==""){
7. alert("Name can't be blank");
8. return false;
9. }else if(uemail==null){
10. alert("Email is mandatory.");
11. return false;
12. }
13. }
14. </script>
15. <body>

Your Servlet

doPost(....){
String age = request.getParameter("ufname");
String age = request.getParameter("ulname");
String age = request.getParameter("unumber");
String age = request.getParameter("uemail");
String age = request.getParameter("age");
String age = request.getParameter("ucourse");
}

[End of 3a]

Answer 3b

Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag and separates the
business logic from the JSP page.

The same business logic can be used many times by the use of custom tag.

The key advantages of Custom tags are as follows:

1. Eliminates the need of scriptlet tag The custom tags eliminates the need of scriptlet tag which
is considered bad programming approach in JSP.
2. Separation of business logic from JSP The custom tags separate the the business logic from the
JSP page so that it may be easy to maintain.
3. Re-usability The custom tags makes the possibility to reuse the same business logic again and
again.

There are two ways to use the custom tag. They are given below:
1. <prefix:tagname attr1=value1....attrn=valuen />

1. <prefix:tagname attr1=value1....attrn=valuen >


2. body code
3. </prefix:tagname>

The javax.servlet.jsp.tagext package contains classes and interfaces for JSP custom tag API. The JspTag
is the root interface in the Custom Tag hierarchy.

End of 3b

Answer 4

INSERT INTO COURSE_REGISTRATION (student_id, student_name, course_name, email_address)


VALUES (01, 'Ramesh Tiwari', science, 'ramesh112@gmail.com);

INSERT INTO COURSE_REGISTRATION (student_id, student_name, course_name, email_address)


VALUES (02, Kamlesh Tiwari', arts, 'kamlesh1212@gmail.com);

INSERT INTO COURSE_REGISTRATION (student_id, student_name, course_name, email_address)


VALUES (03, 'Rahul Tyagi', science, 'rahul_tiwari@hotmail.com);

INSERT INTO COURSE_REGISTRATION (student_id, student_name, course_name, email_address)


VALUES (04, Nisha Pandit', computer_science, 'nisha147@msn.com);

INSERT INTO COURSE_REGISTRATION (student_id, student_name, course_name, email_address)


VALUES (05, 'Altaf Raja', science, 'altaf_raja@yahoo.co.in);

INSERT INTO COURSE_REGISTRATION (student_id, student_name, course_name, email_address)


VALUES (06, Aditya Rathore', arts, 'adida232323@gmail.com);

INSERT INTO COURSE_REGISTRATION (student_id, student_name, course_name, email_address)


VALUES (07, 'Pankaj Roy', computer_science, 'pkj2@hotmail.com);

INSERT INTO COURSE_REGISTRATION (student_id, student_name, course_name, email_address)


VALUES (08, 'Ram Bajaj', science, 'ram8484@yahoo.com);

INSERT INTO COURSE_REGISTRATION (student_id, student_name, course_name, email_address)


VALUES (09, 'Shadab Hasan', arts, 'shada12@gmail.com);

INSERT INTO COURSE_REGISTRATION (student_id, student_name, course_name, email_address)


VALUES (10, Aman Verma', computer_science, 'aman789@yahoo.co.in);

// Query1.java: Query an mSQL database using JDBC.

import java.sql.*;

/**
* A JDBC SELECT (JDBC query) example program.
*/
class Query1 {

public static void main (String[] args) {


try {
String url = "jdbc:msql://200.210.220.1:1114/Demo";
Connection conn = DriverManager.getConnection(url,"","");
Statement stmt = conn.createStatement();
ResultSet rs;

rs = stmt.executeQuery("SELECT student_name FROM COURSE_REGISTRATION WHERE


student_id = "2001");
while ( rs.next() ) {
String Name = rs.getString("student_name");
System.out.println(Name);
}
conn.close();
} catch (Exception e) {
System.err.println("Got an exception! ");
System.err.println(e.getMessage());
}
}
}

End of 4

ANSWER 5

Java EE Security Implementation Mechanisms

Java EE security services are provided by the component container and can be implemented using
declarative or programmatic techniques. Java EE security services provide a robust and easily
configured security mechanism for authenticating users and authorizing access to application
functions and associated data at many different layers. Java EE security services are separate from the
security mechanisms of the operating system.

Application-Layer Security

In Java EE, component containers are responsible for providing application-layer security.
Application-layer security provides security services for a specific application type tailored to the
needs of the application. At the application layer, application firewalls can be employed to enhance
application protection by protecting the communication stream and all associated application
resources from attacks.

Java EE security is easy to implement and configure, and can offer fine-grained access control to
application functions and data. However, as is inherent to security applied at the application layer,
security properties are not transferable to applications running in other environments and only
protect data while it is residing in the application environment. In the context of a traditional
application, this is not necessarily a problem, but when applied to a web services application, where
data often travels across several intermediaries, you would need to use the Java EE security
mechanisms along with transport-layer security and message-layer security for a complete security
solution.

The advantages of using application-layer security include the following:

Security is uniquely suited to the needs of the application.


Security is fine-grained, with application-specific settings.
Transport-Layer Security

Transport-layer security is provided by the transport mechanisms used to transmit information over
the wire between clients and providers, thus transport-layer security relies on secure HTTP transport
(HTTPS) using Secure Sockets Layer (SSL). Transport security is a point-to-point security mechanism
that can be used for authentication, message integrity, and confidentiality. When running over an SSL-
protected session, the server and client can authenticate one another and negotiate an encryption
algorithm and cryptographic keys before the application protocol transmits or receives its first byte of
data. Security is live from the time it leaves the consumer until it arrives at the provider, or vice
versa, even across intermediaries. The problem is that it is not protected once it gets to its destination.
One solution is to encrypt the message before sending.

Transport-layer security is performed in a series of phases, which are listed here:

The client and server agree on an appropriate algorithm.


A key is exchanged using public-key encryption and certificate-based authentication.
A symmetric cipher is used during the information exchange.

Digital certificates are necessary when running secure HTTP transport (HTTPS) using Secure Sockets
Layer (SSL). The HTTPS service of most web servers will not run unless a digital certificate has been
installed. Digital certificates have already been created for the Application Server. If you are using a
different server, use the procedure outlined in Working with Digital Certificates to set up a digital
certificate that can be used by your web or application server to enable SSL.

The advantages of using transport-layer security include the following:

Relatively simple, well understood, standard technology.


Applies to message body and attachments.

Message-Layer Security

In message-layer security, security information is contained within the SOAP message and/or SOAP
message attachment, which allows security information to travel along with the message or
attachment. For example, a portion of the message may be signed by a sender and encrypted for a
particular receiver. When the message is sent from the initial sender, it may pass through
intermediate nodes before reaching its intended receiver. In this scenario, the encrypted portions
continue to be opaque to any intermediate nodes and can only be decrypted by the intended receiver.
For this reason, message-layer security is also sometimes referred to as end-to-end security.

The advantages of message-layer security include the following:

Security stays with the message over all hops and after the message arrives at its destination.
Security can be selectively applied to different portions of a message (and to attachments if
using XWSS).
Message security can be used with intermediaries over multiple hops.
Message security is independent of the application environment or transport protocol.

Example of java security implementation:

public boolean mkdir(String path) throws IOException {


SecurityManager security = System.getSecurityManager();
if (security != null) {
security.checkWrite(path);
}
return mkdir0();
}

Example of security check. This example shows the basic metaphor: the public method mkdir
checks the system SecurityManager (which will throw an exception if the check does not pass)
and then calls the low level private method mkdir0.

END OF 5

Answer 6a
There are various architectures of EJB (J2EE) available which are used for various purposes. J2EE is a
standard architecture specifically oriented to the development and deployment of enterprise Web-
oriented applications that use Java programming language. ISVs and enterprises can use the J2EE
architecture for only not the development and deployment of intranet applications, thus effectively
replacing the two-tier and three-tier models, but also for the development of Internet applications,
effectively replacing the cgi-bin-based approach. The J2EE architecture provides a flexible distribution
and tiering model that allows enterprises to construct their applications in the most suitable manner.
the basic parts of an EJB system: the EJB component, the EJB container, and the EJB object.
The Enterprise JavaBeans Component
An Enterprise JavaBean is a component, just like a traditional JavaBean. Enterprise JavaBeans execute
within an EJB container, which in turn executes within an EJB server. Any server that can host an EJB
container and provide it with the necessary services can be an EJB server. (Hence, many existing
servers are being extended to be EJB servers.)
An EJB component is the type of EJB class most likely to be considered an Enterprise JavaBean. Its a
Java class, written by an EJB developer, that implements business logic. All the other classes in the EJB
system either support client access to or provide services (like persistence, and so on) to EJB
component classes.
The Enterprise JavaBeans Container
The EJB container is where the EJB component lives. The EJB container provides services such as
transaction and resource management, versioning, scalability, mobility, persistence, and security to
the EJB components it contains. Since the EJB container handles all these functions, the EJB
component developer can concentrate on business rules, and leave database manipulation and other
such fine details to the container. For example, if a single EJB component decides that the current
transaction should be aborted, it simply tells its container (container is responsible for performing all
rollbacks, or doing whatever is necessary to cancel a transaction in progress). Multiple EJB component
instances typically exist inside a single EJB container.
The EJB Object and the Remote Interface
Client programs execute methods on remote EJBs by way of an EJB object. The EJB object implements
the remote interface of the EJB component on the server. The remote interface represents the
business methods of the EJB component. The remote interface does the actual, useful work of an EJB
object, such as creating an order form or deferring a patient to a specialist. EJB objects and EJB
components are separate classes, though from the outside (i.e., by looking at their interfaces), they
look identical. This is because, they both implement the same interface (the EJB components remote
interface), but they do very different things. An EJB component runs on the server in an EJB container
and implements the business logic. The EJB object runs on the client and remotely executes the EJB
components methods.
End of Answer 6a

Answer 6b

Entity Beans actually represents the data in a database. It is not that Entity Beans replaces JDBC API.
There are two types of Entity Beans Container Managed and Bean Mananged.

In Container Managed Entity Bean - Whenever the instance of the bean is created the container
automatically retrieves the data from the DB/Persistance storage and assigns to the object variables
in bean for user to manipulate or use them. For this the developer needs to map the fields in the
database to the variables in deployment descriptor files (which varies for each vendor).

In the Bean Managed Entity Bean - The developer has to specifically make connection, retrive values,
assign them to the objects in the ejbLoad() which will be called by the container when it instatiates a
bean object. Similarly in the ejbStore() the container saves the object values back the the persistance
storage. ejbLoad and ejbStore are callback methods and can be only invoked by the container.

Apart from this, when you use Entity beans you dont need to worry about database transaction
handling, database connection pooling etc. which are taken care by the ejb container. But in case of
JDBC you have to explicitly do the above features.
End of answer 6b

ANSWER 7 : Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of a user. It is also known as session management in
servlet.

Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time
user requests to the server, server treats the request as the new request. So we need to maintain the
state of an user to recognize to particular user.

Every user of a site is associated with a javax.servlet.http.HttpSession object that servlets can use to store or
retrieve information about that user. You can save any set of arbitrary Java objects in a session object.

HTTP is stateless that means each request is considered as the new request. It is shown in the
figure given below:
There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

Cookies:

A cookie is a small piece of information that is persisted between the multiple client requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and domain
qualifiers, a maximum age, and a version number.

How Cookie works

By default, each request is considered as a new request. In cookies technique, we add cookie with
response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent
by the user, cookie is added with request by default. Thus, we recognize the user as the old user.

There are 2 types of cookies in servlets.

1. Non-persistent cookie - It is valid for single session only. It is removed each time when user
closes the browser.

Persistent cookie - It is valid for multiple session . It is not removed each time when user closes the
browser. It is removed only if user logout or signout.

javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful
methods for cookies.

Hidden Form Field

In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state of an user.

In such case, we store the information in the hidden field and get it from another servlet. This
approach is better if we have to submit form in all the pages and we don't want to depend on the
browser.
Let's see the code to store value in hidden field.

1. <input type="hidden" name="uname" value="Vimal Jaiswal">

Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.

Real application of hidden form field

It is widely used in comment form of a website. In such case, we store page id or page name in the
hidden field so that each page can be uniquely identified.

Advantage of Hidden Form Field

1. It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field:

1. It is maintained at server side.


2. Extra form submission is required on each pages.
3. Only textual information can be used.

3)URL Rewriting

In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource.
We can send parameter name/value pairs using the following format:

url?name1=value1&name2=value2&??

A name and a value is separated using an equal = sign, a parameter name/value pair is separated from
another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter
name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to
obtain a parameter value.

4) HttpSession interface

In such case, container creates a session id for each user.The container uses this id to identify the
particular user.An object of HttpSession can be used to perform two tasks:

1. bind objects
2. view and manipulate information about a session, such as the session identifier, creation time,
and last accessed time.
The HttpServletRequest interface provides two methods to get the object of HttpSession:

1. public HttpSession getSession():Returns the current session associated with this request, or
if the request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current HttpSession associated
with this request or, if there is no current session and create is true, returns a new session.

Commonly used methods of HttpSession interface:

1. public String getId():Returns a string containing the unique identifier value.


2. public long getCreationTime():Returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a request associated
with this session, as the number of milliseconds since midnight January 1, 1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it. [end of
answer 7]

ANSWER 8:

A web client can authenticate a user to a web server using one of the following mechanisms:

HTTP Basic Authentication


HTTP Digest Authentication
Form Based Authentication
HTTPS Client Authentication

HTTP Basic Authentication:

HTTP basic authentication is defined by the HTTP specification that lightly sends the user's user name
and password over the Internet as text that is uu-encoded (Unix-to-Unix encoded) but not encrypted.
If someone can intercept the transmission, the user name and password information can easily be
decoded. It should only be used with HTTPS, as the password can be easily captured and reused over
HTTP. Basic authentication is supported by Exchange 2000 Server and Exchange Server 2003.

With basic authentication, the following things occur:

1. A client requests access to a protected resource.


2. The web server returns a dialog box that requests the user name and password.
3. The client submits the user name and password to the server.
4. The server validates the credentials and, if successful, returns the requested resource.

HTTP Digest Authentication:

Similar to HTTP Basic Authentication, HTTP Digest Authentication authenticates a user based on a
username and a password. As Digest Authentication is not currently in widespread use, servlet
containers are encouraged but NOT REQUIRED to support it. The advantage of this method is that the
clear text password is protected in transmission; it cannot be determined from the digest that is
submitted by the client to the server. Digested password authentication supports the concept of
digesting user passwords. This causes the stored version of the passwords to be encoded in a form
that is not easily reversible, but that the web server can still utilize for authentication.

The difference between basic and digest authentication is that on the network connection between the
browser and the server, the passwords are encrypted, even on a non-SSL connection. Digested
password is authentication based on the concept of a hash or digest. In this stored version, the
passwords are encoded in a form that is not easily reversible and this is used for authentication.

Form Based Authentication:

Particularly Form-based authentication is not secure. The content of the user dialog box is sent as
plain text, and the target server is not authenticated. This form of authentication can expose the user
names and passwords unless all connections are over SSL. If someone can intercept the transmission,
the user name and password information can easily be decoded. However, we can use an
Exchange2003 Server front-end with an Exchange2000 Server back-end and benefit from forms-
based authentication. Forms-based authentication is supported only by Exchange Server 2003.

With form-based authentication, the following things occur:


1. A client requests access to a protected resource.
2. If the client is unauthenticated, the server redirects the client to a login page.
3. The client submits the login form to the server.
4. If the login succeeds, the server redirects the client to the resource. If the login fails, the client
is redirected to an error page.

HTTPS Client Authentication:

Client-certificate authentication is a more secure method of authentication than BASIC or FORM


authentication. It uses HTTP over SSL, in which the server and, optionally, the client authenticate one
another using public key certificate. Secure Socket Layer (SSL) provides data encryption, server
authentication, message integrity, and optional client authentication for a TCP/IP connection.

[END OF ANSWER 8]

Você também pode gostar