spring的起初可能经常碰壁,因为网上的资料都是混乱的xml堆成的,混乱难以理解,我这个也是,阿哈哈哈哈!
新建一个Maven->create from archetype->org.jetbrains.idea.maven.model.MavenArchetype ->next->finsh
在src/main建立目录Java/com.xx.controller目录,然后建立HomeController,代码如下:
package com.speiyou.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; @Controller public class HomeController { @ResponseBody @RequestMapping("/hello") public String index(){ return "hello bobby"; } }
webapp/WEB-INF/web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <servlet> <servlet-name>myServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>myServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
myServlet-servlet.xml (myServlet和上面的servlet-name相对应)
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd "> <context:component-scan base-package="com.speiyou.controller"/> <!--<context:compent-scan base-package="com.speiyou.controller"/>--> </beans>
pom.xml project节点下增加节点:
<dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.13.RELEASE</version> </dependency> </dependencies>
project/build/plugins节点增加:
<plugin> <groupId>org.apache.tomcat.maven</groupId> <artifactId>tomcat7-maven-plugin</artifactId> <version>2.2</version> <configuration> <port>9003</port> <path>/</path> </configuration> </plugin>
mvn:tomcat7:run 在Maven project 窗口,Plugins->tomcat7->tomcat7:run
即可运行!