SpringMVC:如何在标记为@RequestMapping的方法中获取映射URI
我目前正在开发一个SpringMVC应用程序,当我在web.xml文件中将所有传入的URL映射到一个DispatcherServlet时,我想知道是否有可能检索已有效映射的URI。下面是一个例子来说明我的担忧:SpringMVC:如何在标记为@RequestMapping的方法中获取映射URI,spring,spring-mvc,Spring,Spring Mvc,我目前正在开发一个SpringMVC应用程序,当我在web.xml文件中将所有传入的URL映射到一个DispatcherServlet时,我想知道是否有可能检索已有效映射的URI。下面是一个例子来说明我的担忧: import static org.springframework.web.bind.annotation.RequestMethod.*; import org.springframework.stereotype.Controller; import org.springframew
import static org.springframework.web.bind.annotation.RequestMethod.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class HomeController {
@RequestMapping(method={GET})
public String processAllRequest(){
return "viewName";
}
}
由于我在web.xml中将URL映射定义为“/*”,因此所有传入的请求都将在我的控制器类中结束,如上所示。例如,以下两个请求都将由来自我的控制器的processAllRequest()方法处理
- myApplicationContext/主页
- myApplicationContext/注销
是否可以通过注入HttpServletRequest或另一个对象作为方法的参数来检索此类信息?Spring会注入
HttpServletRequest
,如果您将其放入处理程序参数中,则可以这样做
但如果需要区分不同的URL,只需将它们放在不同的处理程序中:
@Controller
public class HomeController {
@RequestMapping(value="/home", method={GET})
public String processHome(){
return "viewName";
}
@RequestMapping(value="/login", method={GET})
public String processLogin(){
return "viewName";
}
}
xml中的映射将所有请求转发给spring servlet。您仍然可以编写任意数量的
@Controller
s,并使用类级和方法级@RequestMapping
将应用程序拆分为逻辑组件。我可能用一种模棱两可的方式表达了我的问题,但我所寻找的是路径变量。所以我的问题就这样解决了:
@控制器
公共类家庭控制器{
@RequestMapping(value="/{uri}", method={GET})
public String processMappedUri(@PathVariable uri){
return uri;
}
}
使用此解决方案,每当我请求以下请求时,processMappedUri()方法中的uri参数将保存变量值:
- myApplicationContext/home-->uri=home
- myApplicationContext/logout-->uri=注销