我的建議從新練習一遍搭建的過程,若是感受麻煩你能夠直接複製上一個工程,可是須要修改pom.xml中的一點信息php
<groupId>com.hanpang.springmvc</groupId>
<artifactId>springmvc-helloword-annotation</artifactId>
<version>0.0.1-SNAPSHOT</version>
複製代碼
修改artifactId即 , Controller仍是用上一次的便可java
package com.hanpang.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
@Configuration
@EnableWebMvc
@ComponentScan(basePackages="com.hanpang.**.web")
public class SpringMvcConfiguration {
}
複製代碼
等價於web
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<!-- 1.啓動SpringMVC註解 -->
<mvc:annotation-driven/>
<!-- 2.掃描註解 -->
<context:component-scan base-package="com.hanpang.**.web"/>
</beans>
複製代碼
package com.hanpang.config;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class HelloWorldInitializer implements WebApplicationInitializer {
@Override
public void onStartup( ServletContext application ) throws ServletException {
System.out.println("開始加載容器");
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(SpringMvcConfiguration.class);//核心類
ctx.setServletContext(application);
ServletRegistration.Dynamic servlet = application.addServlet("dispatcher", new DispatcherServlet(ctx));
servlet.setLoadOnStartup(2);
servlet.addMapping("/");
}
}
複製代碼
這個推薦使用spring
package com.hanpang.config;
import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
public class HelloWorldInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
@Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] {SpringMvcConfiguration.class};//核心類
}
@Override
protected Class<?>[] getServletConfigClasses() {
return null;
}
@Override
protected String[] getServletMappings() {
return new String[] {"/"};
}
}
複製代碼
tomcat7:run -Dmaven.tomcat.uriEncoding=UTF-8 -Dmaven.tomcat.path=/ -Dmaven.tomcat.port=8080
複製代碼
只要在控制檯能顯示Hello Worldspring-mvc