27 October 2018

HelloWorld Servlet JSP Basic + Eclipse

Cấu trúc project
Creating a Java Dynamic Web Project
Creating a Java Servlet
HelloWorld.java
Servlet JSP 2018
package com.giaima;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorld
 */
@WebServlet("/hello-world")
public class HelloWorld extends HttpServlet {
   private static final long serialVersionUID = 1 L;

   /**
    * @see HttpServlet#HttpServlet()
    */
   public HelloWorld() {
      super();
      // TODO Auto-generated constructor stub
   }

   /**
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    */
   protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      // TODO Auto-generated method stub
      response.getWriter().append("Served at: ").append(request.getContextPath());

      String yourName = request.getParameter("yourName");
      PrintWriter writer = response.getWriter();
      writer.println("<h1>Hello " + yourName + "</h1>");
      writer.close();
   }

   /**
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    */
   protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      // TODO Auto-generated method stub
      doGet(request, response);
   }
}
Creating a JSP Page
index.jsp
Servlet JSP 2018
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
   pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
   <head>
      <meta charset="ISO-8859-1">
      <title>Insert title here</title>
   </head>
   <body>
      <h1>Hello JSP and Servlet!</h1>
      <form action="hello-world" method="post">
         Enter your name: <input type="text" name="yourName" size="20">
         <input type="submit" value="Call Servlet" />
      </form>
   </body>
</html>
Result

27/10/2018

0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang