1
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でまとめてパラメータを送る

Posted at

:arrow_down:ModelAndViewの基本はこちら
https://qiita.com/sakananana/items/c53865dd94ce5f72d0e7

サンプルコード

使用バージョン

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

フォーム

UserFormクラスを作成し、パラメータ名を設定する

UserForm.java
import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class UserForm {
    // ユーザー名
    private String name;

    // email
    private String email;

    // 住所
    private String address;
}

コントローラ

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

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

@Controller
public class SampleController {
    @GetMapping("/")
    public ModelAndView samplePage() {
        ModelAndView mav = new ModelAndView();

        UserForm userForm = new UserForm();
        userForm.setName("Sakana");
        userForm.setEmail("sample@test");
        userForm.setAddress("XX県YY市");
        mav.addObject("userInfo", userForm);   // userFormをuserInfoという名前でmavにセット
        mav.setViewName("samplePage"); 
        return mav;
    }}

ビュー

scriptタグ内のdata部で、/*[[${ userInfo.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>ユーザー名:{{ userInfo.name }}</p>
        <p>email:{{ userInfo.email }}</p>
        <p>住所:{{ userInfo.address }}</p>
    </div>
</body>
</html>
<script th:inline="javascript">
    new Vue({
        el: '#app',
        data: {
            userInfo : {
                name : /*[[${ userInfo.name }]]*/ ユーザー名,
                email : /*[[${ userInfo.email }]]*/ email,
                address : /*[[${ userInfo.address }]]*/ 住所,
            },
        },
    })
</script>


ユーザー名:Sakana
email:sample@test
住所:XX県YY市
 と画面に表示される

1
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
1
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?