Spring MVC 05 - @PathVariable

本章我们来谈下@PathVariable

还是使用前几篇中使用的例子

要使用@PathVariable,需要先在spring-dispather-servlet.xml中做下配置,spring-dispather-servlet.xml文件内容如下:

<beans xmlns="http://www.springframework.org/schema/beans"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xmlns:mvc="http://www.springframework.org/schema/mvc"
     xsi:schemaLocation="
         http://www.springframework.org/schema/beans
         http://www.springframework.org/schema/spring-beans.xsd
         http://www.springframework.org/schema/context
         http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc.xsd">
         
<context:component-scan base-package="com.haha"/>
<mvc:annotation-driven/>

<bean id="viewResolver" 
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
   <property name="prefix">
      <value>/WEB-INF/</value>
   </property>
   <property name="suffix">
      <value>.jsp</value>
   </property>
</bean>
</beans>

@PathVariable可以实现在url路径上设置参数

package com.haha;
import java.util.Map;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController{

@RequestMapping("/welcome/{countryName}/{userName}")
public ModelAndView helloWorld(@PathVariable Map<String,String> pathVars){
// TODO Auto-generated method stub
String name=pathVars.get("userName");
String country = pathVars.get("countryName");
ModelAndView modelandview = new ModelAndView("HelloPage");
   modelandview.addObject("welcomeMessage","Hi, "+name+", you are from" +country );
   return modelandview;
}

}

在浏览器中输入http://localhost:8080/FirstSpringMVCPro/welcome/China/XiaoMing 获取结果如下:




猜你喜欢

转载自blog.csdn.net/u013537471/article/details/53009936