spring4.0 spring MVC(三)学习

来源:互联网 发布:ukulele调音软件 下载 编辑:程序博客网 时间:2024/04/30 10:59

1、上一节中,讲到了spring中autowired自动注入。在本节中我将提到spring MVC中controller的使用。下面的实例仍然沿用上一节中的实例项目。下载地址:http://download.csdn.net/detail/qq5132834/9171379

2、在类的根目录下,新建一个文件:spring-mvc.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-3.0.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context-3.0.xsd"><!-- controller包(自动注入) --><context:component-scan base-package="com.hl.controller" /></beans>

3、在跟目录下新建一个包名:com.hl.controller。在其中新建一个类,如下:

package com.hl.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping("/myController")public class myController {@RequestMapping("/showHelloWorld")public String showHelloWorld(){System.out.println("----showLogin----");return "../index.jsp";}}

4、在web.xml中新增spring mvc的配置。正web.xml文件的内容如下所示:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">  <display-name>SpringStudy</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list>   <servlet><servlet-name>SpringMVC</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><init-param><description>spring MVC  配置文件</description><param-name>contextConfigLocation</param-name><param-value>classpath:spring-mvc.xml</param-value></init-param><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>SpringMVC</servlet-name><url-pattern>*.do</url-pattern></servlet-mapping><welcome-file-list><welcome-file>/index.jsp</welcome-file></welcome-file-list><session-config><session-timeout>15</session-timeout></session-config>  </web-app>


5、新增和配置以上数据后,重新启动项目。在浏览器中输入:http://localhost:8080/SpringStudy/myController/showHelloWorld.do。浏览器会调整至http://localhost:8080/SpringStudy/index.jsp的页面中。后台可以观察到的数据如下:

----showLogin----eatingwalking
6、目前尚没有讲解为何需要这样去配置spring mvc。但是我们的目标是怎么去搭建一个完整的系统。在完成这个目标之后,我会慢慢提到为什么要这么去。这里,我只需要知道怎么操作去完成目标,以便给自己增添信心。
7、Demo下载地址:http://download.csdn.net/detail/qq5132834/9175515





0 0
原创粉丝点击