Servlet 3.0+无web.xml配置Web
目录结构:
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-DyZyM96E-1579497459107)(C:\Users\Administrator\AppData\Roaming\Typora\typora-user-images\image-20200118154248380.png)]
package com.jack.springMVC.web;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HelloController {
@RequestMapping("/index")
public String hello(){
return "index";
}
}
package com.jack.springMVC;
import org.springframework.context.annotation.Bean;
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.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
@Configuration
@EnableWebMvc
@ComponentScan("com.jack.springMVC")
class MyMVCConfig {
@Bean
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views/");
viewResolver.setViewClass(JstlView.class);
viewResolver.setSuffix(".jsp");
return viewResolver;
}
}
package com.jack.springMVC;
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 WebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(MyMVCConfig.class);
ctx.setServletContext(servletContext);
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",new DispatcherServlet(ctx));
servlet.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
t.addMapping("/");
servlet.setLoadOnStartup(1);
}
}
来源:CSDN
作者:_Rowan
链接:https://blog.csdn.net/jgjgkjgk/article/details/104050545