1、增加Spring的支持
新建web项目,添加如下jar包:
commons-logging-1.2.jar spring-aop-4.2.5.RELEASE.jar spring-aspects-4.2.5.RELEASE.jar spring-beans-4.2.5.RELEASE.jar
spring-context-4.2.5.RELEASE.jar spring-context-support-4.2.5.RELEASE.jar spring-core-4.2.5.RELEASE.jar spring-expression-4.2.5.RELEASE.jar
spring-instrument-4.2.5.RELEASE.jar spring-instrument-tomcat-4.2.5.RELEASE.jar spring-jdbc-4.2.5.RELEASE.jar spring-jms-4.2.5.RELEASE.jar
spring-messaging-4.2.5.RELEASE.jar spring-orm-4.2.5.RELEASE.jar spring-oxm-4.2.5.RELEASE.jar spring-test-4.2.5.RELEASE.jar
spring-tx-4.2.5.RELEASE.jar spring-web-4.2.5.RELEASE.jar spring-webmvc-4.2.5.RELEASE.jar
spring-webmvc-portlet-4.2.5.RELEASE.jar spring-websocket-4.2.5.RELEASE.jar
2、配置前端控制器DispatcherServlet
配置web.xml文件(添加DispatcherServlet的配置)
<!-- 定义Spring MVC的前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<sevlet-class>org.springframework.web.servlet.DispacherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-stratup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
3、配置SpringMVC的Controller
配置springMVC的配置文件spring-config.xml
<beans>
<!--配置Handle,映射“Hello”请求-->
<beanname="/hello" class="org.fkit.conttroler.HelloController" />
<!--处理映射器将bean的那么作为url进行查找,需要在配置Handle时指定name(即URL)-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />
<!--SimpleControllerHandlerAdapter是一个处理器适配器,所有处理器适配器都要实现HandlerAdapter接口-->
<bean class="org.springframework.web.servler.mvc.SimpleControllerHandlerAdapter" />
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" />
</beans>
4、Controller类的实现
Controller类必须实现Controller接口 ,用来处理/hello请求。(或者直接使用@Controller注解)
public class HelloController implements Controller{
private static final Log logger = LogFactory.getLog(HelloController.calss);
@Override
public ModelAndView handleRequest(HttpServletRequest request,HttpServletResponse response) throws Exception{
logger.info("HandleRequest 被调用");
ModelAndView mv = new ModelAndView();
mv.addObject("message","Hello World!");
mv.setViewName("/WEB-INF/content/welcome.jsp");
return mv;
}
}
5、View页面
<body>
<!--页面可以访问Controller传递出来的message-->
${requestScope.message}
</body>
6、测试应用
http://localhost:8080/SpringmVCTest/hello