您的位置:首页 > 编程语言 > Java开发

spring: spittr实例 构建简单的web应用

2018-01-23 11:08 381 查看
我的环境是: jdk8, spirng4

之前照者书上说的做了,不得成功,于是网上百度,不得其然。

后来看到一篇文章,甚是所感。https://segmentfault.com/q/1010000007921684/a-1020000007922842

单词拼错了,无地自容……
我的包名是spittr
但是我的自动扫描写的是spitter,

晕,忘了给视图解析器加@Bean了

或者很多注解写成一排了


  

于是乎鼓捣重来

SpittrWebAppInitializer


package spittr.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

public class SpittrWebAppInitializerextends AbstractAnnotationConfigDispatcherServletInitializer{

@Override
protected Class<?>[] getRootConfigClasses() {
//根容器
return new Class<?>[] { RootConfig.class };
}

@Override
protected Class<?>[] getServletConfigClasses() {
//Spring mvc容器
return new Class<?>[] { WebConfig.class };
}

@Override
protected String[] getServletMappings() {
//DispatcherServlet映射,从"/"开始
return new String[] { "/" };
}

}


  RootConfig

package spittr.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@ComponentScan(
basePackages = {"spittr"},
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class)
}
)
public class RootConfig {
}


  WebConfig

package spittr.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
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
@EnableWebMvc
@ComponentScan("spittr.web")
public class WebConfig extends WebMvcConfigurerAdapter{

@Bean
public ViewResolver viewResolver() { //配置JSP视图解析器
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
//可以在JSP页面中通过${}访问beans
resolver.setExposeContextBeansAsAttributes(true);
return resolver;
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable(); //配置静态文件处理
}
}


  

homeController

package spittr.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class HomeController {

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

}


  

目录如下:



运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: