Professional Documents
Culture Documents
Applet
Applet is a special type of program that is
embedded in the webpage to generate the
dynamic content. It runs inside the browser and
works at client side.
Advantage of Applet
It
Drawback of Applet
Plug-in
Hierarchy of Applet
java.applet.Applet class
For creating any applet java.applet.Applet class must be
inherited. It provides 4 life cycle methods of applet.
public void init(): is used to initialized the Applet. It is
invoked only once.
public void start(): is invoked after the init() method or
browser is maximized. It is used to start the Applet.
public void stop(): is used to stop the Applet. It is invoked
when Applet is stop or browser is minimized.
public void destroy(): is used to destroy the Applet. It is
invoked only once.
java.awt.Component class
public void paint(Graphics g): is used to paint the
Applet. It provides Graphics class object that can be used
for drawing oval, rectangle, arc etc.
myapplet.html
<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
To execute
import java.applet.Applet;
import java.awt.*;
public class GraphicsDemo extends Applet{
public void paint(Graphics g){
g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
Syntax:
public Image getImage(URL u, String image){}
public
import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet {
Image picture;
public void init() {
picture = getImage(getDocumentBase(),"sonoo.jpg");
}
public void paint(Graphics g) {
g.drawImage(picture, 30,30, this);
}
}
<html>
<body>
<applet code="DisplayImage.class" width="300"
height="300">
</applet>
</body>
</html>
OUTPUT
import java.applet.Applet;
import java.awt.Graphics;
public class UseParam extends Applet{
public void paint(Graphics g)
{ String str=getParameter("msg");
g.drawString(str,50, 50); }
}
<html>
<body>
<applet code="UseParam.class" width="300" height="300">
<param name="msg" value="Welcome to applet"> </applet>
</body>
</html>
OUTPUT
Animation in applet:
import java.awt.*;
import java.applet.*;
public class AnimationExample extends Applet {
Image picture;
public void init() {
picture =getImage(getDocumentBase(),"bike_1.gif");
}
public void paint(Graphics g) {
for(int i=0;i<500;i++){
g.drawImage(picture, i,30, this);
try{Thread.sleep(100);}catch(Exception e){}
}
}
}
OUTPUT
EventHandling
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class EventApplet extends Applet implements ActionListener{
Button b;
TextField tf;
public void init(){
tf=new TextField();
tf.setBounds(30,40,150,20);
b=new Button("Click");
b.setBounds(80,150,60,50);
add(b);add(tf);
b.addActionListener(this);
setLayout(null);
}
public void actionPerformed(ActionEvent e){
tf.setText("Welcome");
}
}
OUTPUT
Invoking an Applet:
An applet may be invoked by embedding directives in an
HTML file and viewing the file through an applet viewer
or Java-enabled browser.
The
movies
Flash movies
Windows Media Player applets, used to display
embedded video files in Internet Explorer (and
other browsers that support the plugin)
3D modeling display applets, used to rotate and
zoom a model
Browser games can be applet-based, though some
may develop into fully functional applications that
require installation.
Applets are treated as untrusted because they are developed by somebody and
placed on some unknown Web server. When downloaded, they may harm the
system resources or steal passwords and valuable information available on the
system. As applets are untrusted, the browsers come with many security
restrictions. Security policies are browser dependent. Browser does not allow
the applet to access any of the system resources (applet is permitted to use
browser resources, infact, applet execution goes within the browser only).
Applets are not permitted to use any system resources like file system as they
are untrusted and can inject virus into the system.
Applets cannot use any software available on the system (except browser
execution area)
Question
Create a Applet that can Draw.
Painting in Applet
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class MouseDrag extends Applet implements MouseMotionListener{
public void init(){
addMouseMotionListener(this);
setBackground(Color.red);
}
public void mouseDragged(MouseEvent me){
Graphics g=getGraphics();
g.setColor(Color.white);
g.fillOval(me.getX(),me.getY(),5,5);
}
public void mouseMoved(MouseEvent me){}
}
JAVA SERVLET
What Is a Servlet?
A servlet
E.g.
Mail Server
Disadvantages of CGI
If
Servlet Terminology
1.
2.
3.
4.
5.
6.
HTTP
HTTP Request Types
Difference between Get and Post method
Container
Server and Difference between web server
and application server
Content Type
HTTP
Http
Container
It provides runtime environment for JavaEE (j2ee)
applications.
It performs many operations that are given below:
Life
Cycle Management
Multithreaded support
Object Pooling
Security etc.
Server
It is a running program or software that provides
services.
There are two types of servers:
Web Server
Application Server
Web Server
Web server contains only web or servlet container. It can be
used for servlet, jsp, struts, jsf etc. It can't be used for EJB.
Example of Web Servers are: Apache Tomcat and Resin.
Application Server
Application server contains Web and EJB containers. It can
be used for servlet, jsp, struts, jsf, ejb etc.
Example of Application Servers are:
JBoss Open-source server from JBoss community.
Glassfish provided by Sun Microsystem. Now acquired by
Oracle.
Weblogic provided by Oracle. It more secured.
Websphere provided by IBM.
Content Type
Content Type is also known as MIME (Multipurpose internet Mail
Extension) Type. It is a HTTP header that provides the description about
what are you sending to the browser.
There are many content types:
text/html
text/plain
application/msword
application/vnd.ms-excel
application/jar
application/pdf
application/octet-stream
application/x-zip
images/jpeg
video/quicktime etc.
class is loaded.
Servlet instance is created.
init method is invoked.
service method is invoked.
destroy
method is invoked.
Implementation
Servlet use Classes and Interfaces from 2 packages
javax.servlet
It contains classes to support generic protocol
javax.servlet.http
javax.servlet package
Javax.servlet.http package
(deprecated now)
ServletRequest Interface
An object of ServletRequest is used to provide the
client request information to a servlet such as
content type, content length, parameter names and
values, header informations, attributes etc.
Description
java.util.Enumeration getParameterNames()
public ServletInputStream getInputStream() Returns an input stream for reading binary data in the
throws IOException
request body.
public abstract String getServerName()
DemoServ.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServ extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
String name=req.getParameter("name");//will return value
pw.println("Welcome "+name);
pw.close();
}}
Servlet Collaboration
The Servlet collaboration is all about sharing information among
the servlets. Collaborating servlets is to pass the common
information that is to be shared directly by one servlet to
another through various invocations of the methods. To perform
these operations, each servlet need to know the other servlet
with which it is collaborated.
Here are several ways to communicate with one another:
Using RequestDispatchers include() and forward() method;
Using HttpServletResponse sendRedirect() method;
Using ServletContext setAttribute() and getAttribute() methods.
RequestDispatcher in Servlet
The RequestDispatcher interface provides the facility
of dispatching the request to another resource it
may be html, servlet or jsp. This interface can also
be used to include the content of another resource
also. It is one of the way of servlet collaboration.
There are two methods defined in the RequestDispatcher
interface.
void forward(ServletRequest
request,ServletResponse response)throws
ServletException,java.io.IOException: Forwards
a request from a servlet to another resource
(servlet, JSP file, or HTML file) on the server.
public void include(ServletRequest
request,ServletResponse response)throws
ServletException,java.io.IOException: Includes
the content of a resource (servlet, JSP page, or
HTML file) in the response.
Syntax
of getRequestDispatcher method
public RequestDispatcher getRequestDispatcher(String resource);
Example
index.html
index.html
Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Login extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
}
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WelcomeServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
}
web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
SendRedirect in servlet
The
sendRedirect() method of
HttpServletResponse interface can be used
to redirect response to another resource, it
may be servlet, jsp or html file.
It accepts relative as well as absolute URL.
It works at client side because it uses the url
bar of the browser to make another request.
So, it can work inside and outside the server.
DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
response.sendRedirect("http://www.google.com");
pw.close();
}}
<form action="MySearcher">
<input type="text" name="name">
<input type="submit" value="Google Search">
</form>
</body>
</html>
MySearcher.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySearcher extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletRespo
nse response)
throws ServletException, IOException {
String name=request.getParameter("name");
response.sendRedirect("https://www.google.co.in/#q="+name);
}
}
1.
2.
3.
4.
5.
6.
2. Create a Servlet
There are three ways to create the servlet.
By implementing the Servlet interface
By inheriting the GenericServlet class
By inheriting the HttpServlet class
The HttpServlet class is widely used to create the servlet
because it provides methods to handle http requests such
as doGet(), doPost, doHead() etc.
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
//writing html in the stream
pw.println("<html><body>");
pw.println("Welcome to servlet");
pw.println("</body></html>");
pw.close();//closing the stream
}}
Web.xml
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
After
JDBC
a connection to a database.
Creating SQL or MySQL statements.
Executing SQL or MySQL queries in the
database.
Viewing & Modifying the resulting records.
JDBC Architecture
The
Statement:
Output
Connecting to database...
Creating statement...
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal