[Java] [Java Servlet] One step from Senri Road to the fourth step

4 minute read

Progress

Finally at the last time login.jsp → LoginServlet.java → mypage.jsp You can now transition. By the way, the URL when transitioning to mypage is http://localhost:8080/ServletApp/mypage.jsp However, if you care about the last extension, add it to web.xml.

web.xml


<servlet>
<servlet-name>mypage</servlet-name>
<jsp-file>/mypage.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>mypage</servlet-name>
<url-pattern>/ServletApp/mypage</url-pattern>
</servlet-mapping>

If you add http://localhost:8080/ServletApp/mypage Will be.

How to pass other data

Actually, there is something called “cookie” and “session” for passing data between servlets, in addition to using the request.getParameter() method that I did last time.

Let’smakecookies

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

  • Membership site → Omission of user name input from next time
  • Shopping site → Remember the products in your cart

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

LoginServlet.java


protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String name=req.getParameter("name");
Cookie c[]=req.getCookies();
boolean CreatedCookie=false;
for(Cookie cookie:c) {
if(cookie.getName().equals("cookie_user")) {
CreatedCookie=true;
}
}
if(CreatedCookie==false) {
Cookie cookie=new Cookie("cookie_user",name);
res.addCookie(cookie);
}
// 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.setAttribute("name",name);
req.getRequestDispatcher("/mypage.jsp").forward(req,res);
}
  • Lines 6 to 15 and the comment-out line are almost the same, only the writing method is different. Please use it according to your preference.

  • req.getCookies() ・・・ Get the cookies that the client has as an array (5th line)
  • cookie.getName() ・・・ Get the cookie name (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 (14th line)

This allows you to save the username you entered when you logged in as cookie_user. Also, although it does not appear here,

  • cookie.setMaxAge(int seconds) ・・・Specifies the expiration date of the cookie in seconds (when the expiration date expires, the cookie is destroyed)
  • cookie.setValue(String value) ・・・Reset value to cookie

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

login.jsp


<body>
<%
Cookie cookies[]=request.getCookies();
String username="";
for(Cookie c:cookies){
if(c.getName().equals("cookie_user")) username=c.getValue();
}
%>
<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">
</form>
</body>

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

Let’s use cookies

Now access login.jsp. servlet19.png Enter “hato” as the “name” to log in. servlet21.png It doesn’t seem to change at first, but let’s access login.jsp again. servlet22.png You can see that the “hato” that you have already entered is already entered in name.

Lookupcookies

Let’s make cookies said “information stored on the client side”, but there is a way to check the cookies stored in Google Chrome.

  1. With login.jsp open, press the F12 key to open the “Developer Tools”.
  2. Click the Application tab in the menu. 2020-06-07.png

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

Let’s make a session

A session is a series of processes from the start to the end (or discard) of a connection, such as “from login to logout” or “after login and timeout”. However, since a normal web page does not have a function to pass the “connected state”, it is treated as a different connection each time you access the server as follows. servlet24.png

Let’s make this connection A to connection C into a series of processing (session).

Add the following code to LoginServlet.java.

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));
session.setMaxInactiveInterval(20);

Code to save the session start time with the name lastLoginDate.

  • req.getSession() ・・・ Get session
  • session.getCreationTime() ・・・ Gets the date and time when the session was created for the first time as a long type-session.setAttribute(String name,Object value) ・・・ Parameters are stored as a name:value pair
  • session.setMaxInactiveInterval(int s) ・・・ Specify the session expiration time in seconds (default should be 1800 seconds)

I will also modify mypage.jsp.

mypage.jsp


<body>
<%
    String name=request.getParameter("name");
    String session_date=session.getAttribute("lastLoginDate").toString();
%>
<%=name%>'s login date is <%=session_date%>.
</body>
  • session.getAttribute(String name) ・・・ Get the value corresponding to the name specified in the argument as Object type from within the session

Also, I will not use this time,

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

And so on.

Let’s use session

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

The session is also a type of cookie, so you can check the session in the same way as Look up cookie. However, it is a difficult character string that cannot be modified as much as possible.

That’s it for this time. I wonder if it will be added to the framework soon.

Tags:

Updated: