本文讲述的是使用idea搭建一个springmvc web项目,无需web.xml及各种xml配置,将分别演示controller返回一个页面和json数据,然后基于tomcat部署,主要步骤如下:
1.创建maven 项目,点击Next
2. 输入如下信息,点击Next
3. 输入如下信息,点击Next
4. 在 src/main目录下新建webapp目录:
5. 修改pom.xml,配置成war包,并按需求引入相关依赖:
6. 配置tomcat及相关参数,特别要注意第二张图那个配置,否则有可能访问不了:
7.主要代码如下:
package com.francis.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewResolverRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@ComponentScan("com.francis.controller")
@EnableWebMvc
public class AppConfig implements WebMvcConfigurer {
/**
* WebMvcConfigurer中的十多个方法基本上涵盖了spring mvc需要配置的内容,
* 如:跨域配置、视图解析器、参数解析器、拦截器、消息转换器等等,可以按需求重写
*/
/**
* 配置视图解析器
* @param registry
*/
@Override
public void configureViewResolvers(ViewResolverRegistry registry) {
registry.jsp("/WEB-INF/", ".html");
}
/**
* 配置资源映射,否则访问不了html
* @param registry
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/WEB-INF/**").addResourceLocations("/WEB-INF/");
}
}
package com.francis.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class MvcController {
@RequestMapping("/index")
public String index() {
return "index";
}
@RequestMapping("/mvc")
@ResponseBody
public String mvc() {
return "Hello Spring MVC";
}
}
package com.francis;
import com.francis.config.AppConfig;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
public class MyWebApplicationInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
// Load Spring web application configuration
AnnotationConfigWebApplicationContext ac = new AnnotationConfigWebApplicationContext();
ac.register(AppConfig.class);
// ac.refresh();
// Create and register the DispatcherServlet
DispatcherServlet servlet = new DispatcherServlet(ac);
ServletRegistration.Dynamic registration = servletContext.addServlet("dispatcherServlet", servlet);
registration.setLoadOnStartup(1);
registration.addMapping("/*");
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index.html</title>
</head>
<body>
<h2>Hello, Spring MVC</h2>
</body>
</html>
8.启动 tomcat
访问 /index,返回页面,如下图:
访问 /mvc,返回json,如下图:
参考文档: https://docs.spring.io/spring/docs/5.2.5.RELEASE/spring-framework-reference/web.html#mvc