速度を使ったSpring MVCのクイックガイド

Velocityを使用したSpring MVCのクイックガイド

1. 前書き

Velocityは、Apache Software Foundationのテンプレートエンジンであり、通常のテキストファイル、SQL、XML、Javaコード、およびその他の多くのタイプで機能します。

この記事では、典型的なSpring MVCWebアプリケーションでVelocityを利用することに焦点を当てます。

2. Mavenの依存関係

次の依存関係を使用して、Velocityサポートを有効にすることから始めましょう。


    org.apache.velocity
    velocity
    1.7



    org.apache.velocity
    velocity-tools
    2.0

両方の最新バージョンは、velocityvelocity-toolsにあります。

3. 設定

3.1. Web構成

web.xmlを使用したくない場合は、Javaと初期化子:を使用してWebプロジェクトを構成しましょう。

public class MainWebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext sc) throws ServletException {
        AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
        root.register(WebConfig.class);

        sc.addListener(new ContextLoaderListener(root));

        ServletRegistration.Dynamic appServlet =
          sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
        appServlet.setLoadOnStartup(1);
    }
}

あるいは、もちろん、従来のweb.xmlを使用することもできます。


    Spring MVC Velocity
    
        mvc
    org.springframework.web.servlet.DispatcherServlet
        
        contextConfigLocation
        /WEB-INF/mvc-servlet.xml
     
     1
    

    
        mvc
    /*
    

    
        contextConfigLocation
    /WEB-INF/spring-context.xml
    

    
        org.springframework.web.context.ContextLoaderListener
    

サーブレットを「/ *」パスにマッピングしたことに注意してください。

3.2. Spring Config

ここで、Javaから始めて、単純なSpring構成について見ていきましょう。

@Configuration
@EnableWebMvc
@ComponentScan(basePackages= {
  "com.example.mvc.velocity.controller",
  "com.example.mvc.velocity.service" })
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
          .addResourceHandler("/resources/**")
          .addResourceLocations("/resources/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public ViewResolver viewResolver() {
        VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver();
        bean.setCache(true);
        bean.setPrefix("/WEB-INF/views/");
        bean.setLayoutUrl("/WEB-INF/layouts/layout.vm");
        bean.setSuffix(".vm");
        return bean;
    }

    @Bean
    public VelocityConfigurer velocityConfig() {
        VelocityConfigurer velocityConfigurer = new VelocityConfigurer();
        velocityConfigurer.setResourceLoaderPath("/");
        return velocityConfigurer;
    }
}

また、構成のXMLバージョンについても簡単に見てみましょう。


    
    
    
        
            /
        
    
    
        
        
        
        
    

ここで、注釈付きBean定義を探す場所をSpringに伝えています。

[.s1]#次の行で、プロジェクトでアノテーション駆動型構成を使用することを示しています。

velocityConfig」および「viewResolver」Beanを作成することにより、VelocityConfigurerにテンプレートを探す場所、およびVelocityLayoutViewResolverにビューとレイアウトを探す場所を指示します。

4. 速度テンプレート

最後に、共通のヘッダーから始めて、テンプレートを作成しましょう。

Our tutorials

およびフッター:

@Copyright example.com

そして、次のコードでparseを使用して上記のフラグメントを使用するサイトの一般的なレイアウトを定義しましょう。


    
        Spring & Velocity
    
    
        
#parse("/WEB-INF/fragments/header.vm")
$screen_content
#parse("/WEB-INF/fragments/footer.vm")

$screen_content変数にページのコンテンツが含まれていることを確認できます。

最後に、メインコンテンツのテンプレートを作成します。

Index

Tutorials list

#foreach($tut in $tutorials) #end
Tutorial Id Tutorial Title Tutorial Description Tutorial Author
$tut.tutId $tut.title $tut.description $tut.author

5. コントローラー側

レイアウトのコンテンツとしてチュートリアルのリストを返すシンプルなコントローラーを作成しました:

@Controller
@RequestMapping("/")
public class MainController {

    @Autowired
    private ITutorialsService tutService;

    @RequestMapping(value ="/", method = RequestMethod.GET)
    public String defaultPage() {
        return "index";
    }

    @RequestMapping(value ="/list", method = RequestMethod.GET)
    public String listTutorialsPage(Model model) {
        List list = tutService.listTutorials();
        model.addAttribute("tutorials", list);
        return "index";
    }
}

最後に、この簡単な例にローカルでアクセスできます–たとえば:localhost:8080/spring-mvc-velocity/

6. 結論

この簡単なチュートリアルでは、Velocityテンプレートエンジンを使用してSpring MVCWebアプリケーションを構成しました。

このチュートリアルの完全なサンプルコードは、GitHub repositoryにあります。