What are Applets and Servlets in Java? Explain with Example
1
Expert's answer
2017-08-23T06:57:20-0400
Answer: Java applet - an application program, most often written in the Java programming language in the form of bytecode. Java applets are executed in a web browser using a virtual Java machine (JVM), or Apple's AppletViewer, a standalone applet testing tool. The <applet> tag is the basis for embedding an applet in an HTML file. Following is an example that invokes the "Hello, World" applet − <html> <title>The Hello, World Applet</title> <hr> <applet code = "HelloWorldApplet.class" width = "320" height = "120"> If your browser was Java-enabled, a "Hello, World" message would appear here. </applet> <hr> </html> Information taken from this page - https://www.tutorialspoint.com/java/java_applet_basics.htm
The servlet is a Java interface, the implementation of which expands the functionality of the server. The servlet interacts with clients through the request-response principle. Although servlets can serve any requests, they are used to extend Web servers. For such applications, Java Servlet technology defines HTTP-specific servlet classes. The javax.servlet and javax.servlet.http packages provide interfaces and classes for creating servlets. Following is the sample source code structure of a servlet example to show Hello World − // Import required java libraries import java.io.*; import javax.servlet.*; import javax.servlet.http.*;
// Extend HttpServlet class public class HelloWorld extends HttpServlet {
private String message;
public void init() throws ServletException { // Do required initialization message = "Hello World"; }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set response content type response.setContentType("text/html");
// Actual logic goes here. PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>"); }
public void destroy() { // do nothing. } }
Information taken from this page - https://www.tutorialspoint.com/servlets/servlets-first-example.htm
Comments
Leave a comment