I'm a complete beginner, so I may write something sloppy, but please forgive me. This time I decided to try JSP + Servlet for a while, so I will summarize what I learned in a simple way. I will create it almost as a reference and write the story from there. 【reference】 ① Introduction to JSP & Servlet
・ Installation of eclipse ・ Make a simple one ・ Supports Japanese input ・ Image display ・ Add code
There is a recent version, but the reference [https://ftp.jaist.ac.jp/pub/mergedoc/pleiades/4.6/pleiades-4.6.3-java-win-64bit-jre_20170422.zip](https: / /mergedoc.osdn.jp/index.html#/pleiades_distros4.6.html) was installed on Windows 10 as explained. (The numbers below are quoted from the above reference) ① Create a folder such as C: \ app ② Move the downloaded zip file ③ Change the file name to pleiades-4.6.3.zip ④ Extract the ZIP file ⑤ Move pleiades in the expanded folder to C: \ app -Double-click eclipse.exe in the directory under \ app \ pleiades \ eclipse to start it. Workspace is OK by default at startup -Pin to the taskbar. Right click and click "Pin to taskbar" 【reference】 ・ Ultra-basic usage of Eclipse
Let's make the simplest of the above reference ①. Now you can see the directory structure and how to move it. ① When you start eclipse, the package X-prowler is on the upper left. Right-clicking in this area (inside the square) ... transitions in the order in (), -Create a dynamic web project (right-click-new-other-dynamic web project-next) ・ Project name; sampleWeb -Target runtime; Tomcat8 (Java8) You can create a sampleWeb project by typing. ② Now right-click on src (New-Other-Servlet-Next) -Java package; sample.controller ・クラス名;HelloSample.java You can create a servlet; sample.controller by typing. This seems to be the simplest servlet.
Right-click sampleWeb-Run-1 Click Run on Server. .. .. URL;http://localhost:8080/sampleWeb/HelloSample You can see that the following is executed in. In a normal browser, it worked even if I assigned the above URL and returned.
Served at: /sampleWeb
The code is as follows It's a skeleton, but it works.
HelloSample.py
package sample.controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Next, there is an annotation that says @WebServlet ("/ HelloSample"). At the same time as the comment, it seems to inform the system of the mapping of WebServlet ("/ HelloSample"). It is quoted from Reference ②. "Annotations are not part of a program, but they provide information about the program. In Servlet programming, annotations can be used to declare mapping information between URL paths and Servlets. The latest version of Java EE allows you to use annotations without using web.xml for mapping. You can choose to use web.xml or annotations. "
【reference】 ② [Java & Tomcat] Web application settings (annotation) * With sample program
/**
* Servlet implementation class HelloSample
*/
@WebServlet("/HelloSample")
public class HelloSample extends HttpServlet {
private static final long serialVersionUID = 1L;
And in the constructor, this will be the first thing to do when you start it. I don't seem to be doing anything.
/**
* @see HttpServlet#HttpServlet()
*/
public HelloSample() {
super();
// TODO Auto-generated constructor stub
}
Next is doGet. This is (request, response) and it interacts with something.
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
Then there was doPost. This also exchanges something with (request, response). Isn't it the same? ?? The only function written is doGet (), which is called (executed).
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
In other words, this Servlet starts, doGet works,
response.getWriter().append("Served at: ").append(request.getContextPath());
Has moved.
After all, if you do not make Jsp, it goes against the title, so I will make it. This is also all as shown in Reference ① above. -Create index.jsp (Right-click WebContent-New-Other-jsp file File name; index.jsp Enter and complete You have now created index.jsp directly under WebContent. The code is as follows <% = New java.util.Date ()%> that displays the time is added to the body. In addition, Title is Hello, World.
.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>
Now let's move it in the same way as before. The following is http://localhost:8080/sampleWeb/ It was output to.
Wed Apr 22 21:55:03 JST 2020
The directory structure is as follows. I don't really understand how it works, but ... Apparently each one is working on its own, http: // localhost: 8080 / sampleWeb / It seems that index.jsp is called and the time is displayed. On the other hand, at http: // localhost: 8080 / sampleWeb / HelloSample, Served at: / sampleWeb is displayed. It doesn't seem to be the title unless we interact with each other.
First, in order to exchange between jsp-servelets, move index.jsp under WEB-INF so that it cannot be seen from the outside. -Create a view folder under WEB-INF (right-click WEB-INF-New-Folder Next and enter view-Done), drag index.jsp there, and drop it to move it.
"When a client (browser) makes a request to HelloSample, the doGet method is executed." So, write the following in doGet of HelloSample.java.
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String view = "/WEB-INF/view/index.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(view);
dispatcher.forward(request, response);
}
Now that HelloSample.java has been rewritten, restart the server. Reference ① above is from the window. .. However, here you can re-execute by right-clicking sampleWeb-execution-1 execution on the server-complete. Now, the following message will be displayed, but the restart is successful. In fact, http: // localhost: 8080 / sampleWeb / HelloSample If you put in the url and return, the last time will be displayed, and you can see that index.jsp was called and displayed.
HTTP status 404- /sampleWeb/
type status report
message/sampleWeb/
Description The requested resource is not available.
Apache Tomcat/8.0.43
Add the following code to the above doGet.
//Pass an appropriate string to JSP
request.setAttribute("foo", "bar");
And index.jsp is received as follows.
.jsp
<%= request.getAttribute("foo") %>
As a result, restart the server as above, http://localhost:8080/sampleWeb/HelloSample If you look at the browser, you can see that the following is displayed. Thu Apr 23 17:35:06 JST 2020 bar In other words, since it is placed behind, the bar is displayed after the time.
First, describe the receiving index.jsp as follows.
When <body>
is described, it is as follows.
I'm leaving the additions so far.
.jsp
<body>
<%= new java.util.Date() %>
<%= request.getAttribute("foo") %>
<form method="post" action="./HelloSample">
Enter something: <input type="text" name="hoge">
<button type="submit">Send</button>
</form>
</body>
Next, the recipient receives it with doPost of HelloSample.java this time. request.getPasrameter("hoge"); Get the value with, assign it to value, and output it to the standard output.
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);
}
If you write as much as possible without erasing the code so far,
.jsp
<body>
<%= new java.util.Date() %>
<%= request.getAttribute("foo") %><br/>
<%= request.getAttribute("userName") %>
<form method="post" action="./HelloSample">
Enter something: <input type="text" name="name">
<button type="submit">Send</button>
</form>
</body>
On the Servlet side, doPost of HelloSample.java is rewritten as follows
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Character code specification
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
request.setAttribute("userName", name);
System.out.println(name);
doGet(request, response);
}
In addition, doGet is:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Pass an appropriate string to JSP
request.setAttribute("foo", "bar");
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);
}
First, run Servlet; HelloSample.java on one server. And if you look at the following url in your browser http://localhost:8080/sampleWeb/
HTTP status 404- /sampleWeb/
type status report
message/sampleWeb/
Description The requested resource is not available.
Apache Tomcat/8.0.43
And http://localhost:8080/sampleWeb/HelloSample The following image appears.
Thu Apr 23 21:35:55 JST 2020 bar
Guest
Enter something:Send
If you enter the following and press send,
Thu Apr 23 21:35:55 JST 2020 bar
Guest
Enter something:MuAuan transmission
Guest changed to MuAuan as below,
Thu Apr 23 21:35:55 JST 2020 bar
MuAuan
Enter something:Send
MuAuan is output to the standard output. So you can see that JSP-Servlet-JSP and MuAuan were passed.
Muuwan was also displayed safely. This is because the character code is specified by the following code. If you try to remove this, garbled characters will occur.
//Character code specification
request.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
request.setAttribute("userName", name);
You can also eliminate garbled characters with the following code. However, according to the reference, the following seems to be the old code that is not recommended as it can be done with the above code now. 【reference】 -JSP / Servlet parameter passing is garbled and does not work.
String name = new String(request.getParameter("name").getBytes("ISO-8859-1"), "UTF-8");
request.setAttribute("userName", name);
Next, I'd like to display an image because it's dull. However, there is no example. So I managed to do it ... I'd like to read the whole reference. 【reference】 ・ Insert image into jsp page
-Right-click WebContent-New-Folder Folder name; Add image storage folder called media when completed with media ・ Add the image files you want to display in this folder. Right-click media-New-File-Extended-Check link to file in file system-Reference-Click image file-Open-Done Then, one image file will be added to the folder.
Finally
<img src="${pageContext.request.contextPath}/media/image.png " alt="Tokyo">
Then, the image file was displayed.
<body>
<%= new java.util.Date() %>
<%= request.getAttribute("foo") %><br/>
<%= request.getAttribute("userName") %>
<form method="post" action="./HelloSample">
Enter something: <input type="text" name="name">
<button type="submit">Send</button>
</form>
<br/>
<img src="${pageContext.request.contextPath}/media/image.png " alt="Tokyo">
</body>
I'd like to pass images after this, but. .. .. I was still lacking in power.
・ I played with JSP + Servlet ・ I was able to display Japanese and images
-Free images. .. .. I want to try object motion drawing
-JSP-Servlet / HelloSample.java -JSP-Servlet / index.jsp
Recommended Posts