In java, both Applets and servlets are the programs or applications that run in a java environment. The main difference in both the programs is in their processing is done in different environments.
The following are the important differences between Applets and Servlets.
| Sr. No. | Key | Applets | Servlets |
|---|---|---|---|
| 1 | Execution | Applets are executed on client-side i.e applet runs within a Web browser on the client machine. | Servlets on other hand executed on the server-side i.e servlet runs on the web Page on server. |
| 2 | Parent packages | Parent package of Applet includes java.applet.* and java.awt.* | Parent package of Servlet includes javax.servlet.* and java.servlet.http.* |
| 3 | Methods | Important methods of applet includes init(), stop(), paint(), start(), destroy(). | Lifecycle methods of servlet are init( ), service( ), and destroy( ). |
| 4 | User interface | For the execution of the applet, a user interface is required such as AWT or swing. | No such interface is required for the execution of servlet. |
| 5 | Required Bandwidth | The applet requires user interface on the client machine for execution so it requires more bandwidth. | On the other hand, Servlets are executed on the servers and hence require less bandwidth. |
| 6 | Secure | Applets are more prone to risk as execution is on the client machine. | Servlets are more secure as execution is under server security. |
Example of applet vs servlet
AppletDemo.java
import java.applet.Applet;
import java.awt.Graphics;
public class AppletDemo extends Applet {
// Overriding paint() method
@Override
public void paint(Graphics g){
g.drawString("AppletDemo", 20, 20);
}
}Output
AppletDemo
Example
ServletDemo.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletDemo extends HttpServlet {
private String message;
public void init() throws ServletException{
// Do required initialization
message = "Servlet Demo";
}
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(message);
}
}Output
Servlet Demo