您的位置:首页 > 移动开发

SpringMVC之@RequestMapping

2016-04-28 23:38 295 查看
一、SpringMVC通过使用@RequestMapping注解为控制器指定可以处理哪些URL请求。

       @RequestMapping可以放在类处或者方法处

       1.放在类定义处:它是相对于web应用的根目录,提供初步应用的映射请求

       2.放在方法处:它是相对于类定义处的url,如果类定义处未标注@RequestMapping,则方法处标注的@RequestMapping相对于web应用的根目录。

下面通过一个简单的例子来看下这两个的区别:

1.首先引入所需要的jar包



2.配置web.xml

<!-- 配置DispatcherServlet -->
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!-- 配置 DispatcherServlet 的一个初始化参数: 配置 SpringMVC 配置文件的位置和名称 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

3.配置springmvc的配置文件springmvc.xml

<!-- 配置自定扫描的包 -->
<context:component-scan base-package="com.kevin"></context:component-scan>

<!-- 配置视图解析器: 如何把 handler 方法返回值解析为实际的物理视图 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>


4.配置页面index.jsp

<a href="hello">hello world!</a>

5.配置控制器类

package com.kevin.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class TestRequestMapping {

@RequestMapping("/hello")
public String hello(){
return "hello";
}
}


6.配置对应的hello.jsp

<h1>Hello World!</h1>


当点击index.jsp页面的超链接时候,浏览器的地址栏会变为 http://localhost:8080/springmvc_study/hello,然后页面会跳转到 hello.jsp
如果把index.jsp变为

<a href="springmvc/hello">hello world!</a>

把控制类修改为

package com.kevin.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/springmvc")
public class TestRequestMapping {

@RequestMapping("/hello")
public String hello(){
return "hello";
}
}
当点击 index.jsp页面的超链接时候,浏览器地址会变为http://localhost:8080/springmvc_study/springmvc/hello,然后页面跳转到hello.jsp

 


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息