[Java Servlet] The road of Senri is also the fourth step from the first step


Finally last time login.jsp → LoginServlet.java → mypage.jsp You can now make transitions. By the way, the URL at the time of mypage transition is http://localhost:8080/ServletApp/mypage.jsp However, if you are concerned about the last extension, go to web.xml



If you add, the URL at the time of transition will be http://localhost:8080/ServletApp/mypage Will be.

Other data transfer methods

Actually, there are other methods called "cookies" and "sessions" for passing data between Servlets, in addition to the method using the request.getParameter () method that was done last time.

Let's make cookies

A cookie is information stored on the client side when a response is returned from the server. (If you often browse the site, you may see pop-ups such as "This site uses cookies".) servlet17.png As a merit of saving data on the client side,

--Membership site → Omit user name input from next time --Shopping site → Remember the items you have added to your cart

And so on. Let's make cookies. First, modify the doPost () method of LoginServlet.java.


protected void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
	String name=req.getParameter("name");
	Cookie c[]=req.getCookies();
	boolean CreatedCookie=false;
	for(Cookie cookie:c) {
		if(cookie.getName().equals("cookie_user")) {
	if(CreatedCookie==false) {
		Cookie cookie=new Cookie("cookie_user",name);
//		if(Arrays.stream(c)
//			.filter(e->!e.getName().equals("cookie_user"))
//			.count()==c.length) {
//		Cookie cookie=new Cookie("cookie_user",name);
//		res.addCookie(cookie);
//	}

--req.getCookies () ・ ・ ・ Get the cookies that the client has in an array (5th line) --cookie.getName () ・ ・ ・ Get the name of the cookie (8th line) --new Cookie (String name, String value) ・ ・ ・ Create a cookie with a pair of name: value (line 13) --res.addCookie (Cookie cookie)` ・ ・ ・ Set cookie as response (line 14)

This allows you to save the username you entered at login as cookie_user. Also, although it does not appear here,

--cookie.setMaxAge (int seconds) ・ ・ ・ Specify the expiration date of the cookie in seconds (when the expiration date expires, the cookie will be destroyed) --cookie.setValue (String value) ・ ・ ・ Reset the value to the cookie

And so on. Next, modify the inside of the <body> tag of login.jsp.


	Cookie cookies[]=request.getCookies();
	String username="";
	for(Cookie c:cookies){
<form action="/ServletApp/mypage" method="post">
name:<input type="text" name="name" value=<%=username%>><br>
password:<input type="text" name="password"><br>
<input type="submit" value="login">

If the cookie name cookie_user already exists when the login screen is displayed, the value will be entered in the text field.

Let's use cookies

Now access login.jsp. servlet19.png Enter "hato" in name to log in. servlet21.png At first glance it looks like nothing has changed, but let's access login.jsp again. servlet22.png You can see that the "hato" that was already entered is already entered in name.

Let's check cookies

I said "information stored on the client side" in [Let's make cookies](# Let's make cookies), but there is a way to check the cookies stored in Google Chrome.

  1. With login.jsp open, press the F12 key to open "Developer Tools".

  2. Click the ʻApplication` tab in the menu. 2020-06-07.png

  3. Click Cookies. 2020-06-07 (1).png

  4. Click http: // localhost: 8080. 2020-06-07 (2).png accomplished. In Name, cookie_user, which is the name of the cookie created earlier, is displayed, and "Hato", which is the user name entered in Value, is displayed. You can also rewrite or delete the value on this screen.

Let's make a session

A session refers to a series of processes from the start to the end (or discard) of a connection, such as "from login to logout" or "after login to leaving it to time out". However, since a normal Web page does not have a function to pass the "connected state", it will be treated as a different connection every time you access the server as shown below. servlet24.png

Let's make this connection A to C a series of processes (sessions).

Add the following code to LoginServlet.java.


HttpSession session=req.getSession();
Date date=new Date(session.getCreationTime());
SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
session.setAttribute("lastLoginDate", sdf.format(date));

Code that saves the session start time with the name lastLoginDate.

--req.getSession () ・ ・ ・ Get session --session.getCreationTime () ・ ・ ・ Get the date and time when the session was first created as a long type --session.setAttribute (String name, Object value) ・ ・ ・ Name: Value pair stores parameters --session.setMaxInactiveInterval (int s) ・ ・ ・ Specify the session expiration date with seconds (default should be 1800 seconds)

Also modify mypage.jsp.


    String name=request.getParameter("name");
    String session_date=session.getAttribute("lastLoginDate").toString();
<%=name%>Login date and time<%=session_date%>is.

--session.getAttribute (String name) ・ ・ ・ Get the value corresponding to the name specified by the argument from within the session with ʻObject type`

Also, I will not use it this time

--session.getAttributeNames () ・ ・ ・ Get the parameter names stored in the session as a String type array`` --session.lastAccessedTime ()` ・ ・ ・ Get the last connected time in the session

And so on.

Let's use the session

Now access login.jsp again. Enter "Hato" to log in. servlet26.png I think that the current time is roughly displayed. Then, refresh the page with the F5 key without a break (do not do it on the real input form or product page) servlet26.png The time does not change. The 20 seconds you set the expiration date earlier are considered "same connection". Then reload after a while. servlet27.png

Since a session is also a type of cookie, you can check the session in the same way as [Let's check cookies](#Let's check cookies). However, it is a difficult character string so that it cannot be modified as much as possible.

That's all for this time. I wonder if I can put it in the framework soon ...

Recommended Posts

[Java Servlet] The road of Senri is also the fourth step from the first step
[Java Servlet] The road of Senri is also the fifth step from the first step
[Java Servlet] The road of Senri is also the third step from the first step
[Java Servlet] The road of Senri is also one step to the first
The road from JavaScript to Java
From Java9, the constructor of the class corresponding to primitive types is deprecated.
[Promotion of Ruby comprehension (1)] When switching from Java to Ruby, first understand the difference.
What is the Java Servlet / JSP MVC model?
The order of Java method modifiers is fixed
The story of learning Java in the first programming
[Java] Calculate the day of the week from the date (Calendar class is not used)
First touch of the Files class (or Java 8)
How to write Scala from the perspective of Java
Java language from the perspective of Kotlin and C #
The story that .java is also built in Unity 2018
Get to the abbreviations from 5 examples of iterating Java lists
Java: The problem of which is faster, stream or loop
Road to Java Engineer Part2 What kind of language is Java?
[Java] Delete the specified number of characters from the end of StringBuilder
[Java beginner] Conversion from character string to numerical value-What is the parseInt method of the Integer class? ~
[Java] Beginner's understanding of Servlet-②
[Java] Beginner's understanding of Servlet-①
This is the first post.
Java is the 5th day
The milliseconds to set in /lib/calendars.properties of Java jre is UTC
Read the first 4 bytes of the Java class file and output CAFEBABE
From fledgling Java (3 years) to Node.js (4 years). And the impression of returning to Java
[Swift] The color of the Navigation Bar is different (lighter) from the specified color.
Is the version of Elasticsearch you are using compatible with Java 11?
Investigation method when the CPU of the server running java is heavy
Let's summarize the Java 8 grammar from the perspective of an iOS engineer