本文共 3079 字,大约阅读时间需要 10 分钟。
ViewResolver
javax.servlet javax.servlet-api javax.servlet jstl org.springframework.boot spring-boot-starter-tomcat org.apache.tomcat.embed tomcat-embed-jasper
spring.mvc.view.prefix=/WEB-INF/jsp/ spring.mvc.view.suffix=.jsp
package cn.netkiller;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.EnableAutoConfiguration;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.ComponentScan;import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication@EnableAutoConfiguration@ComponentScan@EnableSchedulingpublic class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); }}
package cn.netkiller.web;import java.util.HashMap;import java.util.Map;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.client.RestTemplate;import org.springframework.web.servlet.ModelAndView;@Controllerpublic class IndexController { @RequestMapping("/welcome") @ResponseBody public String welcome() { String message = "Welcome"; return message; } @RequestMapping("/index") public ModelAndView index() { String message = "Helloworld"; return new ModelAndView("index").addObject("message", message); }}
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>Home ${message}
如果你需要使用其他模板引擎可以采用 Bean 注解方式。
package cn.netkiller.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;import org.springframework.web.servlet.config.annotation.EnableWebMvc;import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;import org.springframework.web.servlet.view.InternalResourceViewResolver;@Configuration@EnableWebMvcpublic class WebMvcConfig extends WebMvcConfigurerAdapter { @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("WEB-INF/jsp/"); resolver.setSuffix(".jsp"); return resolver; }}
原文出处:Netkiller 系列 手札
本文作者:陈景峯 转载请与作者联系,同时请务必标明文章原始出处和作者信息及本声明。