Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
JSP and Servlet Example Code This handout containts simple examples of JSP and a Servlet. JavaServer Pages Example This page using JSP to using the Java Random class in a website: <%-This is a simple JSP file than uses the Java Random Object to do a sum. --%> <%-- Notice that java.util.Random is imported in below --%> <%@page contentType="text/html" pageEncoding="UTF-8" import="java.util.Random" <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>JSP Page</title> </head> <body> <h1>Hello World!</h1> <%-- JSP lets you put Java code your HTML, it goes between the <% %> tags, and must write to out --%> <% out.println("Here is an example of a sum: "); // Generated two random numbers using java.util.random Random gen = new Random(); int x = gen.nextInt(); int y = gen.nextInt(); // Print their product out.print(x+" times " +y+" = "); out.println(x*y); %> </body> </html> 1 %> Servlet Example This servlet example writes a very simple webpage: /* * A very simple HTTPServlet. * The page this servlet respondes to is set when the project is created * When the webpage is requested the doGet method is called. * Everything written to out is returned to the client as part of the * HTTP response. */ import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author tpc */ public class NewServlet extends HttpServlet { /** * Handles the HTTP <code>GET</code> method. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String hello = "Hello World"; out.println("<html>"); out.println("<head>"); out.println("<title>Servlet NewServlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h1>"+ hello + "</h1>"); out.println("This webpage was generated dynamically."); out.println("</body>"); out.println("</html>"); } finally { out.close(); } } } 2