A rough explanation of how Java-based web applications work

Introduction

I joined an IT company a few months ago as an inexperienced person. I spent about two months developing a web application using Java in the training. I will briefly summarize what I learned. I think there are many mistakes, so it would be helpful if you could point out more and more. ** * Development method and procedure are not written. It roughly describes the terms and the whole picture necessary for knowledge. ** **

Target

--Those who have created static web pages with HTML / CSS but do not know what kind of knowledge is required to create dynamic web applications. --Those who understand how to write Java code but cannot see the whole picture when creating a dynamic web application

Web client and web server

First of all, the web page you are looking at on your browser is realized by computers (software) called ** client ** and ** server **.

Web client

A computer (software) that requests some service from a server and is provided with that service by the server is called a client. A web client that can be used by accessing a web page stored on a web server is called a web client. You can imagine a web client as a browser such as Chrome or IE.

Web server

A computer (software) that provides a client with some kind of service or function in response to a request from the client is called a server. Servers include web servers, mail servers, database servers, application servers, etc. A server that responds to access from a web client is called a web server. Apache, IIS, nginx, etc. are well-known web server software.

スクリーンショット 2018-10-01 22.32.10.png

Flow of displaying a web page

Now, about how to display a web page, For example, when a user wants to search something on Google, the URL field on the browser You can access it by typing https://www.google.com. When you actually access it, the Google page will be displayed instantly, but when you look at it between the client and the server, The following interactions occur while users try to access Google pages: スクリーンショット _流れ2.png

** 1. Web client sends Request message to web server ** ** 2. Based on the message, the web server prepares the web page requested by the web client ** ** 3. The web server sends a Resonse message to the web client and the web page is displayed ** The messages sent and received here are exchanged using a protocol called ** HTTP **.

protocol

A protocol is simply a rule when computers interact with each other. For example, when talking between Japanese people, it is the same as talking in the language (rule) of Japanese. When a web client and a web server communicate with each other, they send and receive using a protocol (rule) called HTTP. By doing so, you can browse the web page on the client side. However, a mere web server can only display a static web page, and in order to display a dynamic web page, software for executing the process is required. In addition, there are two types of request messages sent by the client to the web server, ** GET ** and ** POST **, and it is necessary to properly use these to realize a dynamic web page. .. First, let's compare a static web page with a dynamic web page before explaining the software, GET, and POST.

Static and dynamic content

Static web page

When displaying a static web page, as shown in the image below, the web page requested by the web client to the web server Since it is returned to the Web client as a response as it is, the same page content will be returned no matter how many times you request it. In other words, an image that returns the HTML file stored in advance on the Web server as it is. スクリーンショット_静的なページ.png

Dynamic web page

When displaying a dynamic web page, the web client requests the web server and I'm doing something and then returning the web page to the web client. In other words, an image that generates HTML text by executing some processing (program) on the Web server side. In the case of the image below, the displayed content of the web page you just accessed is Hello World!, By entering Qiita in the input form and pressing the button, you can change the display content of the web page to Qiita. スクリーンショット_動的なページ4.png

In this way, some kind of processing (program) is required to realize a dynamic Web page, Software that executes the program is required to execute the process. This kind of processing will be implemented in C language and programming languages such as PHP and Java.

Flow of displaying dynamic web pages

Earlier, I explained the flow of displaying a web page, but I focused on displaying a dynamic web page (program execution). I would like to explain the flow of displaying a web page.

Run the application inside the web server

First, as an example, if you implement a web page in PHP, the web server does not have a module to execute PHP files, so Extend the web server by embedding the PHP execution module in the web server. If your web server uses Apache, include a PHP execution module called mod_php5 to run PHP scripts. Doing so will generate an HTML file within the web server and return it to the client. That is, the flow is as follows. ** 1. Web client sends Request message to web server ** ** 2. Based on that message, run the application in the module built into the web server ** ** 3. The executed application generates HTML text ** ** 4. The web server sends a Resonse message to the web client and the web page is displayed ** スクリーンショット_流れ_php.png

Run the application on the application server

Next, if you want to implement a web page in Java as an example, prepare an application server. An application server is software for running applications Well-known Java application servers include ** Tomcat **, Jetty, and GlassFish. The application server prepared here is different from the Web server, so it cannot be easily exchanged. To allow communication between the web client and web server using the HTTP protocol It requires some protocol to allow communication between the web server and the application server as well. If the web server is ** Apache ** and the application server is ** Tomcat ** Apache provides a cooperation module called ** mod_jk **, which is included as an extension of Apache. The cooperation module ** mod_jk ** uses a protocol called ** ajp13 ** to realize communication between the Web server and the application server. By the way, Tomcat also has a simple web server, so you can display dynamic web pages without any cooperation. By allowing communication between the web server and the application server, requests from the web client reach the application server, HTML text is generated by executing the process based on the message. In other words, the flow is as follows. ** 1. The web client sends a Request message to the web server using the HTTP protocol ** ** 2. Web server sends Request message to application server (Tomcat) using ajp13 protocol ** ** 3. The application server executes the application based on the message ** ** 4. The executed application generates HTML text ** ** 5. The application server sends a Resonse message to the web server using the ajp13 protocol ** ** 6. The web server sends a Resonse message to the web client using the HTTP protocol and the web page is displayed ** スクリーンショット_流れ_java.png In this way, dynamic web page display can be realized by using modules and application servers. Next, I will explain what kind of application is executed to generate the HTML file using Java.

Servlet

A Servlet is a program for generating Web content such as HTML written in Java, which is executed by an application server such as Tomcat. I actually created a simple Servlet called ServletController.java as shown below.

ServletController.java


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;

@WebServlet("/ServletController")
public class ServletController extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public ServletController() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Character code setting
		response.setContentType("text/html; charset=UTF-8");

        //HTML to send to client
		PrintWriter out = response.getWriter();
		out.println("<html>");

		//header
		out.println("<head>");
		out.println("<title>");
		out.println("Test");
		out.println("</title>");
		out.println("</head>");

		//body
		out.println("<body>");

		out.println("<h1>");
		out.println("Dynamic web page");
		out.println("</h1>");

		out.println("<p>");
		out.println("This is the web content generated by the Servlet executed by Tomcat.");
		out.println("</p>");

		out.println("</body>");
		out.println("</html>");
        out.close();
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}

By executing this Servlet, the following web page can be displayed on the browser. スクリーンショット_サーブレット2.png By the way, this web page cannot be changed, so you may feel that it is a static web page. After the request from the web client, the HTML file stored in the web server is not displayed as it is. This is a dynamic web page because the application server runs the java file to generate the HTML text and display it in the browser.

GET and POST

Next, we will explain how the display content is changed, as in the dynamic Web page (static content and browser image in the dynamic content) in the above example. In the dynamic web page in the example above, I changed the characters from Hello World! To Qiita. As shown in the flow of displaying a web page, the web client can only send a Request message as a way to send information to the web server. In other words, in order to change the display content of the Web page, it is necessary to send the Request message with a parameter (arbitrary value). Therefore, there are two types of request message transmission methods, GET and POST, so let's compare how these have parameters.

We have prepared a simple web page that allows you to send a Request message by GET or POST, as shown below. By the way, the URL when you access this web page is 192.168.56.101/Test/TestController. スクリーンショット_GETPOST1.png

GET First, try sending the Request message with GET and the parameter as Qiita. スクリーンショット_GETPOST6.png Of course, the part that was displayed as Hello World! Was changed to Qiita, At the same time, the URL was changed from 192.168.56.101/Test/TestController to 192.168.56.101/Test/TestController?inputText=Qiita. In other words, when GET is used as the method for sending the Request message, the sent parameters are embedded in the URL and reach the web server. By the way, in this case ʻinputText is the key and Qiitais the value for that key. POST Next, try sending the Request message with POST and the parameter asQiita. <img width="594" alt="スクリーンショット_GETPOST7.png " src="https://qiita-image-store.s3.amazonaws.com/0/296506/c2c1ffb9-d3e9-4a76-048d-f666e3d2b58c.png "> Of course, the part that was displayed as Hello World!Was changed toQiita, but Unlike GET, the URL remains 192.168.56.101/Test/TestController`. In other words, when POST is used as the method for sending the Request message, the sent parameter is not included in the URL, but is included in the Request message and reaches the Web server.

Proper use of GET and POST

Consider a real example. If you go to Googlehttps: //www.google.com and enter Qiita in the search word, The URL field on the browser is accessed as https://www.google.com/search?hl=ja&q=Qiita. In other words, Google search is sending a Request message with GET. By sending with GET, you can easily access it again by bookmarking it when you want to see this page again later. It is better to use GET when there is not much problem even if other people see the search conditions and it is convenient to save each parameter. POST, on the other hand, should be used to send and access content that should not be seen by humans, or to rewrite a database. Below is a brief summary of the differences.

GET request POST request
Method to use GET POST
Parameter storage location URL Message body
Security Low Relatively expensive
Parameter length Up to 255 characters in older software No limit
Parameter storage / reproduction It's easy to do Difficult to do

Relationship between Servlet and GET / POST

Regarding what kind of processing is done on the application side by sending the Request message by either GET or POST, As you can see from the source code of the Servlet earlier, There were methods ** doGet ** and ** doPost ** in the ServletController class. If the Request message is sent by GET, the doGet method is implemented and If the Request message is sent by POST, the doPost method will be implemented to generate the HTML text.

How to send GET and POST

Let's check what the HTML text actually generated for displaying a web page looks like. The HTML text when accessing 192.168.56.101/Test/TestController is as follows.

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
	<h1>Dynamic web page</h1>
	<p>Send parameters with GET</p>
	<form action="TestController" method="get">
		<input type="text" name="inputText" >
		<button type="submit">Character change(GET)</button>
	</form>
	<p>Send parameters by POST</p>
	<form action="TestController" method="post">
		<input type="text" name="inputText" >
		<button type="submit">Character change(POST)</button>
	</form>
	<p>HelloWorld!</p>

</body>
</html>

Regarding ʻaction and methodspecified in the form tag, action specifies which class file (.java) to execute, method specifies how to send the request message (get or post). In other words, if you press the submit button in a form tag on the client side, a request message will be sent to the web server. ThedoGet or doPost method of the class specified in action is executed. At that time, if there is a parameter to be sent, the parameter is also sent. In this case, the name of the input tag will be the key ʻinputText and the entered string will be sent as the value Qiita. And the Servlet for 192.168.56.101/Test/TestController looks like this:

TestController.java


package controller;

import java.io.IOException;

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

@WebServlet("/TestController")
public class TestController extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public TestController() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Character code setting
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

        //Setting parameters used in JSP
		if(request.getParameter("inputText") != null) {
			request.setAttribute("inputText", request.getParameter("inputText"));
		}

		//Page navigation
		ServletContext context = this.getServletContext();
		RequestDispatcher dispatcher = context.getRequestDispatcher("/TestView");
		dispatcher.forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//Character code setting
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

        //Setting parameters used in JSP
		if(request.getParameter("inputText") != null) {
			request.setAttribute("inputText", request.getParameter("inputText"));
		}

		//Page navigation
		ServletContext context = this.getServletContext();
		RequestDispatcher dispatcher = context.getRequestDispatcher("/TestView");
		dispatcher.forward(request, response);
	}

}

You don't need to understand the contents of this source file in detail at all, but please note that There is no process to output html tags etc. as described in ServletController.java. This process does not need to be described because ** Servlet ** and ** JSP ** share roles and cooperate.

JSP A JSP is simply an embedded Java code in HTML format. Efficient development can be achieved by sharing the processing between the Servlet and the JSP that displays it. Below is the JSPTestView.jsp called from the Servlet TestController.java mentioned above.

TestView.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
</head>
<body>
	<h1>Dynamic web page</h1>
	<p>Send parameters with GET</p>
	<form action="TestController" method="get">
		<input type="text" name="inputText" >
		<button type="submit">Character change(GET)</button>
	</form>
	<p> </p>
	<p>Send parameters by POST</p>
	<form action="TestController" method="post">
		<input type="text" name="inputText" >
		<button type="submit">Character change(POST)</button>
	</form>
	<p>
	<%
	if(request.getAttribute("inputText") == null){
		out.println("HelloWorld!");
	}else{
		out.println(request.getAttribute("inputText"));
	}
	%>
	</p>
</body>
</html>

Since JSP is in HTML format, when embedding Java code, We will incorporate it in the tag <% ...%>. To output characters to a Web page, enter the character string you want to display in the argument of ʻout.println (); . In addition, you can output a character string with <% = variable%>`. If you want to read an external file of CSS or JavaScript, fill in the header part as well as HTML.

In this way, it is easier to develop by separating the roles of the Servlet in charge of processing and the JSP in charge of display. However, if you want to handle a Web application while storing and managing some data, you cannot develop efficiently by simply separating it into a Servlet and a JSP, and at the same time, at the same time. You need a server that can store and manage large amounts of data. The server that can store and manage that large amount of data is the ** database server **. MySQL, Oracle DataBase, PostgreSQL, etc. are well-known database server software. By using such a database server, you can manage a large number of databases through a web application. And when developing a Web application using the large amount of database, you can efficiently perform large-scale development by using the development method called ** MVC model **.

MVC model

The MVC model develops application software by dividing it into three roles: ** Model **, ** View **, and ** Controller **. I will briefly explain each of them. Model The model is responsible for processing the application. For example, managing data, accessing databases and managing methods. The process is executed according to the instruction from the controller. A typical java file is the model. View The view is responsible for displaying the application. The output result is passed from the controller. The view is a JSP file written in HTML format. Controller The controller receives information input from View (screen), calls Model (processing and data), and is in charge of outputting the result to View. In other words, the process for a specific View and the flow of a specific process are written in one controller. The Servlet class is the controller.

MVC model flow

The processing flow of the application when divided into these three roles is as follows. ** 1. Client sends Request message to server ** ** 2. The Controller in the application is executed based on the Request message and calls the Model process ** ** 3. Model called from Controller accesses DB or executes processing ** ** 4. Model passes the processing result to Controller ** ** 5. Controller instructs View to output based on the processing result (HTML text generation) ** ** 6. The server sends a Resonse message to the client and the web page is displayed ** スクリーンショット_MVC.png This is a simple flow of the MVC model, but strictly speaking, there are types such as MVC2, MVP, MVVM, etc., and it should be changed appropriately depending on the application to be developed.

Flow of the entire web application

Based on the above, the overall mechanism of a Java Web application is as follows. スクリーンショット_All流れ.png Of course, there is a web client on the client side, and there are web servers, application servers, and database servers on the server side. When building a server, install a web server, application server, database server, etc. and execute each of them so that they will operate normally when you access the web application. If you add a new application, you can install, run, and extend the application server that runs it.

reference

Yusuke Komori (2010/4/10) "Introduction to Web Technology to Become a Professional" -Why Can't You Develop a Web System? Gijutsu-Hyoronsha

Recommended Posts

A rough explanation of how Java-based web applications work
A brief explanation of commitAllowingStateLoss
How Microservices Change the Way of Developing Applications
[Rough explanation] How to separate the operation of the production environment and the development environment with Rails
Understand in 3 minutes! A very rough explanation of the difference between session and cookie