springmvc所需要的jar包:
- commons-logging.jar
- org.springframework.asm-3.0.5.RELEASE.jar
- org.springframework.beans-3.0.5.RELEASE.jar
- org.springframework.context-3.0.5.RELEASE.jar
- org.springframework.core-3.0.5.RELEASE.jar
- org.springframework.expression-3.0.5.RELEASE.jar
- org.springframework.web-3.0.5.RELEASE.jar
- org.springframework.web.servlet-3.0.5.RELEASE.jar
web.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!-- 配置springmvc -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置DispatcherServlet的初始化参数:配置springMVC的配置文件位置名称
如果不配置,默认加载WEB-INF下的DispatcherServlet-servlet.xml文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- 为src目录下的springmvc.xml文件 -->
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<!-- 拦截所有.action的请求【也可以为.do】 -->
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
springmvc.xml配置
<?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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
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.wcg.springmvc"></context:component-scan>
<!-- 配置视图解析器:如何把handler方法返回的值解析为实际的物理视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceView">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
HelloWorld.java
@Controller
public class HelloWorld {
/**
* 1.使用@RequestMapping注解来映射请求的url
* 2.返回值会通过视图解析器解析为实际的物理视图,对于InternalResourceViewResolver视图解析器,会做如下的解析
* 通过prefix+returnValue+suffix这样的方式对到实际的物理视图,然后执行转发操作【/WEB-INF/views/success.jsp】
* @return
*/
@RequestMapping("/helloworld.action")
public String helloWorld(){
System.out.println("Hello World");
return "success";
}
}