在我们之前进行web开发的时候,通常都会有一个web.xml存在,我们会在web.xml里面配置Servlet、Filter等一些web开发相关的东西。但是由于Servlet3.0的规范和Spring3.1功能的增强,现在我们在进行web开发的时候可以不用再使用web.xml了,转而全部使用java注解就可以了。下面是一个例子:
首先我们先创建一个StrartWebApplicationInitializer类,这个类继承AbstractAnnotationConfigDispatcherServletInitializer这个类,代码如下:
package com.zkn.springmvc.annotationanalysis;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import javax.servlet.ServletContext;
/**
* Create By ZKN
*
* @date 2017/10/28
* @time 上午9:53
*/
public class StrartWebApplicationInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
/**
* SpringContext中相关的bean
*
* @return
*/
@Override
protected Class>[] getRootConfigClasses() {
return new Class[]{SpringRootConfig.class};
}
/**
* DispatcherServlet中上下文相关的Bean
*
* @return
*/
@Override
protected Class>[] getServletConfigClasses() {
return new Class[]{WebMvcConfig.class};
}
/**
* Servlet请求映射路径
*
* @return
*/
@Override
protected String[] getServletMappings() {
return new String[]{
"/"
};
}
@Override
public void registerDispatcherServlet(ServletContext servletContext) {
//配置profile,激活不同的环境
servletContext.setInitParameter("spring.profiles.active", "jsp");
super.registerDispatcherServlet(servletContext);
}
}
这里需要注意一下,getRootConfigClasses这个方法返回的类对应的是Spring上下文相关的一些配置,getServletConfigClasses这个方法返回的类是SpringMVC相关的一些类的配置。我们看一下SpringRootConfig和WebMvcConfig这两个类中的配置项:
package com.zkn.springmvc.annotationanalysis;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
/**
* Create By ZKN
*
* @date 2017/10/28
* @time 上午9:55
*/
@Configuration
@ComponentScan(basePackages = "com.zkn.springmvc.annotationanalysis.service")
public class SpringRootConfig {
}
package com.zkn.springmvc.annotationanalysis;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.context.ServletContextAware;
import org.springframework.web.servlet.HandlerAdapter;
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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ITemplateResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import javax.servlet.ServletContext;
import java.util.Arrays;
/**
* Create By ZKN
*
* @date 2017/10/28
* @time 上午10:04
*/
@EnableWebMvc
@Configuration
@ComponentScan(basePackages = "com.zkn.springmvc.annotationanalysis.controller")
public class WebMvcConfig extends WebMvcConfigurerAdapter implements ServletContextAware {
private ServletContext servletContext;
@Bean
@Profile("jsp")
public ViewResolver jspViewResolver() {
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("WEB-INF/resources/jsp/");
viewResolver.setSuffix(".jsp");
viewResolver.setViewClass(JstlView.class);
viewResolver.setExposePathVariables(true);
return viewResolver;
}
/**
* 视图解析器
*
* @return
*/
@Bean
@Profile(value = "thymeleaf")
public ViewResolver viewResolver() {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine());
return viewResolver;
}
/**
* 模版引擎
*
* @return
*/
@Bean
@Profile("thymeleaf")
public TemplateEngine templateEngine() {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver());
return templateEngine;
}
/**
* 模版引擎解析器
*
* @return
*/
@Bean
@Profile("thymeleaf")
public ITemplateResolver templateResolver() {
ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver(servletContext);
templateResolver.setPrefix("WEB-INF/resources/thymeleaf/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode(TemplateMode.HTML);
return templateResolver;
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
/**
* 配置静态资源
*
* @param configurer
*/
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
/**
* 处理静态资源
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/js/**").addResourceLocations("/WEB-INF/resources/js/");
registry.addResourceHandler("/img/**").addResourceLocations("/WEB-INF/resources/img/");
super.addResourceHandlers(registry);
}
@Bean
public HandlerAdapter requestMappingHandlerAdapter(){
RequestMappingHandlerAdapter handlerAdapter = new RequestMappingHandlerAdapter();
StringHttpMessageConverter messageConverter = new StringHttpMessageConverter();
messageConverter.setSupportedMediaTypes(Arrays.asList(MediaType.valueOf("text/html;charset=UTF-8")));
handlerAdapter.getMessageConverters().add(messageConverter);
handlerAdapter.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
return handlerAdapter;
}
}
下面我们写个Controller来测试一下:
package com.zkn.springmvc.annotationanalysis.controller;
import com.zkn.springmvc.annotationanalysis.result.DataResult;
import com.zkn.springmvc.annotationanalysis.vo.PersonInfoVO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* Create By ZKN
*
* @date 2017/10/28
* @time 下午3:00
*/
@RestController
@RequestMapping("rest")
public class RestfulController {
/**
* 返回一个字符串
*
* @return
*/
@GetMapping("resultString")
public String resultString() {
return "我是一个字符串!";
}
/**
* 返回一个json数据
*
* @return
*/
@GetMapping("resultJson")
public DataResult resultJson() {
DataResult dataResult = new DataResult<>();
PersonInfoVO personInfoVO = new PersonInfoVO();
personInfoVO.setUserName("我是张三");
personInfoVO.setPassWord("woshizhangsan");
dataResult.setData(personInfoVO);
dataResult.setSuccess(true);
return dataResult;
}
}
当我们发送的请求为:http://localhost:8082/rest/resultString时,结果如下:
当我们发送的请求为:http://localhost:8082/rest/resultJson时,结果如下:
在上面的demo中我们使用了两种视图技术,一种是JSP,一种是Thymeleaf,通过激活不同的profile来切换不同的环境。完整代码请点击这里:
https://github.com/zhangconan/JavaWeb/tree/master/springmvc-annotation-analysis
是不是感觉有点神奇呢?不需要web.xml只需要这样配置一下我们就可以进行web开发了。我会在近期的文章中简单的说明一下我们为什么可以这样去做,敬请期待。