我们在上一篇文章《提高开发和发布效率-创建不依赖于外部环境可独立运行java程序的项目(一):基础篇》
中提到了如何简化开发、调试、打包java程序,以及如何嵌入一个tomcat到自己应用程序的方法。但大多数人在实际web开发中,不会全部从最原始的servlet
进行开发,一般要使用一些框架简化开发。本文以流行的spring
为例,介绍如何整合spring mvc
。
pom.xml
文件,导入spring mvc
相关依赖类修改属性
<properties>
<tomcat.version>8.5.30tomcat.version>
<spring.version>4.0.7spring.version>
<commons-lang3.version>3.1commons-lang3.version>
properties>
增加依赖
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>${spring.version}.RELEASEversion>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-lang3artifactId>
<version>${commons-lang3.version}version>
dependency>
spring mvc
在com.gchsoft下创建一个web package
,然后创建WebConfig
类
package com.gchsoft.web;
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.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
@EnableWebMvc //启用spring mvc
@ComponentScan("com.gchsoft.web") //启用组件扫描
public class WebConfig extends WebMvcConfigurerAdapter {
@Bean
public ViewResolver viewResolver() {
//指定视图解析器为jsp
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
//配置静态资源处理
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
super.addResourceHandlers(registry);
}
}
RootConfig
,以方便增加其他config在com.gchsoft下创建一个config package
,然后创建RootConfig
类
package com.gchsoft.config;
import java.util.regex.Pattern;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.core.type.filter.RegexPatternTypeFilter;
/**
配置组件扫描包为com.gchsoft,排除com.gchsoft.web
**/
@Configuration
@ComponentScan(basePackages={"com.gchsoft"},
excludeFilters={
@Filter(type=FilterType.CUSTOM, value=RootConfig.WebPackage.class)
})
public class RootConfig {
public static class WebPackage extends RegexPatternTypeFilter {
public WebPackage() {
super(Pattern.compile("com\\.gchsoft\\.web"));
}
}
}
DispatcherServlet是Spring MVC的核心,它负责将请求路由到其他的组件之中.
在com.gchsoft.config下添加MySpringMvcWebInitializer
类
package com.gchsoft.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import com.gchsoft.web.WebConfig;
public class MySpringMvcWebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[] { RootConfig.class };
}
@Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[] { WebConfig.class };
}
@Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
}
spring mvc
在com.gchsoft.web下创建HomeController.java
package com.gchsoft.web;
import static org.springframework.web.bind.annotation.RequestMethod.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/")
public class HomeController {
@RequestMapping(value="/home",method = GET)
public String home(Model model) {
return "home";
}
}
在webapp
下创建WEB-INF/views
目录,在下面添加home.jsp
<html>
<head>
<title>MySpring webmvctitle>
head>
<body>
<h1>Welcome to MySpring Application!h1>
body>
html>
测试访问控制器
运行我们的App.main()
方法以启动tomcat
,然后打开浏览器输入:http://localhost:8080/home,出现:
Welcome to MySpring Application!
这明控制器的home方法访问成功。
测试前一篇文章中创建的index.jsp
在浏览器输入:http://localhost:8080/,出现:
Hello,tomcat!
测试前一篇文章中创建的FirstServlet
在浏览器输入:http://localhost:8080/first,出现:
HTTP Status 404 – Not Found
Type Status Report
Message /first
Description The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.
Apache Tomcat/8.5.30
这说明没有找到FirstServlet
,为啥呢?
这是因为我们启用
spring mvc
之后,spring拦截了所有的/*
的servlet请求转发,FirstServlet
没有针对spring mvc
做任何设置,当然也就无法访问了。
servlet
和spring mvc
和谐相处在com.gchsoft.config下添加MyWebApplicationInitializer
类
package com.gchsoft.config;
import com.gchsoft.servlet.FirstServlet;
import org.springframework.web.WebApplicationInitializer;
import javax.servlet.Registration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
/**
* Created by gch
*/
public class MyWebApplicationInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException{
//加载FirstServlet
Dynamic firstServlet=servletContext.addServlet("/firstServlet", FirstServlet.class);
firstServlet.addMapping("/first");
}
}
打开src/main/java/com/gchsoft/servlet/FirstServlet.java
,去掉@WebServlet
注解(为什么?因为不需要了):
//@WebServlet(
// name = "FirstServlet",
// urlPatterns = {"/first"}
// )
public class FirstServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
ServletOutputStream out = resp.getOutputStream();
out.write("This is first servlet for embedded tomcat. ".getBytes());
out.flush();
out.close();
}
}
重新运行我们的App.main()
方法,在浏览器输入:http://localhost:8080/first,出现:
This is first servlet for embedded tomcat.
我们的FirstServlet
又回来啦。
本文介绍了一般java
程序导入spring mvc
的方法,以及如何与原有的servlet
程序和谐相处;这样可以根据自己的需要来扩充、灵活的使用spring mvc
,不必为二选一烦恼;同时,你仍然可以使用前一篇文章的方法,将tomcat
、spring mvc
打包成jar包,进行发布。
访问最新文章,请访问我的独立博客或者关注微信公众号:
独立博客: http://gch.w3c0.com/
微信公众号:程序与算法