Servlet Session and Cookie Examples
Servlet Session and Cookie Examples
Packages:
[Link]
[Link]
[Link]
[Link]
Note: Using sessions in Servlets is quite straightforward, and involves looking up the session
object associated with the current request, creating a new session object when necessary, looking
up information associated with a session, storing information in a session, and discarding
completed or abandoned sessions.
This is done by calling the getSession method of HttpServletRequest. If this returns null, you can
create a new session, but this is so commonly done that there is an option to automatically create
a new session if there isn't one already. Just pass true to getSession.
HttpSession session = [Link](true);
➢ getId :This method returns the unique identifier generated for each session. It is
sometimes used as the key name when there is only a single value associated with a
session, or when logging information about previous sessions.
➢ isNew: This returns true if the client (browser) has never seen the session, usually
because it was just created rather than being referenced by an incoming client request. It
returns false for preexisting sessions.
➢ getCreationTime: This returns the time, in milliseconds since the epoch, at which the
session was made. To get a value useful for printing out, pass the value to the Date
constructor or the setTimeInMillis method of Gregorian Calendar.
➢ getLastAccessedTime: This returns the time, in milliseconds since the epoch, at which
the session was last sent from the client.
➢ getMaxInactiveInterval: This returns the amount of time, in seconds, that a session
should go without access before being automatically invalidated. A negative value
indicates that the session should never timeout.
Page| 1
[Link]:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
[Link]("text/html");
[Link](dataName, dataValue);
Enumeration e = [Link]();
while ([Link]()) {
Page| 2
String value = [Link](name).toString();
[Link]
<html>
<head>
<title>Sessions Example</title>
</head>
<body>
<h1> An example for session attributes </h1>
<form action="Session" method=GET>
<br>
Value of Session Attribute:
<input type=text size=20 name=datavalue>
<br>
<input type=submit>
</form>
</body>
</html>
Page| 3
Steps to Execute:
1. Place [Link] file in C:\Program Files\Apache Software Foundation\Tomcat
5.0\webapps\ROOT\WEB-INF\classes
Ex: <servlet>
<servlet-name>Sessiondemo</servlet-name>
<servlet-class>Session</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Sessiondemo</servlet-name>
<url-pattern>/Session</url-pattern>
</servlet-mapping>
Page| 4
OUTPUT:
Page| 5
1(b). Write a program to demonstrate cookies using servlets.
Packages:
[Link]
[Link]
[Link]
[Link]
Note: Cookies are small bits of textual information that a Web server sends to a browser and
that the browser returns unchanged when visiting the same Web site or domain later. By having
the server read information it sent the client previously, the site can provide visitors with a
number of conveniences:
To send cookies to the client, a servlet would create one or more cookies with the appropriate
names and values via new Cookie(name, value) set any desired optional attributes via
[Link], and add the cookies to the response headers via [Link](cookie).To
read incoming cookies, call [Link](), which returns an array of Cookie objects. In
most cases, you loop down this array until you find the one whose name (getName) matches the
name you have in mind, then call getValue on that Cookie to see the value associated with that
name.
A Cookie is created by calling the Cookie constructor, which takes two strings: the cookie name
and the cookie value. Neither the name nor the value should contain whitespace or any of:
[]()=,"/?@:;
Before adding the cookie to the outgoing headers, you can look up or set attributes of the cookie.
Here's a summary:
getComment/setComment
Gets/sets a comment associated with this cookie.
Page| 6
getDomain/setDomain
Gets/sets the domain to which cookie applies. Normally, cookies are returned only to the
exact hostname that sent them. You can use this method to instruct the browser to return
them to other hosts within the same domain. Note that the domain should start with a dot
(e.g. .[Link]), and must contain two dots for non-country domains like .com, .edu,
and .gov, and three dots for country domains like .[Link] and .[Link].
getMaxAge/setMaxAge
Gets/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 (i.e. until the user quits the
browser), and will not be stored on disk.
getName/setName
Gets/sets the name of the cookie. The name and the value are the two pieces you virtually
always care about. Since the getCookies method of HttpServletRequest returns an array
of Cookie objects, it is common to loop down this array until you have a particular name,
then check the value with getValue.
getPath/setPath
Gets/sets the path to which this cookie applies. If you don't specify a path, the cookie is
returned for all URLs in the same directory as the current page as well as all
subdirectories. This method can be used to specify something more general. For example,
[Link]("/") specifies that all pages on the server should receive the cookie.
Note that the path specified must include the current directory.
getSecure/setSecure
Gets/sets the boolean value indicating whether the cookie should only be sent over
encrypted (i.e. SSL) connections.
getValue/setValue
Gets/sets the value associated with the cookie. Again, the name and the value are the two
parts of a cookie that you almost always care about, although in a few cases a name is
used as a boolean flag, and its value is ignored (i.e the existence of the name means true).
getVersion/setVersion
Gets/sets the cookie protocol version this cookie complies with. Version 0, the default, adheres
to the original Netscape specification.
Page| 7
[Link]:
<html>
<body bgcolor="red">
<input type="submit">
</form>
</body>
</html>
[Link]:
import [Link].*;
import [Link].*;
import [Link].*;
import [Link].*;
[Link]("text/html");
PrintWriter out=[Link]();
[Link]("<html>");
[Link]("<head>");
Page| 8
[Link]("<title> example Cookies</title>");
[Link]("</head>");
[Link]("<body>");
[Link]("hello");
String name=[Link]("cookiename");
String value=[Link]("cookievalue");
[Link](c);
for(int i=0;i<[Link];i++){
Cookie c=cookies[i];
String a=[Link]();
String b=[Link]();
[Link]("</body>");
[Link]("</html>");
Page| 9
Steps to Execute:
1. Place [Link] file in D:\Program Files\Apache Software Foundation\Tomcat
5.0\webapps\ROOT\WEB-INF\classes
Ex: <servlet>
<servlet-name>Cookiedemo</servlet-name>
<servlet-class>Cookie1</servlet-class>
</servlet>
<servlet-mapping>
<url-pattern>/Cookie</url-pattern>
</servlet-mapping>
P a g e | 10
OUTPUT:
P a g e | 11
[Link] a Java Web application to integrate JSP & Servlets.
Procedure:
1) Open NetBeans IDE.
2) Click on File, Choose New Project.
3) Select Web Application under Java Web and Click Next.
4) Choose a meaningful name for the project and specify the location for the project and
Click Next.
5) Choose Server, Java EE Version and Context Path for the application and Click Finish.
6) This will create a new Web Application.
7) Right Click on Project, Select New and Select JSP.
8) Choose File Name and Click Finish.
9) Right Click on Project->New->Other->JavaBeans Objects->JavaBeans Component and
Click Next.
10) Choose the Name, Package for the Bean file and Click Finish.
11) .Add Servlet to the Application.
12) Right click on project and New and Select Servlet.
13) Specify Name and Package for the servlet and Click Next.
14) Check the mark Add information to deployment descriptor and Click Finish.
15) This will add the new Servlet to the Project.
16) If you want to add a new java class to the existing project, then right click on project and
New and Select Java Class.
17) Choose the name for the class, Specify the package and click Finish.
18) Connect to your Database.
19) Create table UNTITLED for accessing user details from Database and for INSERTING
the details of corresponding data entry.
20) After the completion of project, Right Click on it and select Clean and Build.
21) Go to Services tab, expand Servers and Right Click on Glassfish Server and select Start.
22) Now Right Click on Project and Click Run.
23) This will open your application in browser.
P a g e | 12
[Link]:
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="NewServlet">
</form>
</body>
</html>
[Link]:
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
P a g e | 13
public class NewServlet extends HttpServlet {
@EJB
private NewSessionBeanLocal n;
[Link]("text/html;charset=UTF-8");
/* TODO output your page here. You may use following sample code. */
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet NewServlet</title>");
[Link]("</head>");
[Link]("<body>");
String name=[Link]("name");
String mobno=[Link]("mobno");
if (k==true)
[Link]("/[Link]").include(request, response);
else
[Link]("/[Link]").include(request, response);
P a g e | 14
}
@Override
processRequest(request, response);
@Override
processRequest(request, response);
@Override
}// </editor-fold>
P a g e | 15
[Link]:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<%
%>
</body>
</html>
[Link]:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<%
P a g e | 16
%>
</body>
</html>
[Link]:
package abc;
import [Link];
@Local
[Link]:
package abc;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Stateless
@Override
P a g e | 17
int i=0;
try {
[Link]("[Link]");
try {
Connection con;
con = [Link]("jdbc:derby://localhost:1527/it","it","it");
[Link](1,roll);
[Link](2,name);
[Link](3,mob);
i=[Link]();
if (i==1)
return true;
else
return false;
P a g e | 18
[Link]:
<?xml version="1.0" encoding="UTF-8"?>
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
P a g e | 19
OUTPUT:
P a g e | 20
3. Write a JSF application to demonstrate Party Planner.
PROCEDURE:
1. Open NetBeans IDE.
4. Choose a meaningful name for the project and specify the location for the project and Click
Next.
5. Choose Server, Java EE Version and Context Path for the application and Click Next.
9. Specify the Name and Package for the bean file and Click Finish.
11. If you want to add a new java class to the existing project, then right click on project and
New and Select Java Class.
12. Choose the name for the class, Specify the package and click Finish.
13. After the completion of project, Right Click on it and select Clean and Build.
14. Go to Services tab, expand Servers and Right Click on Glassfish Server and select Start.
P a g e | 21
[Link]:
<?xml version='1.0' encoding='UTF-8' ?>
<html xmlns="[Link]
xmlns:f="[Link]
xmlns:h="[Link]
<h:head>
<title>#{[Link]}</title>
</h:head>
<h:body>
<div align="center">
<h:form>
<h:selectOneMenu value="#{[Link]}">
</h:selectOneMenu><br/>
<h:selectBooleanCheckbox value="#{[Link]}"
></h:selectBooleanCheckbox><br/>
P a g e | 22
<h:commandButton value="Submit picture and parent choices" action="index"
/><br/>
<h:commandButton value="Reset to default" action="#{[Link]}"
/><br/><br/>
</h:form>
<br/><br/>
<h:outputText value="#{[Link]}"/><br/><br/>
<h:column >
#{[Link]}
</h:column>
<h:column>
#{[Link]}
</h:column>
</h:dataTable>
<br/><br/>
<p>
<h:form>
</h:form>
</p>
</div>
</h:body>
</html>
P a g e | 23
[Link]:
<?xml version='1.0' encoding='UTF-8' ?>
<html xmlns="[Link]
xmlns:h="[Link]
<h:head>
<title>Surprise !</title>
</h:head>
<h:body>
<div align='center'>
<img src="[Link]"/><br/>
<p>
<h:form>
</h:form>
</p>
</div>
</h:body>
</html>
[Link]
package [Link];
import [Link].*;
import [Link];
P a g e | 24
import [Link].*;
import [Link];
@Named("partyBean")
@SessionScoped
private List<Guest>items;
public PartyBean() {
[Link]();
return [Link];
[Link] = imageUri;
return name;
[Link] = name;
P a g e | 25
}
return parentsAllowed;
[Link] = on;
return [Link];
[Link] = false;
[Link] = "[Link]";
P a g e | 26
[Link](", ");
[Link](", ");
[Link]("and parents are " + (parentsAllowed ? "": "not") + " allowed to stay.");
return [Link]();
[Link]:
package [Link];
[Link] = name;
[Link] = age;
[Link] = age;
return [Link];
[Link] = name;
P a g e | 27
public String getName() {
return [Link];
P a g e | 28
OUTPUT:
P a g e | 29
4. Write a Program to demonstrate Asynchronous web sockets.
4. Choose a meaningful name for the project and specify the location for the project and Click
Next.
7. Specify name, package and endpoint for the websocket endpoint file and then click Finish.
[Link]:
<!DOCTYPE html>
<html>
<head>
<title>Chat Server</title>
<meta charset="UTF-8">
<script type="text/javascript">
var websocket=new
WebSocket("[Link]
[Link]=function processMessage(message){
if([Link]!=null)
[Link]+=[Link]+"\n";
P a g e | 30
}
function sendMessage(){
[Link]([Link]);
[Link]="";
</script>
</head>
<body>
</body>
</html>
[Link]:
package aaa;
import [Link];
import [Link].*;
import [Link];
import [Link].*;
@ServerEndpoint("/chatroomServerEndpoint")
@OnOpen
P a g e | 31
public void handleOpen(Session userSession){
[Link](userSession);
@OnMessage
String username=(String)[Link]().get("username");
if(username==null){
[Link]().put("username",message);
else{
while([Link]()){
[Link]().getBasicRemote().sendText(username+" : "+message);
@OnClose
[Link](userSession);
P a g e | 32
OUTPUT:
P a g e | 33
[Link] a Program to Demonstrate Stateful Session Bean (Shopping Cart).
Packages:
[Link]
[Link]
[Link]
[Link]
STEP1: Open the netbeans IDE 6.* and open the file newproject and select enterprise
application.
P a g e | 34
Step2: Name the application as shopping cart and set the project location
P a g e | 35
Step 4:Right click the bean and create new session bean
Step4:Name the bean with shopping cart and enter the package and mark either the local or
remote. Local if bean is different system then mark it as remote otherwise Local
P a g e | 36
Step5: Create the servlet in war file by right clicking the [Link] click in the
servlet file and select call enterprise bean to create instance of remote bean
P a g e | 37
[Link]:
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Stateful
@PostConstruct
item=null;
order=new ArrayList();
@PreDestroy
[Link]("Inside PreDestroy()");
item=new Item(pn,q,up);
[Link](item);
P a g e | 38
}
boolean flag=false;
item=(Item)[Link]();
if([Link](pn)) {
[Link](item);
flag=true;
break;
if(flag)
else
item=(Item)[Link]();
[Link]([Link]());
return order;
class Item {
P a g e | 39
public String pname;
pname=pn;
Qty=q;
uprice=up;
@Override
[Link]:
package [Link];
import [Link];
import [Link];
Collection getItems();
P a g e | 40
[Link]:
package c;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet(name="NewServlet", urlPatterns={"/NewServlet"})
NewSessionBeanLocal n = lookupNewSessionBeanLocal1();
[Link]("text/html;charset=UTF-8");
String name=[Link]("t1");
int qty=[Link]([Link]("t2"));
double price=[Link]([Link]("t3"));
P a g e | 41
[Link](name,qty,price);
@Override
processRequest(request, response);
@Override
processRequest(request, response);
@Override
try {
P a g e | 42
throw new RuntimeException(ne);
try {
[Link]:
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form action="NewServlet">
P a g e | 43
valu<input type="text" name="t3"><br>
<input type="submit">
</form>
</body>
</html>
Execution Steps:
1. Build Project
2. Run Project
P a g e | 44
Output:
P a g e | 45
6. Write a program to demonstrate Message Driven Bean.
Packages:
[Link],
[Link],
[Link],
[Link],
[Link],
[Link]
Step1: Create the application project type as enterprise application and right click the message
ejb and select new message driven bean.
P a g e | 46
[Link]:
package ab;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
})
P a g e | 47
public mesgbean() {
@Override
[Link]("bean");
TextMessage tm=(TextMessage)message;
try{
String te=[Link]();
}catch(JMSException e){
@PreDestroy
[Link]:
package asd;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
P a g e | 48
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServlet(name="NewServlet1", urlPatterns={"/NewServlet1"})
@Resource(name = "jms/newMessage")
@Resource(name = "jms/newMessageFactory")
[Link]("text/html;charset=UTF-8");
try{
try {
String note=[Link]("body");
P a g e | 49
if(note!=null)
{Connection conn=[Link]();
Session ses=[Link](false,Session.AUTO_ACKNOWLEDGE);
MessageProducer mp=[Link](newMessage);
TextMessage tm=[Link]();
[Link](note);
[Link](tm);
[Link]();
} catch (JMSException e) {
}}catch(Exception e)
@Override
processRequest(request, response);
@Override
processRequest(request, response);
P a g e | 50
@Override
[Link]:
<html>
<head>
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<form action="NewServlet1">
<textarea name="body">
</textarea><br><br>
</form>
</body>
</html>
P a g e | 51
Output:
P a g e | 52
7. Write a program to demonstrate Entity Bean
Procedure:
1. Create a JavaEE application.
2. Create a table to store the values of books in sample database.
3. Right click on ejb and choose New-> Entity classes from Database.
P a g e | 53
5. Select the table and click Add.
P a g e | 54
6. Click Next.
7. Click Finish.
8. This automatically creates a entity bean file for the selected database to store the values.
Expand your ejb application and select web services and expand it select [Link] file and
open it.
P a g e | 55
[Link]
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
</form>
</body>
</html>
[Link]
package book;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
P a g e | 56
import [Link];
import [Link];
import [Link];
import [Link];
@EJB
/**
* methods.
*/
[Link]("text/html;charset=UTF-8");
int id=[Link]([Link]("t0"));
String title=[Link]("t1");
String author=[Link]("t2");
int price=[Link]([Link]("t3"));
P a g e | 57
/* TODO output your page here. You may use following sample code. */
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet NewServlet</title>");
[Link]("</head>");
[Link]("<body>");
[Link](id,title,author,price);
[Link]("<p><b>Record added</b><p>");
Collection list=(Collection)[Link]();
[Link]("</body>");
[Link]("</html>");
P a g e | 58
}
/**
*/
@Override
processRequest(request, response);
/**
P a g e | 59
*/
@Override
processRequest(request, response);
/**
*/
@Override
}// </editor-fold>
[Link]
package book;
import [Link];
import [Link];
@Local
P a g e | 60
public void addBook(int id, String title, String author, int price);
[Link]
package book;
import [Link];
import [Link];
import [Link];
import [Link];
@Stateless
@PersistenceContext(unitName="entity_bean_book_bank-ejbPU")
EntityManager em;
@Override
if (book == null)
[Link](book);
P a g e | 61
}
@Override
//System. [Link]("u");
return bookList;
[Link]
package book;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@Entity
@Table(name = "BOOKBANK")
@XmlRootElement
@NamedQueries({
P a g e | 62
@NamedQuery(name = "[Link]", query = "SELECT b FROM Bookbank b"),
@Id
@Basic(optional = false)
@NotNull
@Column(name = "ID")
@Basic(optional = false)
@NotNull
@Column(name = "TITLE")
@Basic(optional = false)
@NotNull
@Column(name = "AUTHOR")
@Basic(optional = false)
P a g e | 63
@NotNull
@Column(name = "PRICE")
public Bookbank() {
[Link] = id;
[Link] = id;
[Link] = title;
[Link] = author;
[Link] = price;
return id;
[Link] = id;
return title;
[Link] = title;
P a g e | 64
}
return author;
[Link] = author;
return price;
[Link] = price;
@Override
int hash = 0;
return hash;
@Override
// TODO: Warning - this method won't work in the case the id fields are not set
return false;
P a g e | 65
Bookbank other = (Bookbank) object;
return false;
return true;
@Override
OUTPUT:
P a g e | 66
P a g e | 67
[Link] a web service application and web service client application to access web
service (to insert books into database).
Aim:
a)
Steps:
i) Create a project.
ii) Right click on ejb module
iii) Select New -> web Service
iv) Enter your service name and
v) Select the create web service from existing session Bean radio button
vi) Browse the file to which you want to create service.
vii) click Finish
viii) It creates a web service with the name you given.
ix) The services are listed in the web services folder in ejb module.
P a g e | 68
[Link]
<!DOCTYPE html>
<!--
-->
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
</form>
</body>
</html>
P a g e | 69
[Link]
package a;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@EJB
/**
* methods.
*/
[Link]("text/html;charset=UTF-8");
int s0=[Link]([Link]("t0"));
P a g e | 70
String s1=[Link]("t1");
String s2=[Link]("t2");
int s3=[Link]([Link]("t3"));
/* TODO output your page here. You may use following sample code. */
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet NewServlet</title>");
[Link]("</head>");
[Link]("<body>");
[Link]();
[Link]("</body>");
[Link]("</html>");
/**
P a g e | 71
* @param response servlet response
*/
@Override
processRequest(request, response);
/**
*/
@Override
processRequest(request, response);
/**
P a g e | 72
* Returns a short description of the servlet.
*/
@Override
}// </editor-fold>
[Link]
/*
*/
package a;
import [Link];
import [Link];
@Local
P a g e | 73
[Link]
/*
*/
package a;
import [Link];
import [Link];
import [Link];
import [Link];
@Stateless
@PersistenceContext(unitName="bookcatalog-ejbPU")
EntityManager em;
@Override
if (book == null)
P a g e | 74
[Link](book);
@Override
//System. [Link]("u");
return bookList;
[Link]
/*
*/
package a;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
P a g e | 75
import [Link];
import [Link];
import [Link];
@Entity
@Table(name = "BOOKBANK")
@XmlRootElement
@NamedQueries({
@Id
@Basic(optional = false)
@NotNull
@Column(name = "ID")
@Basic(optional = false)
@NotNull
P a g e | 76
@Column(name = "TITLE")
@Basic(optional = false)
@NotNull
@Column(name = "AUTHOR")
@Basic(optional = false)
@NotNull
@Column(name = "PRICE")
public Bookbank() {
[Link] = id;
[Link] = id;
[Link] = title;
[Link] = author;
[Link] = price;
return id;
P a g e | 77
public void setId(Integer id) {
[Link] = id;
return title;
[Link] = title;
return author;
[Link] = author;
return price;
[Link] = price;
@Override
int hash = 0;
P a g e | 78
return hash;
@Override
// TODO: Warning - this method won't work in the case the id fields are not set
return false;
return false;
return true;
@Override
[Link] (service)
package a;
import [Link];
import [Link];
import [Link];
import [Link];
P a g e | 79
import [Link];
import [Link];
import [Link];
@WebService(serviceName = "bookinsert")
@Stateless()
@EJB
private bookinsertionbeanLocal ejbRef;// Add business logic below. (Right-click in editor and
choose
@WebMethod(operationName = "addBook")
@Oneway
@WebMethod(operationName = "getAllBooks")
return [Link]();
} }
P a g e | 80
Web Service client application
Steps: i) Create a web application
P a g e | 81
[Link]
<!DOCTYPE html>
<!--
-->
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
</form>
</body>
</html>
P a g e | 82
[Link]
/*
*/
package a;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServiceRef(wsdlLocation = "WEB-
INF/wsdl/localhost_8080/bookinsert/[Link]")
[Link]("text/html;charset=UTF-8");
int s0=[Link]([Link]("t0"));
String s1=[Link]("t1");
String s2=[Link]("t2");
P a g e | 83
int s3=[Link]([Link]("t3"));
/* TODO output your page here. You may use following sample code. */
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet NewServlet</title>");
[Link]("</head>");
[Link]("<body>");
addBook(s0,s1,s2,s3);
[Link]("</body>");
[Link]("</html>");
@Override
processRequest(request, response);
@Override
P a g e | 84
processRequest(request, response);
@Override
}// </editor-fold>
private void addBook(int id, [Link] title, [Link] author, int price) {
// Note that the injected [Link] reference as well as port objects are not
thread safe.
// If the calling of port operations may lead to race condition some synchronization is
required.
P a g e | 85
Output:
P a g e | 86
9. Write a Web service and web service client application to validate credit card.
Aim:
To demonstrate a Web service and web service client application to validate credit card.
Web service :
[Link]
<!DOCTYPE html>
<!-- To change this license header, choose License Headers in Project Properties.
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
</form>
</body>
</html>
P a g e | 87
[Link]
package a;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@EJB
/**
* methods.
*/
[Link]("text/html;charset=UTF-8");
String num=[Link]("t0");
P a g e | 88
String date=[Link]("t1");
int cvv=[Link]([Link]("t2"));
/* TODO output your page here. You may use following sample code. */
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet NewServlet</title>");
[Link]("</head>");
[Link]("<body>");
int a=[Link](num,date);
if(a==1)
[Link]("valid card");
else
[Link]("invalid card");
[Link]("</body>");
[Link]("</html>");
P a g e | 89
/**
*/
@Override
processRequest(request, response);
/**
*/
@Override
P a g e | 90
processRequest(request, response);
/**
*/
@Override
}// </editor-fold>
[Link]
package a;
import [Link];
@Local
[Link]
package a;
import [Link];
import [Link];
import [Link];
P a g e | 91
import [Link];
@Stateless
@Override
int len=[Link]();
if(len<16)
return 0;
else
int a=[Link]([Link]([Link]()-4,[Link]()));
int b=[Link]([Link](0,2));
int year=[Link]([Link](d));
int month=[Link]([Link](d));
return 1;
else
P a g e | 92
return 0;
[Link]
package a;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebService(serviceName = "creditcardservice")
@Stateless()
@EJB
private validationLocal ejbRef;// Add business logic below. (Right-click in editor and choose
@WebMethod(operationName = "validate")
P a g e | 93
WebService client application
[Link]
<!DOCTYPE html>
<!--
-->
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
</form>
</body>
</html>
P a g e | 94
[Link]
package a;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
@WebServiceRef(wsdlLocation = "WEB-
INF/wsdl/localhost_8080/creditcardservice/[Link]")
/**
* methods.
*/
P a g e | 95
[Link]("text/html;charset=UTF-8");
String num=[Link]("t0");
String date=[Link]("t1");
int cvv=[Link]([Link]("t2"));
/* TODO output your page here. You may use following sample code. */
[Link]("<!DOCTYPE html>");
[Link]("<html>");
[Link]("<head>");
[Link]("<title>Servlet NewServlet</title>");
[Link]("</head>");
[Link]("<body>");
int a=validate(num,date);
if(a==1)
[Link]("valid card");
else
[Link]("invalid card");
[Link]("</body>");
[Link]("</html>");
P a g e | 96
/**
*/
@Override
processRequest(request, response);
@Override
processRequest(request, response);
@Override
}// </editor-fold>
// Note that the injected [Link] reference as well as port objects are not
thread safe.
P a g e | 97
// If the calling of port operations may lead to race condition some synchronization is
required.
Output:
P a g e | 98
P a g e | 99
10. Write a WSDL file for taking a message from the client and displaying it.
Aim: To demonstrate a WSDL file for taking a message from the client and displaying it.
<definitions name="HelloService"
targetNamespace="[Link]
xmlns="[Link]
xmlns:soap="[Link]
xmlns:tns="[Link]
xmlns:xsd="[Link]
<message name="SayHelloRequest">
</message>
<message name="SayHelloResponse">
</message>
<portType name="Hello_PortType">
<operation name="sayHello">
<input message="tns:SayHelloRequest"/>
<output message="tns:SayHelloResponse"/>
</operation>
</portType>
<soap:binding style="rpc"
transport="[Link]
P a g e | 100
<operation name="sayHello">
<soap:operation soapAction="sayHello"/>
<input>
<soap:body
encodingStyle="[Link]
namespace="urn:examples:helloservice"
use="encoded"/>
</input>
<output>
<soap:body
encodingStyle="[Link]
namespace="urn:examples:helloservice"
use="encoded"/>
</output>
</operation>
</binding>
<service name="Hello_Service">
<soap:address
location="[Link] />
</port>
</service>
</definitions>
P a g e | 101