#03:リクエストスコープ
このチャプターでは、リクエストスコープについて学習します。
【import】import java.util.*;
import java.time.*;
import java.time.format.*;
【本日の日付の取得】String today = LocalDate.now().format(
DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.JAPAN));
【LoginServlet.java】package jp.paiza.servlet;
import java.io.*;
import java.util.*;
import java.time.*;
import java.time.format.*;
import jakarta.servlet.*;
import jakarta.servlet.annotation.*;
import jakarta.servlet.http.*;
import jp.paiza.model.*;
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String today = LocalDate.now().format(
DateTimeFormatter
.ofLocalizedDate(FormatStyle.SHORT)
.withLocale(Locale.JAPAN));
req.setAttribute("today", today);
System.out.println(req.getAttribute("today"));
RequestDispatcher d =
req.getRequestDispatcher("/WEB-INF/jsp/login-input.jsp");
d.forward(req, res);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String userId = req.getParameter("user-id");
String password = req.getParameter("password");
LoginModel m = new LoginModel();
if (m.login(userId, password)) {
RequestDispatcher d =
req.getRequestDispatcher("/WEB-INF/jsp/login-result.jsp");
d.forward(req, res);
} else {
res.sendRedirect("login");
}
}
}
【login-input.jsp】<%@ page contentType="text/html; charset=UTF-8" %>
<%
request.setAttribute("title", "ログインフォーム");
%>
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<title><%= request.getAttribute("title") %></title>
</head>
<body>
<div class="page-background">
<div class="form-container">
<h1>ログイン <%= request.getAttribute("today") %></h1>
<form action="/learning/login" method="POST">
<div class="input-group">
<label for="user-id">ユーザーID</label>
<input type="text" id="user-id" name="user-id" required>
</div>
<div class="input-group">
<label for="password">パスワード</label>
<input type="password" id="password" name="password" required>
</div>
<div class="form-actions">
<button type="submit">ログイン</button>
</div>
</form>
</div>
</div>
</body>
</html>
Web技術入門編
https://paiza.jp/works/web_tech/primer
新・Java入門編
https://paiza.jp/works/java/new-primer
新・Java入門編40: 国際化(internationalization)について学習しよう > 日付の操作とフォーマット
https://paiza.jp/works/java/new-primer/java-new-primer-40/114003