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)
Package Explorer
and select New
-> Project ...
Web
-> Dynamic Web Project
and click Next>
Finish
--Project name: TodoServlet
--Target runtime: Tomcat8 (Java8)
1 | 2 | 3 |
---|---|---|
First, create a very simple Servlet to check the operation.
src
in Package Explorer
and select New
->Other ...
Web
-> Servlet
and click Next>
Finish
--Java package: todo.controller
--Class name: HelloServlet
Package Explorer
, right-click TodoServlet
and click Run
-> Run on Server
.Tomcat v8.0 Server
and click Done
--The startup log of Tomcat
is output to the console, and after a while, the built-in browser of Eclipse is displayed.
--The page HTTP Status 404-/ TodoServlet /
is displayed.http: // localhost: 8080 / TodoServlet / HelloServlet
and press Enter.
--If the page Served at: / TodoServlet
is displayed, Servlet has been executed normally.1 | 2 | 3 |
---|---|---|
Next, check the operation of JSP.
WebContent
in Package Explorer
and select New
->Other ...
Web
-> JSP File
and click Next>
Finish
--File name: index.jsp<title>
--Added code to output date and time to <body>
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.
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.
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.
First, simply receive the request with Servlet and implement it to return the contents of JSP.
Move ʻindex.jsp under
WEB-INFso that the JSP is not accessed directly. In the future, we will create a
WEB-INF / view` folder and place the JSP files under it so that it will be easier to manage when there are multiple JSP files.
WebContent / WEB-INF
in Package Explorer
and select New
-> Folder
Finish
--Folder name: view
WebContent / index.jsp
in Package Explorer
and select Refactoring
-> Move
WebContent / WEB-INF / view
and click ʻOK`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);
}
Window
-> Show View
-> Other
Server
and click ʻOK`Server
tab will be displayed. Click(▶)
.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
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
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>
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.
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>
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);
}
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);
}
without any questions. If nothing is done, the value set in
doPost` will be overwritten by" Guest ", so let's fix it.ʻSet "Guest" only if userNameis
null` 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);
}
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>
1 | 2 |
---|---|
Source code so far: Kazunori-Kimura / todo-servlet at v2.3.0
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.
Depending on your browser, the script will not be blocked and you will see a dialog called stupid
.
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.
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. | |
Eclipse/WebContent/WEB-INF/lib Drag the 4 jars you downloaded to&Drop it. A confirmation message will be displayed.Copy file SelectOK Click. |
|
lib Make sure the file exists in the folder. |
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>
1 | 2 |
---|---|
Source code so far: Kazunori-Kimura / todo-servlet at v2.4.0
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