--Introduction --What is Servlet? --Class declaration --Main methods - doGet(), doPost() - getWriter() - setContentType() --Exception
This article is ・ "I'm going to do Java now" ・ "I'm doing Java, but I want to review it." It is a rough content for people. I am also studying hard, so I do not guarantee the accuracy of the content. .. .. I hope it will help you in your learning ~~ (notepad for your own learning) ~~.
In a nutshell, it's a server-side Java program </ b>.
・ Normal class file → File exchange in the local environment -Servlet class file → The Servlet performs processing according to the HTTP request and outputs it as a response. Image of.
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 {
//Method to set the HTTP response to be returned for the HTTP request sent by GET
public void doGet(HttpServletRequestrequest,HttpServletResponse response)
throws IOException, ServletException {
//Change the format of the file returned as an HTTP response to "html"
//Set the character set to "UTF-Designated as "8"
response.setContentType("text/html; charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<body>HelloServlet</body>");
}
}
Servlet is created as an inherited class of HttpServlet class
public class HelloServlet extends HttpServlet{
}
●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 to be output as an HTTP response. The set value is reflected in Content-Type of html header
●getWriter()
PrintWriter out = response.getWriter();
Method to get stream for output By creating the PrintWriter class as an out object, you can use PrintWriter class methods such as println ().
The following two exceptions occur
Since the Servlet class is not operated by itself and is often operated by calling from another main class (?), Exceptions are thrown to the calling class.
public void doGet(HttpServletRequestrequest,HttpServletResponse response)
throws IOException, ServletException {
}
Difficult sentences / difficult to understand ... I want to be able to write more sentences. I'll do my best to post so that I can improve gradually ~~
Then.
Recommended Posts