添加jar包
除了添加spring核心的那4个jar包和一个commons-logging.jar。
还需要添加
- spring-web-3.2.0.RELEASE.jar
- spring-webmvc-3.2.0.RELEASE.jar
- jstl-1.2.jar
在web.xml里边配置前端控制器
<!-- 前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 加载springmvc配置 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
建立springmvc.xml文件
<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/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- 使用spring组件扫描 -->
<context:component-scan base-package="cn.itcast.springmvc.first" />
<!-- 配置注解驱动 -->
<mvc:annotation-driven />
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>
</beans>
建立Test.java
@Controller
public class Test {
@RequestMapping(value="/test")
public void test(HttpServletRequest request,HttpServletResponse response) throws Exception{
String num=request.getParameter("num");
request.setAttribute("item", num);
request.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(request, response);
}
}
建立test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
${item}
</body>
</html>
在浏览器访问
http://localhost:8080/springmvctest/test.action?num=222
之后会在页面显示出222