[Java] [Java] Understanding Servlet for beginners-①

1 minute read

table of contents

  • Introduction
  • What is a Servlet?
  • Class declaration
  • Main methods -doGet(), doPost() -getWriter() -setContentType()
  • Exception
  • in conclusion


This article “・”I will do Java from now on” “・I’m doing Java, but I would like to review it a lot~” It is a miscellaneous content for people. The author is also studying hard, so I cannot guarantee the accuracy of the content. .. .. I hope to help everyone’s learning ~~ (Notepad of my learning) ~~.

What is #Servlet? In a word, “Java program running on the server side”.

· Regular class file →File exchange under local environment

  • Servlet class file → Servlet performs processing according to HTTP request and outputs as response Image.
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;

public class HelloServlet extends HttpServlet {
    // A method that sets the HTTP response to be returned for the HTTP request that was sent by GET
    public void doGet(HttpServletRequestrequest,HttpServletResponse response)
            throws IOException, ServletException {

        //The format of the file returned as HTTP response is "html",
        // Specify the character set as "UTF-8"
        response.setContentType("text/html; charset=UTF-8");
        PrintWriter out = response.getWriter();


Class declaration

Servlet is created as an inherited class of HttpServlet class

public class HelloServlet extends HttpServlet{

Main methods

● doGet(), doPost();

public void doGet[doPost](HttpServletRequestrequest,HttpServletResponse){

A method that returns an HTTP response to a Get/Post request. The first argument corresponds to the HTTP request and the second argument corresponds to the HTTP response.

● setContentType()
response.setContentType("text/html; charset=UTF-8");

A method that specifies the “format” and “character code” of the file output as an HTTP response. Set value is reflected in Content-Type of html header

● getWriter()
PrintWriter out = response.getWriter();

Method to get the stream for output Create a PrintWriter class as an out object so that you can use PrintWriter class methods such as println() *The contents of println() are written as an html file.


The following two exceptions occur

  • IOException
  • ServletException

Servlet class is not operated by itself and is often operated by calling from other main class (?) Exception is thrown to the calling class.

public void doGet(HttpServletRequestrequest,HttpServletResponse response)
        throws IOException, ServletException {

in conclusion

Difficult sentences/Difficult to understand… I’m now able to write more informative sentences. I’ll do my best to post so that I can improve gradually.