[JAVA] Getting Started with JSP & Servlet

Introduction

Please refer to Ultra-basic usage of Eclipse --Qiita for setting up the development environment.

First, let's check the operation of Servlet and JSP. (This article) After that, I will explain the basics of Web application development by JSP & Servlet through the development of TODO application. (Next time)

Creating a project

1 2 3
Creating a project(1) Creatingaproject(2) Creatingaproject(3)

Creating HelloServlet

First, create a very simple Servlet to check the operation.

Creating a Servlet class

Execution of Servlet

1 2 3
Screenshot 2017-06-22 14.51.48.png Screenshot2017-06-2214.52.29.png Screenshot2017-06-2214.53.09.png

Creating index.jsp

Next, check the operation of JSP.

Creating a JSP file

index.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Hello, World!</title>
</head>
<body>
	<%= new java.util.Date() %>
</body>
</html>

Access http: // localhost: 8080 / TodoServlet / with the built-in browser of Eclipse or the browser you normally use.

スクリーンショット 2017-06-22 15.13.18.png

Source code so far: Kazunori-Kimura / todo-servlet at v1.0.0


We have confirmed the creation method and operation of Servlet and JSP. Eclipse creates templates for classes and files, so it seems like you can create a web application just by fleshing it out.


Cooperation between Servlet and JSP

JSP is converted to Servlet by Tomcat and executed. Therefore, what you can do with Servlet should basically be possible with JSP.

However, if you stuff the detailed logic into the JSP that embeds the code in HTML, the source code will soon become unclear.

By dividing the roles, the outlook will improve and development will proceed smoothly.

I will explain how to link Servlet and JSP using a simple example.

Forward from Servlet to JSP

First, simply receive the request with Servlet and implement it to return the contents of JSP.

Move index.jsp

Move ʻindex.jsp under WEB-INFso that the JSP is not accessed directly. In the future, we will create aWEB-INF / view` folder and place the JSP files under it so that it will be easier to manage when there are multiple JSP files.

HelloServlet fix

When a client (browser) makes a request to HelloServlet, the doGet method is executed.

You can use the RequestDispatcher # forward method to forward processing to another Servlet or JSP.

This time, when a request comes to / HelloServlet, it is forwarded to WEB-INF / view / index.jsp.

HelloServlet.java



/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	// TODO Auto-generated method stub

	String view = "/WEB-INF/view/index.jsp";
	RequestDispatcher dispatcher = request.getRequestDispatcher(view);

	dispatcher.forward(request, response);
}

View server view and restart tomcat

Tomcat will be restarted for the Servlet changes to take effect.

Go to http: // localhost: 8080 / TodoServlet / HelloServlet in your browser and verify that you can see the contents of ʻindex.jsp`.

Source code so far: Kazunori-Kimura / todo-servlet at v2.0.0

Pass values from Servlet to JSP

Use the HttpServletRequest # setAttribute method to pass a value from Servlet to JSP.

Set the key in the first argument and the value in the second argument.

HelloServlet.java


/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	//Pass an appropriate string to JSP
	request.setAttribute("foo", "bar");

	//Forward to JSP
	String view = "/WEB-INF/view/index.jsp";
	RequestDispatcher dispatcher = request.getRequestDispatcher(view);

	dispatcher.forward(request, response);
}

The value setAttribute in Servlet can be obtained by the request.getAttribute method of JSP.

The request object is available in the JSP without any special declaration.

index.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Hello, World!</title>
</head>
<body>
	<%= request.getAttribute("foo") %>
</body>
</html>

Source code so far: Kazunori-Kimura / todo-servlet at v2.1.0

Reference: EL expression

Abbreviation for * Expression Language *. The expression is evaluated and output by writing $ {...}.

Click here for detailed explanation> [For beginners] EL formula --Qiita

In the EL expression, you can get the value by omitting the description of request.getAttribute.

index.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Hello, World!</title>
</head>
<body>
	${foo}
</body>
</html>

Pass values from JSP to Servlet

Let's place a text box in JSP and receive the entered value in Servlet.

Use the form and ʻinput` tags to accept some input from the user in JSP.

index.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Hello, World!</title>
</head>
<body>
	<%= request.getAttribute("foo") %>

	<form method="post" action="./HelloServlet">
Enter something: <input type="text" name="hoge">
		<button type="submit">Send</button>
	</form>
</body>
</html>

Specifies which HTTP method to use when the submit button is pressed in the method attribute of the form tag. You will be using get or post.

The ʻaction` attribute specifies the destination URL. It is better to specify the path relative to the URL currently displayed in the browser. If you specify an absolute path, it will be difficult to handle cases such as when the URL differs between the production environment and the development environment.

Since the get method is used when there is a request from the browser, use the post method to receive data from the form.

Display a text box using the ʻinput` tag.

If the type attribute of the button tag is submit, the form tag is used in the HTTP method specified by the method attribute for the URL specified in the action attribute of the form when the button is clicked. Sends the value of each element in.

HelloServlet.java


/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	//Get value from form
	String value = request.getParameter("hoge");
	System.out.println(value);

	doGet(request, response);
}

When the user clicks the button, the process moves to the doPost method.

The value entered in form can be obtained with the HttpServletRequest # getParameter method. In the argument, specify the name attribute of the ʻinput` tag.

This time, I get the value of name =" hoge ", output it to the console, and then execute the doGet method.

Source code so far: Kazunori-Kimura / todo-servlet at v2.2.0

JSP -> Servlet -> JSP

Let's implement a Web application-like behavior by combining the cooperation from JSP to Servlet and the cooperation from Servlet to JSP.

  1. If there is access GET "Hello, Guest-san!" To display the message, the name input form
  2. Enter the name and click the submit button to POST the input to Servlet.
  3. Replace "Guest" with the POSTed name to hide the form

Preparation of name input form

First prepare the message and the name input form of "Hello".

index.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Hello, World!</title>
</head>
<body>
Hello,<%= request.getAttribute("userName") %>San!

	<form method="post" action="./Hello">
Please enter your name: <input type="text" name="name">
		<button type="submit">Send</button>
	</form>
</body>
</html>

Variable initialization at first access

Since we want to display "Guest" when accessing with GET for the first time, set "Guest" to ʻuserName`.

HelloServlet.java


/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	request.setAttribute("userName", "Guest");

	String view = "/WEB-INF/view/index.jsp";
	RequestDispatcher dispatcher = request.getRequestDispatcher(view);
	dispatcher.forward(request, response);
}

Receive input data

Receives the name entered in the form and updates ʻuserName`.

When dealing with languages such as Japanese, Chinese, and Korean (called CJK from the acronym of Chinese, Japanese, Korean, or CJKV by adding Vietnamese), the characters will be garbled if the character code is not specified properly. Please note that it will occur.

HelloServlet.java


/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	//Character code specification
	request.setCharacterEncoding("utf-8");
	//Get value from form
	String name = request.getParameter("name");

	request.setAttribute("userName", name);

	doGet(request, response);
}

Display of input data

ʻSet "Guest" only if userNameisnull` or empty.

HelloServlet.java


/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String name = (String) request.getAttribute("userName");
	
	if (name == null || "".equals(name)) {
		request.setAttribute("userName", "Guest");
	}
	
	String view = "/WEB-INF/view/index.jsp";
	RequestDispatcher dispatcher = request.getRequestDispatcher(view);
	dispatcher.forward(request, response);
}

Hide input form

Once you enter your name, you don't need an input form and hide it. ʻThe input form should be displayed only when userName` is "Guest".

index.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Hello, World!</title>
</head>
<body>
	<% String userName = (String) request.getAttribute("userName"); %>
Hello,<%= userName %>San!

	<% if ("Guest".equals(userName)) { %>
	<form method="post" action="./HelloServlet">
Please enter your name: <input type="text" name="name">
		<button type="submit">Send</button>
	</form>
	<% } %>
</body>
</html>

Operation check

1 2
Screenshot 2017-06-27 10.19.16.png Screenshot2017-06-2710.19.31.png

Source code so far: Kazunori-Kimura / todo-servlet at v2.3.0

Cross-site scripting (XSS) vulnerabilities

In fact, the web application we just created is vulnerable to cross-site scripting (XSS). XSS is * embedding a malicious script in someone else's website *.

Actually enter <script> alert ("stupid "); </ script> in the name form.

For Google Chrome, the error screen ʻERR_BLOCKED_BY_XSS_AUDITOR` is displayed as shown below.

スクリーンショット 2017-06-27 10.29.59.png

Depending on your browser, the script will not be blocked and you will see a dialog called stupid.

How to avoid XSS

The cause of XSS is that the data entered by the user is output to HTML as it is. An effective XSS countermeasure is to prevent characters such as < and > from being recognized as tags. This kind of processing is called * escape *.

Escape functions are provided as standard in PHP and JavaScript, but Java (JSP) does not. You can make your own, but it is possible that bugs will be mixed in, so it is better to introduce a proven library.

Also, some people may consider a method of checking the input and not inputting characters such as < and >, but it is not a good method for XSS countermeasures. Input check is easy with a simple form like this one, but it is difficult to implement and test to perform input check without omission in a complicated Web application. It would also be difficult to ensure that there is absolutely no way to bypass the input check. After all, as an XSS countermeasure, it is easy and reliable to escape at the time of output.

Introduction of taglib

JSP has a mechanism called tag library. Encapsulating JSP processing can improve the visibility of JSP and improve the reusability of functions.

procedure image
Apache Tomcat® - Apache Taglibs DownloadsDownloadthefourjarfilesfrom. Screenshot2017-06-2710.49.17.png
Eclipse/WebContent/WEB-INF/libDrag the 4 jars you downloaded to&Drop it. A confirmation message will be displayed.Copy fileSelectOKClick. Screenshot 2017-06-27 10.52.45.png
libMake sure the file exists in the folder. Screenshot 2017-06-27 10.53.02.png

Modify index.jsp

JSTL is being read with the <% @ taglib%> directive. The output part has been changed from <% =%> to the <c: out> tag. The <c: out> tag escapes by default.

Reference: JSTL reference: <c: out>

index.jsp


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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>Hello, World!</title>
</head>
<body>
	<% String userName = (String) request.getAttribute("userName"); %>
Hello,<c:out value="${userName}" />San!

	<% if ("Guest".equals(userName)) { %>
	<form method="post" action="./HelloServlet">
Please enter your name: <input type="text" name="name">
		<button type="submit">Send</button>
	</form>
	<% } %>
</body>
</html>

Operation check

1 2
Screenshot 2017-06-27 11.02.14.png Screenshot2017-06-2711.02.23.png

Source code so far: Kazunori-Kimura / todo-servlet at v2.4.0

reference


We checked the operation of Servlet and JSP, and covered how to link Servlet <-> JSP with a very simple Web application. Also, the XSS countermeasures introduced at the end are very important, so always be careful when creating a web application.

Recommended Posts

Getting Started with JSP & Servlet
Getting Started with Ruby
Getting Started with Swift
Getting Started with Docker
Getting Started with Doma-Transactions
Getting Started with Doma-Annotation Processing
Getting Started with Java Collection
Getting Started with Java Basics
Getting Started with Spring Boot
Getting Started with Ruby Modules
Getting Started with Java_Chapter 5_Practice Exercises 5_4
Passing parameters from JSP with Servlet
[Google Cloud] Getting Started with Docker
Hello World with GlassFish 5.1 + Servlet + JSP
Getting started with Java lambda expressions
Getting Started with Docker with VS Code
Getting Started with Doma-Criteria API Cheat Sheet
Getting Started with Ruby for Java Engineers
Getting Started with Docker for Mac (Installation)
Getting Started with Parameterization Testing in JUnit
Getting Started with Java Starting from 0 Part 1
Getting started with the JVM's GC mechanism
Getting Started with Language Server Protocol with LSP4J
Getting Started with Creating Resource Bundles with ListResoueceBundle
Getting Started with Java_Chapter 8_About Instances and Classes
Getting Started with Doma-Using Projection with the Criteira API
Getting Started with Doma-Using Subqueries with the Criteria API
Getting Started with Java 1 Putting together similar things
Getting started with Kotlin to send to Java developers
Getting Started with Doma-Using Joins with the Criteira API
Getting Started with Doma-Introduction to the Criteria API
I tried Getting Started with Gradle on Heroku
About [servlet] [JSP] [tomcat]
Get started with Gradle
Getting started with Java programs using Visual Studio Code
Getting Started with Legacy Java Engineers (Stream + Lambda Expression)
Web application development memo with MVN, Tomcat, JSP / Servlet with VScode
Getting Started with Reactive Streams and the JDK 9 Flow API
Get started with Spring boot
Java Servlet / JSP View drawing
Get started with DynamoDB with docker
JSP error display from Servlet
Until you create a Web application with Servlet / JSP (Part 1)
Completable Future Getting Started (First Future)
Getting Started with GitHub Container Registry instead of Docker Hub
Comparison of WEB application development with Rails and Java Servlet + JSP
Create a memo app with Tomcat + JSP + Servlet + MySQL using Eclipse
Summarize the main points of getting started with JPA learned with Hibernate
Getting started with Swift / C bridges with porting Echo Server using libuv
[Introduction to JSP + Servlet] I played with it for a while ♬
Let's get started with parallel programming
How to use scope (JSP & Servlet)
Java Servlet / JSP Request Scope Part 1
How to get started with slim
Java Servlet / JSP Request Scope Part 2
About image upload of jsp (servlet)
CompletableFuture Getting Started 2 (Try to make CompletableFuture)
Message cooperation started with Spring Boot
Getting Started with Micronaut 2.x ~ Native Build and Deploy to AWS Lambda ~
Getting Started with Machine Learning with Spark "Price Estimate" # 1 Loading Datasets with Apache Spark (Java)