0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

ModelAndViewの基本の使い方を理解する

Last updated at Posted at 2025-10-19

:writing_hand_tone2:この記事は、初めてModelAndViewクラスを使ってみたい初心者向けに書いています。

ModelAndViewとは

ModelとViewをセットで定義できるクラス。
画面表示処理を行うコントローラで画面に渡す値をModelAndViewオブジェクトに詰めて返却することで、画面に値を渡すことができる。
画面に渡した値は、ビュー側でテンプレートエンジンによって処理される。

サンプルコード

使用バージョン

  • Java: 23.0.2
  • springframework: 3.5.6
  • Vue.js: 2.7.14

設定ファイル

thymeleafライブラリをプロジェクトに追加する

pom.xml
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

コントローラ

ModelAndViewオブジェクトを生成後、必要な情報を設定し返却する

SampleController.java
import org.springflamework.web.servlet.ModelAndView;

@Controller
public class SampleController {
    @GetMapping("/")
    public ModelAndView samplePage() {
        ModelAndView mav = new ModelAndView();
        mav.addObject("message", "Hello");     // 「Hello」をmessageという名前でmavにセット
        mav.setViewName("samplePage");         // HTML名(画面名)を指定
        return mav;
    }}

ビュー

scriptタグ内のdata部で、ModelAndViewオブジェクトに設定したキー名(第一引数)を/*[[${ xxx }]]*/の形で受け取る
補足:/*[[${ xxx }]]*/に続いて書いている「サンプルメッセージ」の部分は実行時に無視されるので、コメントアウトとして書いておくのがおすすめです。

samplePage.html
<!DOCTYPE html>
<html lang="ja" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.7.14/dist/vue.js"></script>
</head>
<body>
    <div id="app">
        <p>メッセージ:{{ msg }}</p>
    </div>
</body>
</html>
<script th:inline="javascript">
    new Vue({
        el: '#app',
        data: {
            msg : /*[[${ message }]]*/ サンプルメッセージ,
        },
    })
</script>

→メッセージ:Hello
 と画面に表示される

さいごに

送るデータが多くなる場合はFormクラスを利用してまとめるのが良いかと思います。
こちらに関してはプチ応用編として、近日中に追って投稿する予定です:bow_tone1:

参考

ModelAndView (Spring Framework API) - Javadoc

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?