Spring MVC 05 - @PathVariable

In this chapter we will talk about @PathVariable

Or use the examples used in the previous articles

To use @PathVariable, you need to configure the spring-dispather-servlet.xml first. The content of the spring-dispather-servlet.xml file is as follows:

<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 can implement setting parameters on the url path

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;
}

}

Enter http://localhost:8080/FirstSpringMVCPro/welcome/China/XiaoMing in the browser to get the result as follows:




Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325988556&siteId=291194637