0% found this document useful (0 votes)
64 views28 pages

Exp 6-13

Uploaded by

SAKSHI CHAUHAN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views28 pages

Exp 6-13

Uploaded by

SAKSHI CHAUHAN
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

EXPERIMENT NO: 6

OBJECTIVE: Use JavaScript to develop the following program:


a) to calculate multiplication and division of two numbers (input from user).

Sample form

b. to accept a string as a parameter and counts the number of vowels within the string.
c. using function to validate whether a given value in the text box is number or not.

DESCRIPTION:

JavaScript is a dynamic computer programming language. It is lightweight and most commonly


used as a part of web pages, whose implementations allow client-side script to interact with the
user and make dynamic pages. It is an interpreted programming language with object-oriented
capabilities.

A) to calculate multiplication and division of two numbers

SAMPLE CODE:

<body>
<form>
1st Number : <input type="text" id="first" /><br>
2nd Number: <input type="text" id="second" /><br>
<input type="button" onClick="multiplyBy()" Value="Multiply" />
<input type="button" onClick="divideBy()" Value="Divide" />
</form>
<p>The Result is : <br>
<span id = "result"></span>
</p>
<script>
function multiplyBy()
{
num1 = document.getElementById("first").value;
num2 = document.getElementById("second").value;
document.getElementById("result").innerHTML = num1 * num2;
}
function divideBy()
{
num1 = document.getElementById("first").value;
num2 = document.getElementById("second").value;
document.getElementById("result").innerHTML = num1 / num2;
}
</script>
</body>

OUTPUT:

B) to accept a string as a parameter and counts the number of vowels within the string.

SAMPLE CODE:

<body>
<script> function a()
{
var v1=document.getElementById ("txt").value;
var c=0;
for(var i=0;i<v1.length;i++)
{
if(v1[i]==='a'||v1[i]==='e'||v1[i]==='i'||v1[i]==='o'||v1[i] ==='u' ||v1[i]==='A'||
v1[i]==='E'||v1[i]==='I'||v1[i]==='O'||v1[i]==='U')
{
c=c+1;
}
}
document.getElementById('Result').innerHTML = c;
}
</script>

<input type="text" placeholder="Enter the text" id="txt">


<button type="button" onclick=" a();">Get Vowel </button>
<p id="Result"></p>
</body>
</html>
OUTPUT:
C) using function to validate whether a given value in the text box is number or not.

SAMPLE CODE:

<body>
<input type="text" placeholder="Enter the Text" id="Txt">
<button type="button" onclick="check();">validate</button>
<p id="result"></p>
<script>
function check()
{
var v1=document.getElementById("Txt").value;
if(isNaN(v1)) // Check not a number
{
document.getElementById('result').innerHTML = "False";
}
else
{
document.getElementById('result').innerHTML = "True";
}
}
</script>
</body>

OUTPUT:
EXPERIMENT NO: 7

OBJECTIVE: Write programs using Java script for Web Page to display browsers information.

DESCRIPTION:

The navigator object contains information about the browser.

NAVIGATOR OBJECT PROPERTIES:

Property Description
appCodeName Returns the code name of the browser
appName Returns the name of the browser
appVersion Returns the version information of the browser
cookieEnabled Determines whether cookies are enabled in the browser
Returns a Geolocation object that can be used to locate the user's
geolocation
position
language Returns the language of the browser
onLine Determines whether the browser is online
platform Returns for which platform the browser is compiled
product Returns the engine name of the browser
userAgent Returns the user-agent header sent by the browser to the server

SAMPLE CODE:

<html>
<head>
<title>Browser Information</title>
</head>
<body>
<h1>Browser Information</h1>
<hr>
<p>
The <b>navigator</b> object contains the following information about the browser you are
using.
</p>
<ul>
<script LANGUAGE="JavaScript" type="text/javascript">
document.write("<li><b>Code Name:</b> " + navigator.appCodeName);
document.write("<li><b>App Name:</b> " + navigator.appName);
document.write("<li><b>App Version:</b> " + navigator.appVersion);
document.write("<li><b>User Agent:</b> " + navigator.userAgent);
document.write("<li><b>Language:</b> " + navigator.language);
document.write("<li><b>Platform:</b> " + navigator.platform);
</script>
</ul>
<hr>
</body>
</html>

OUTPUT:
EXPERIMENT NO: 8

OBJECTIVE: Write an HTML program to design an entry form of student details and validate
it using JavaScript.

DESCRIPTION:

JavaScript is a dynamic computer programming language. It is lightweight and most commonly


used as a part of web pages, whose implementations allow client-side script to interact with the
user and make dynamic pages. It is an interpreted programming language with object-oriented
capabilities.

HTML FORMS: HTML Forms are required to collect different kinds of user inputs, such as
contact details like name, email address, phone numbers, or details like credit card information,
etc. Users generally complete a form by modifying its controls e.g. entering text, selecting items,
etc. and submitting this form to a web server for processing.

SYNTAX:

<form>
form elements
</form>

Form elements are different types of input elements, like text fields, checkboxes, radio buttons,
submit buttons, etc.

INPUT ELEMENT: An input element can be of type text field, checkbox, password field, radio
button, submit button, reset button, etc. and several new input types. The <input> element can be
displayed in several ways, depending on the type attribute. Eg.

Type Description

<input type="text"> Defines a one-line text input field

<input type="radio"> Defines a radio button (for selecting one of many choices)

<input type="submit"> Defines a submit button (for submitting the form)

<input
Defines a password field
type="password">

<input type="reset"> Defines a reset button that reset form values to default values

<input Defines checkbox


type="checkbox">

<input type="button"> Defines a button


THE ACTION ATTRIBUTE: The action attribute defines the action to be performed when the
form is submitted.

<form action="path">

THE METHOD ATTRIBUTE: The method attribute specifies the HTTP method
(GET or POST) to be used when submitting the form data:

<form action="path" method="get/post">

THE <SELECT> ELEMENT:

 The <select> element defines a drop-down list.


 The <option> elements defines an option that can be selected.
 By default, first item in drop-down list is selected. To define a pre-selected option, use
selected attribute.

THE <TEXTAREA> ELEMENT: The <textarea> element defines a multi-line input field (a
text area). It has three main attributes name, rows and cols.

THE <BUTTON> ELEMENT: The <button> element defines a clickable button.

SAMPLE CODE:

<html>
<head>
<script>
function validateform()
{
//let name = document.forms["myform"]["name"].value;
var name=document.myform.namee.value;
var pass=document.myform.pwd.value;
var mail=document.myform.emailing.value;
var regEmail=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/g;
var regName = /^[a-zA-Z]+ [a-zA-Z]+$/;
/*
if (name==null || name=="")
{
alert("Name can't be blank");
return false;
}
*/
if (name==null || name=="" || !regName.test(name) || name.length<6 )
{
alert("Name must be at least 6 characters long");
return false;
}
else if(pass.length<6)
{
alert("Password must be at least 6 characters long.");
return false;
}
else if(mail == "" || !regEmail.test(mail))
{
alert("Enter correct Email.");
return false;
}
}
</script>
</head>
<body>
<form name="myform" method="post" action="aaa.html" onsubmit="return validateform()" >
Name: <input type="text" name="namee"><br/>
Password: <input type="password" name="pwd"><br/>
<!--Email: <input type="email" name="emailing"><br/> -->
Email: <input type="text" name="emailing"><br/>
<input type="submit" value="register">
</form>
</body>
</html>

OUTPUT-
EXPERIMENT NO: 9

OBJECTIVE: Demonstrate client-server communication using socket programming.

DESCRIPTION: To connect to another machine we need a socket connection. A socket


connection means the two machines have information about each other’s network location (IP
Address) and TCP port. The java.net.Socket class represents a Socket.

To open a socket:

Socket socket = new Socket (“127.0.0.1”, 4999)

 First argument – IP address of Server. (127.0.0.1 is the IP address of


localhost, where code will run on single stand-alone machine).

 Second argument – TCP Port. (Just a number representing which application to run on
a server. For example, HTTP runs on port 80. Port number can be from 0 to 65535)

SAMPLE CODE:

File name as Client.java-

import java.net.*;

import java.io.*;

public class client

public static void main (String[] args) throws IOException

Socket s=new Socket("localhost",4999);

File Name as Server.java


import java.net.*;

import java.io.*;

public class server

public static void main(String[] args) throws IOException

ServerSocket ss = new ServerSocket (4999);

Socket s=ss.accept();

System.out.println("client connection");

OUTPUT:
EXPERIMENT NO: 10

OBJECTIVE: Install TOMCAT web server and APACHE. Access the above developed static
web pages for books web site, using these servers by putting the web pages developed.

DESCRIPTION:

Introduction to servlets:

Servlets are java programs that run on web or application servers, acting as middle layer between
request coming from the web browsers or other HTTP clients and database servers. Servlets
process user request, produce the results and sends the results as a response to the user.

Life cycle of Servlet

Loading: The servlet container loads the servlet during startup or when the first request is made.
The loading of the servlet depends on the attribute <load-on-startup> of web.xml file. If the
attribute <load-on-startup> has a positive value then the servlet is load with loading of the
container otherwise it load when the first request comes for service. After loading of the servlet,
the container creates the instances of the servlet.

Initialization: After creating the instances, the servlet container calls the init() method and
passes the servlet initialization parameters to the init() method. The init() must be called by the
servlet container before the servlet can service any request. The initialization parameters persist
untill the servlet is destroyed. The init() method is called only once throughout the life cycle of
the servlet.
The servlet will be available for service if it is loaded successfully otherwise the servlet container
unloads the servlet.

Servicing the Request: After successfully completing the initialization process, the servlet will
be available for service. Servlet creates seperate threads for each request. The sevlet container
calls the service() method for servicing any request. The service() method determines the kind of
request and calls the appropriate method (doGet() or doPost()) for handling the request and sends
response to the client using the methods of the response object.

Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet
container calls the destroy() method . Like the init() method this method is also called only once
throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet
container not to sent the any request for service and the servlet releases all the resources
associated with it. Java Virtual Machine claims for the memory associated with the resources for
garbage collection.

Servlet API provides the following two packages

Javax.servlet

The javax.servlet package contains a number of classes and interfaces that describe and define
the contracts between a servlet class and the runtime environment provided for an instance of
such a class by a conforming servlet container.

Javax.servlet.http

The javax.servlet.http package contains a number of classes and interfaces that describe and
define the contracts between a servlet class running under the HTTP protocol and the runtime
environment provided for an instance of such a class by a conforming servlet container.

PROCESS TO CREATE ENVIRONMENT FOR EXCECTION OF A SERVLET


SAMPLE CODE:ME

Set the JAVA_HOME Variable

You must set the JAVA_HOME environment variable to tell Tomcat where to find Java. Failing
to properly set this variable prevents Tomcat from handling JSP pages. This variable should list
the base JDK installation directory, not the bin subdirectory.
We could do this by click on the Start menu, select Control Panel, choose System, click on the
advanced tab, press the Environment Variables button at the bottom, and enter the JAVA_HOME
variable and value directly as:

Name: JAVA_HOME
Value: C:\jdk

Set the CLASSPATH

Since servlets and JSP are not part of the Java 2 platform, standard edition, youhave to identify
the servlet classes to the compiler. The server already knows about theservlet classes, but the
compiler (i.e., javac ) you use for development probably doesn't.So, if you don't set your
CLASSPATH, attempts to compile servlets, tag libraries, or other classes that use the servlet and
JSP APIs will fail with error messages about unknownclasses.

Name: JAVA_HOME
Value: install_dir/common/lib/servlet-api.jar

Turn on Servlet Reloading

The next step is to tell Tomcat to check the modification dates of the class files of requested
servlets and reload ones that have changed since they were loaded into the server’s memory. This
slightly degrades performance in deployment situations, so is turned off by default. However, if
you fail to turn it on for your development server, you’ll have to restart the server every time you
recompile a servlet that has already been loaded into the server's memory.

To turn on servlet reloading, edit install_dir/conf/server.xml and add a Default Context sub
element to the main Host element and supply true for the reloadable attribute. For example, in
Tomcat 5.0.27, search for this entry:
<Host name="localhost" debug="0" appBase="webapps" ...> and then insert the following
immediately below it:

<Default Context reloadable="true"/>

Be sure to make a backup copy of server.xml before making the above change.

Enable the Invoker Servlet

The invoker servlet lets you run servlets without first making changes to yourWeb application's
deployment descriptor. Instead, you just drop your servlet into WEB-INF/classes and use the
URL http://host/servlet/ServletName . The invoker servlet isextremely convenient when you are
learning and even when you are doing your initialdevelopment.

To enable the invoker servlet, uncomment the following servlet and servlet-mapping elements in
install_dir/conf/web.xml. Finally, remember to make a backup copyof the original version of this
file before you make the changes.
<servlet>

<servlet-name>invoker</servlet-name>

<servlet-class> org.apache.catalina.servlets.InvokerServlet
</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>invoker</servlet-name>

<url-pattern>/servlet/*</url-pattern>

</servlet-mapping>
EXPERIMENT NO: 11

OBJECTIVE: Write a JSP which insert the details of the 3 or 4 users who register with the the
web site by using registration form. Authenticate the user when he submits the login form using
the username and password.

DESCRIPTION:

JSP Scripting Elements

JSP scripting elements let you insert Java code into the servlet that will be generated from the
current JSP page. There are three forms:

1. Expressions of the form <%= expression %> that are evaluated and inserted into the
output.
2. Scriptlets of the form <% code %> that are inserted into the servlet's service method.
3. Declarations of the form <%! code %> that are inserted into the body of the servlet
class, outside of any existing methods.

Each of these is described in more detail below.

JSP Expressions
A JSP expression is used to insert Java values directly into the output. It has the following form:

<%= Java Expression %>

The Java expression is evaluated, converted to a string, and inserted in the page. This evaluation
is performed at run-time (when the page is requested), and thus has full access to information
about the request. For example, the following shows the date/time that the page was requested:
Current time: <%= new java.util.Date() %>

To simplify these expressions, there are a number of predefined variables that you can use.

These implicit objects are discussed in more detail later, but for the purpose of expressions, the
most important ones are:

• request, the HttpServletRequest;


• response, the HttpServletResponse;
• session, the HttpSession associated with the request (if any); and
• out, the PrintWriter (a buffered version of type JspWriter) used to send output to the client.

JSP Scriptlets

If you want to do something more complex than insert a simple expression, JSP scriptlets let you
insert arbitrary code into the servlet method that will be built to generate the page. Scriptlets
have the following form:

<% Java Code %>

Scriptlets have access to the same automatically defined variables as expressions. So, for
example, if you want output to appear in the resultant page, you would use the out variable.

<%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>

Note that code inside a scriptlet gets inserted exactly as written, and any static HTML (template
text) before or after a scriptlet gets converted to print statements. This means that scriptlets need
not contain complete Java statements, and blocks left open can affect the static HTML outside of
the scriptlets.

JSP Declarations

A JSP declaration lets you define methods or fields that get inserted into the main body of the
servlet class (outside of the service method processing the request). It has the following form:

<%! Java Code %>

Since declarations do not generate any output, they are normally used in conjunction with JSP
expressions or scriptlets. For example, here is a JSP fragment that prints out the number of times
the current page has been requested since the server booted (or the servlet class was changed and
reloaded):

<%! private int accessCount = 0; %>


SAMPLE CODE:

Login.html:

<html>
<body>
<center><h1>XYZ Company Ltd.</h1></center>
<table border="1" width="100%" height="100%">
<tr>
<td valign="top" align="center"><br/>
<form action="auth.jsp"><table>
<tr>
<td colspan="2" align="center"><b>Login Page</b></td>
</tr>
<tr>
<td colspan="2" align="center"><b>&nbsp;</td>
</tr>
<tr>
<td>User Name</td>
<td><input type="text" name="user"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="pwd"/></td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="LogIN"/></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
</body>
</html>

Auth.jsp:

<%@page import="java.sql.*;"%>
<html>
<head>
<title>
This is simple data base example in JSP</title>
</title>
</head>
<body bgcolor="yellow">
<%!String uname,pwd;%>
<%
uname=request.getParameter("user");
pwd=request.getParameter("pwd");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@195.100.101.158:1521:CCLAB
","scott","tiger ");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select name,password from personal where
name='"+uname+"' and password='"+pwd+"'");
if(rs.next())
{
out.println("Authorized person");
}
else
{
out.println("UnAuthorized person");
}
con.close();
}
catch(Exception e){out.println(""+e);}
%>
</body>
</html>

OUTPUT
EXPERIMENT NO: 12

OBJECTIVE: Install a database (Mysql or Oracle). Create a table which should contain at least
the following fields: name, password, email-id, phone number Write a java program/servlet/JSP
to connect to that database and extract data from the tables and display them. Insert the details of
the users who register with the web site, whenever a new user clicks the submit button in the
registration page.

DESCRIPTION:

JDBC Driver Types

There are four types of JDBC drivers in use:

Type 1: JDBC-ODBC Bridge

A Type 1 JDBC-ODBC Bridge provides application developers with a way to access


JDBC drivers via the JDBC API. Type 1 JDBC drivers translate the JDBC calls into ODBC calls
and then send the calls to the ODBC driver. Type 1 JDBC drivers are generally used when the
database client libraries need to be loaded on every client machine.

Type 2: Native API/Partly Java Driver

A Type 2 Native API/Partly Java Driver is a partial Java driver because it converts JDBC
calls into database specific calls. Type 2 Native API/Partly Java Driver communicates directly
with the database server.

Type 3: Pure Java Driver


A Type 3 Pure Java Driver works in a three tiered architecture. The JDBC calls are
passed via the network to the middle tier server. This server translates the calls to the database
specific native interface to further request the server. JDBC drivers available from Simba are
Type 3 drivers.

Type 4: Native Protocol Java Driver

The type 4 driver is written completely in Java and is hence platform independent. It is
installed inside the Java Virtual Machine of the client. It provides better performance over the
type 1 and 2 drivers as it does not have the overhead of conversion of calls into ODBC or
database API calls. Unlike the type 3 drivers, it does not need associated software to work.A
Type 4 Native Protocol Java Driver converts JDBC calls into the database specific calls so that
the client applications can communicate directly with the server.

SAMPLE CODE:

Registration.html:

<html>
<head>
<title>Registration page</title>
</head>
<body bgcolor="#00FFFf">
<form METHOD="POST" ACTION="register">
<CENTER>
<table>
<center>
<tr> <td> Username </td>
<td><input type="text" name="usr"> </td> </tr>
<tr><td> Password </td>
<td><input type="password" name="pwd"> </td> </tr>
<tr><td>Age</td>
<td><input type="text" name="age"> </td> </tr>
<tr> <td>Address</td>
<td> <input type="text" name="add"> </td> </tr>
<tr> <td>email</td>
<td> <input type="text" name="mail"> </td> </tr>
<tr> <td>Phone</td>
<td> <input type="text" name="phone"> </td> </tr>
<tr> <td colspan=2 align=center> <input type="submit" value="submit"> </td> </tr>
</center>
</table>
</form>
</body>
</html>
Login.html

<html>
<head>
<title>Registration page</title>
</head>
<body bgcolor=pink> <center> <table>
<form METHOD="POST" ACTION="authent">
<tr> <td> Username </td>
<td><input type="text" name="usr"></td> </tr>
<tr> <td> Password </td>
<td> <input type="password" name="pwd"> </td> </tr>
<tr> <td align=center colspan="2"><input type="submit" value="submit"></td> </tr>
</table> </center>
</form>
</body>
</html>

Ini.java:

import javax.servlet.*;
import java.sql.*;
import java.io.*;
public class Ini extends GenericServlet
{
private String user1,pwd1,email1;
public void service(ServletRequest req,ServletResponse res) throws
ServletException,IOException
{
user1=req.getParameter("user");
pwd1=req.getParameter("pwd");
email1=req.getParameter("email");
res.setContentType("text/html");
PrintWriter out=res.getWriter();

try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@195.100.101.158:1521:cc
lab","scott","tiger");
PreparedStatement st=con.prepareStatement("insert into personal values(?,?,?,?,?,?)");
st.setString(1,user1);
st.setString(2,pwd1);
st.setString(3,"25");
st.setString(4,"hyd");
st.setString(5,email1);
st.setString(6,"21234");
st.executeUpdate();
con.close(); }

catch(SQLException s)
{ out.println("not found "+s);
}

catch(ClassNotFoundException c)
{
out.println("not found "+c);
}
}
}
web.xml:

<web-app>
<servlet>
<servlet-name>init1</servlet-name>
<servlet-class>Ini</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>init1</servlet-name>
<url-pattern>/regis</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT:
EXPERIMENT NO: 13

OBJECTIVE: Assume four users user1, user2, user3 and user4 having the passwords pwd1,
pwd2, pwd3 and pwd4 respectively. Write a servlet for doing the following.

1. Create a Cookie and add these four user id’s and passwords to this Cookie.
2. Read the user id and passwords entered in the Login form (week1) and
authenticate with the values (user id and passwords) available in the cookies.

DESCRIPTION:

Servlet Life cycle:


1. Servlet class loading
2. Servlet Instantiation
3. call the init method
4. call the service method
5. call destroy method

Class loading and instantiation

If you consider a servlet to be just like any other Java program, except that it runs within a
servlet container, there has to be a process of loading the class and making it ready for requests.
Servlets do not have the exact equivalent of a main method that causes them to start execution.
When a web container starts it searches for the deployment descriptor (WEB.XML) for each of
its web applications. When it finds a servlet in the descriptor it will create an instance of the
servlet class. At this point the class is considered to be loaded (but not initialized).

The init method

The HttpServlet class inherits the init method from GenericServlet. The init method performs a
role slightly similar to a constructor in an “ordinary” Java program in that it allows initialization
of an instance at start up. It is called automatically by the servlet container and as it causes the
application context (WEB.XML) to be parsed and any initialization will be performed. It comes
in two versions, one with a zero parameter constructor and one that takes a ServletConfig
parameter.

The servlet engine creates a request object and a response object. The servlet engine invokes the
servlet service() method, passing the request and response objects. Once the init method returns
the servlet is said to be placed into service. The process of using init to initialize servlets means
that it is possible to change configuration details by modifying the deployment descriptor
without having them hard coded in with your Java source and needing a re-compilation.
void init(ServletConfig sc)

Calling the service method

The service() method gets information about the request from the request object, processes the
request, and uses methods of the response object to create the client response. The service
method can invoke other methods to process the request, such as doGet(), doPost(), or methods
you write. The service method is called for each request processed and is not normally
overridden by the programmer.
The code that makes a servlet “go” is the.

servlet void service(ServletRequest req,ServletResponse res)

The destroy Method

Two typical reasons for the destroy method being called are if the container is shutting down or
if the container is low on resources. This can happen when the container keeps a pool of
instances of servlets to ensure adequate performance. If no requests have come in for a particular
servlet for a while it may destroy it to ensure resources are available for the servlets that are
being requested. The destroy method is called only once, before a servlet is unloaded and thus
you cannot be certain when and if it is called.
void destroy()

ServletConfig Class
ServletConfig object is used by the Servlet Container to pass information to the Servlet during
it's initialization. Servlet can obtain information regarding initialization parameters and their
values using different methods of ServletConfig class initialization parameters are name/value
pairs used to provide basic information to the Servlet during it's initialization like JDBC driver
name, path to database, username, password etc.

Methods of ServletConfig class

Following are the four methods of this class :


1. getInitParameter(String paramName) Returns value of the given parameter. If value of
parameter could not be found in web.xml file then a null value is returned.
2. GetInitParameterNames() Returns an Enumeration object containing all the names of
initialization parameters provided for this Servlet.
3. GetServletContext() Returns reference to the ServletContext object for this Servlet. It is
similar to getServletContext() method provided by HttpServlet class.
4. GetServletName() Returns name of the Servlet as provided in the web.xml file or if none is
provided then returns complete class path to the Servlet.
SAMPLE CODE:

1. Create a Cookie and add these four user id’s and passwords to this Cookie.

cologin.html:

<html>
<head>
<title> login Page </title>
<p style= "background:yellow; top:100px; left:250px; position:absolute; ">
</head>

<body>
<form ACTION="clogin">
<label> Login </label>
<input type="text" name="usr" size="20"> <br> <br>
<label> Password </label>
<input type="password" name="pwd" size="20"> <br> <br>
<input type="submit" value="submit">
</form>
</body>
</html>
cologin1.html
<html>
<head>
<title> login Page </title>
<p style= "background:yellow; top:100px; left:250px; position:absolute; ">
</head>
<body>
<form ACTION="clogin1">
<label> Login </label>
<input type="text" name="usr" size="20"> <br> <br>
<label> Password </label>
<input type="password" name="pwd" size="20"> <br> <br>
<input type="submit" value="submit">
</form>
</body>
</html>

Addcook.java:

import javax.servlet.* ;
import javax.servlet.http.*;
import java.io.*;
public class Addcook extends HttpServlet
{
String user,pas;
public void service(HttpServletRequest req,HttpServletResponse res) throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
Cookie c1=new Cookie("usr1","suni");
Cookie p1=new Cookie("pwd1","ani");
Cookie c2=new Cookie("usr2","abc");
Cookie p2=new Cookie("pwd2","123");
Cookie c3=new Cookie("usr3","def");
Cookie p3=new Cookie("pwd3","456");
Cookie c4=new Cookie("usr4","mno");
Cookie p4=new Cookie("pwd4","789");

res.addCookie(c1);
res.addCookie(p1);
res.addCookie(c2);
res.addCookie(p2);
res.addCookie(c3);
res.addCookie(p3);
res.addCookie(c4);
res.addCookie(p4);

out.println("COOKIE ADDED");
}
}

Clogin.java:

import javax.servlet.* ;
import javax.servlet.http.*;
import java.io.*;
public class Clogin extends HttpServlet
{
String user,pas;

public void service(HttpServletRequest req,HttpServletResponse res) throws


ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
user=req.getParameter("usr");
pas=req.getParameter("pwd");
Cookie[] c=req.getCookies();
for(int i=0;i<c.length;i++)
{
if((c[i].getName().equals("usr1")&&c[i+1].getName().equals("pwd1"))||
c[i].getName().equals("usr2") &&c[i+1].getName().equals("pwd2"))||
(c[i].getName().equals("usr3")&& c[i+1].getName().equals("pwd3"))||
(c[i].getName().equals("usr4")&& c[i+1].getName().equals("pwd4") ))
{
if((user.equals(c[i].getValue()) && pas.equals(c[i+1].getValue())) )
{

//RequestDispatcher rd=req.getRequestDispatcher("/cart.html");
rd.forward(req,res);
}
else
{
out.println("YOU ARE NOT AUTHORISED USER ");
//res.sendRedirect("/cookdemo/cologin.html");
}
}
}
}
}

Web.xml:

<web-app>
<servlet>
<servlet-name>him</servlet-name>
<servlet-class>Clogin</servlet-class>
</servlet>
<servlet>
<servlet-name>him1</servlet-name>
<servlet-class>Addcook</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>him</servlet-name>
<url-pattern>/clogin</url-pattern>
</servlet-mapping>

<servlet-mapping>
<servlet-name>him1</servlet-name>
<url-pattern>/clogin1</url-pattern>
</servlet-mapping>
</web-app>

OUTPUT
2 Read the user id and passwords entered in the Login form (week1) and authenticate with the
values (user id and passwords) available in the cookies.

STEPS:

1. Crete a web page to get input from user

2. Write code for java servelet

If the user is a valid user (i.e., user-name and password match) you should welcome the
user by name (user-name) else you should display “You are not an authenticated user “.
Use init-parameters to do this.

3. Do required changes in web.xml

Store the user-names and passwords in the webinf.xml and access them in the servlet by
using the getInitParameters() method.

You might also like