LoginSignup
2
1

More than 3 years have passed since last update.

Spring Frameworkを使ってみる(2)

Last updated at Posted at 2020-06-07

おさらい

この章で下記の内容を紹介しています。

  • 画面遷移
  • 遷移元画面index.jspの作成
  • 遷移先画面top.jspの作成
  • ログイン画面のコントローラLoginController.javaの作成

画面遷移

Propertiesファイルを編集

Spring boot start projectのため、JSPを利用するには、少々面倒な設定が必要です。
ちなみに、Spring bootはJSPを非推奨で、Thymleafが推奨されています。

Thymeleafを利用したHTMLの場合、templatesフォルダの配下へHTMLファイルを配置します。
staticフォルダ配下へjs, cssファイルを配置します。

application.propertiesには下記を追記します。


spring.mvc.view.prefix: /WEB-INF/jsp/
spring.mvc.view.suffix: .jsp

image.png

index.jspを作成

index.jspファイルをWEB-INFのjspフォルダ配下へ配置します。


<!DOCTYPE html>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<html>
 <head>
 <meta charset="utf-8">
 <title>ログイン</title>
 </head>
 <body>

<form action="login" method="post">

<div>
 <input type="submit" value="ログイン">
 </div>

 </form>

 </body>
</html>

サーバを立ち上げた後に、Path with WEB-INF or META-INFというWarningメッセージが出て、ページが表示されない場合、下記のリンクを参照し、解決することができます。
https://www.yawintutor.com/warn-3200-path-with-web-inf-or-meta-inf/

top.jspを作成

LoginController.java
<!DOCTYPE html>

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="spring" uri="http://www.springframework.org/tags"%>

<html>
 <head>
 <meta charset="utf-8">
 <title>トップ</title>
 </head>
 <body>
 ようこそ
 </body>
</html>

LoginController.javaを作成

(LoginController.java)
package com.example.HelloWorld;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
    public class LoginController {
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(Model model) {
        return "top";
    }
}

コントローラに関する説明は下記を参照してください。


サーバを立ち上げて、index.htmlへアクセスすると、下記画面が表示されます。
image.png

ログインを押下すると、top.htmlへ遷移することができました。
image.png

次回

画面間の値の受け渡しを説明します。

2
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
1