[JAVA] [Introduction to JSP + Servlet] I played with it for a while ♬

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

What i did

・ Installation of eclipse ・ Make a simple one ・ Supports Japanese input ・ Image display ・ Add code

・ Installation of eclipse

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

・ Make a simple one

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.

I will start it

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.

-Try to create Jsp-Servlet

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. package_exp.jpg 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.

・ Supports Japanese input

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.

-Pass information from HelloSample to JSP

"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

Next, pass an appropriate character string from HelloSample.java to index.jsp and display it.

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.

Make the delivery a little more complicated

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);
	}

Next, the linked application called JSP-Servlet-JSP is as follows

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.

On the other hand, in the case of the above code, Japanese is also displayed properly.

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);

・ Image display

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

Add image files to your project

-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.

Display on JSP

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>

image_draw_in_jsp.jpg I'd like to pass images after this, but. .. .. I was still lacking in power.

Summary

・ I played with JSP + Servlet ・ I was able to display Japanese and images

-Free images. .. .. I want to try object motion drawing

I put the code below

-JSP-Servlet / HelloSample.java -JSP-Servlet / index.jsp

Recommended Posts

[Introduction to JSP + Servlet] I played with it for a while ♬
[Introduction to JSP + Servlet] A little animation ♬
I tried to break a block with java (1)
[Go To Travel] I searched for a plan with a quo card in Jalan
[Java] I tried to connect using a connection pool with Servlet (tomcat) & MySQL & Java
When I tried to use a Wacom tablet with ubuntu 20.04, I didn't recognize it.
I made a method to ask for Premium Friday
I want to monitor a specific file with WatchService
I played with Refinements
Introduction to Programming for College Students: Making a Canvas
[Azure] I tried to create a Java application for free ~ Connect with FTP ~ [Beginner]
roman numerals (I tried to simplify it with hash)
I want to create a generic annotation for a type
I want to implement it additionally while using kotlin on a site running Java
Implemented a strong API for "I want to display ~~ on the screen" with simple CQRS
I tried to make an introduction to PHP + MySQL with Docker
I tried to create a java8 development environment with Chocolatey
Tutorial to create a blog with Rails for beginners Part 1
I tried to modernize a Java EE application with OpenShift.
[Rails] I tried to create a mini app with FullCalendar
I made a plugin to execute jextract with Gradle task
I was addicted to setting default_url_options with Rails devise introduction
I searched for a web framework with Gem in Ruby
Until you create a Web application with Servlet / JSP (Part 1)
Tutorial to create a blog with Rails for beginners Part 2
I tried to create a padrino development environment with Docker
Tutorial to create a blog with Rails for beginners Part 0
Introduction to Programming for College Students: Draw a Straight Line
Getting Started with JSP & Servlet
How to deal with the type that I thought about writing a Java program for 2 years
A story that I struggled to challenge a competition professional with Java
I want to create a chat screen for the Swift chat app!
I want to make a button with a line break with link_to [Note]
Create a memo app with Tomcat + JSP + Servlet + MySQL using Eclipse
I made a method to ask for Premium Friday (Java 8 version)
I tried to build a laravel operating environment while remembering Docker
I want to extract between character strings with a regular expression
I tried to make a group function (bulletin board) with Rails
[For beginners] I want to automatically enter pre-registered data in the input form with a selection command.
I want to create a Servlet war file with OpenJDK on CentOS7. Without mvn. With no internet connection.
A story that I wanted to write a process equivalent to a while statement with the Stream API of Java8
I want to download a file on the Internet using Ruby and save it locally (with caution)
I made a GUI with Swing
Passing parameters from JSP with Servlet
Introduction to algorithms with java-Shakutori method
I tried to interact with Java
Introduction to Programming for College Students: Introduction
I made an app to scribble with PencilKit on a PDF file
[Java] How to turn a two-dimensional array with an extended for statement
I want to select multiple items with a custom layout in Dialog
Even in Java, I want to output true with a == 1 && a == 2 && a == 3 (PowerMockito edition)
I want to summarize Apache Wicket 8 because it is a good idea
[iOS] I tried to make a processing application like Instagram with Swift
I thought about how to make it serverless while avoiding vendor lock-in
I tried to make a Web API that connects to DB with Quarkus
I tried to build a Firebase application development environment with Docker in 2020
I want to create a dark web SNS with Jakarta EE 8 with Java 11
It was a life I wanted to reset the thread-safe associative counter
I wanted to implement a slide show in a fashionable way with slick.
Create a program to post to Slack with GO and make it a container
I want to display a PDF in Chinese (Korean) with thin reports