1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Spring4を使ってみる(・8・)2

Posted at

Springおじさんにならなくては

お仕事でSpringを使っていく風潮が出てきたので、設定とかアノテーションとかをさらっておこうと思います。とりあえずJSON返すメソッドが作れたので、viewを返すクラス、メソッドを作ってみます。

前回

最低限の設定ファイルとクラスを書いてJSONをGETしてみた

設定

ServletContext.java
@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.hoge")
public class ServletContext extends WebMvcConfigurerAdapter {
    
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {

        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        registry.viewResolver(viewResolver);
    }
}

前回はアノテーションだけだったクラスが、MVCの設定でごにょごにょやってる

  • extends WebMvcConfigurerAdapter
    • Viewの設定とかを登録するメソッド(↓)を実装したいので、継承します。
  • configureViewResolvers(ViewResolverRegistry registry)
    • viewのテンプレートファイルを置くディレクトリの設定と、ファイルの拡張子の設定

viewファイル

index.jsp
<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head></head>
<body>
<h2>すぷりんぐ!</h2>
(・8・)${voice}
</body>
</html>
  • 上記の設定通り、/webapp/WEB-INF/views/に設置する
  • ${voice}はviewを返却するメソッドからもらう変数

Controllerクラス

ViewController.java
@Controller
public class ViewController {

    @RequestMapping("view")
    public String getView(Model model){
        model.addAttribute("voice", "ちゅん!");
        return "index";
    }
}
  • @Controller
    • WebAPIを定義したクラスのもの(@RestController)とちがう
    • こちらをアノテートすると戻り値の文字列に対応するパス、ファイル名のviewを返却するようになる
  • model.addAttribute()
    • 引数に置いたModel modelに自動的に(!)オブジェクトがインジェクトされてメソッドに渡ってくる
    • Model#addAttribute()で渡したkey, valueはjspから参照出来る

スクリーンショット 2016-07-13 1.18.44.png

やったー(・8・)

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?