本文講述的是使用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