2016-03-14 128 views
1

有沒有什麼辦法通過property'context-path'爲同一個Spring Boot MVC應用程序設置很多映射?我的目標是避免爲uri映射創建許多「Dispatcherservlet」。Spring Boot中的多個servlet映射

例如:

servlet.context-path =/, /context1, context2 

回答

0

您只需要一個根環境路徑設置爲您想要的(可能是/mySuperApp)的單個Dispatcherservlet。

通過聲明多個@RequestMaping,您將能夠使用相同的DispatcherServlet提供不同的URI。

這裏是一個例子。與@RequestMapping("/service1")設置的DispatcherServlet到/mySuperApp@RequestMapping("/service2")會暴露以下端點:

/mySuperApp/service1

/mySuperApp/service2

有多個上下文單個servket不是Servlet規範的一部分。單個servlet無法從多個上下文中提供服務。

您可以做的是將多個值映射到您的請求映射。

@RequestMapping({ 「/ CONTEXT1 /服務1}」,{ 「/上下文2 /服務1}」)

我沒有看到它周圍的其他方式。

+0

Daniel我不想映射uri控制器,我的目標是爲同一個servlet創建許多上下文映射。 –

+0

這不是Servlet規範的一部分。單個servlet不能從多個上下文中獲得服務器。 您可以做的是將多個值映射到您的請求映射。 @RequestMapping({「/ context1/service1}」,{「/ context2/service1}」) 我沒有看到任何其他方式。 –

+0

如果您查看web.xml描述符,我們可以添加 servlet * .jsp servlet /url

0

您可以使用「server.contextPath」屬性佔位符設置上下文路徑爲整個春季啓動應用程序。 (例如server.contextPath=/live/path1

此外,還可以設置將要施加到所有的方法例如爲:

@RestController 
@RequestMapping(value = "/testResource", produces = MediaType.APPLICATION_JSON_VALUE) 
public class TestResource{ 

@RequestMapping(method = RequestMethod.POST, value="/test", produces = MediaType.APPLICATION_JSON_VALUE) 
    public ResponseEntity<TestDto> save(@RequestBody TestDto testDto) { 
... 

利用這種結構類級別上下文路徑,可以使用/live/path1/testResource/test執行save方法。

+0

但我是如何映射了很多映射一個相同的servlet?這是我的問題。 –

+0

您可以創建一個類並使用不同的映射編寫不同的方法。 –

+0

Darshan,我們可以使用spring引導屬性來創建它,而無需創建新類嗎? –

0

您可以創建@Bean帶註釋的方法,該方法返回ServletRegistrationBean,並在其中添加多個映射。這是更可取的方法,因爲Spring引導鼓勵Java的配置,而不是配置文件:

@Bean 
    public ServletRegistrationBean myServletRegistration() 
    { 
     String urlMapping1 = "/mySuperApp/service1/*"; 
     String urlMapping2 = "/mySuperApp/service2/*"; 
     ServletRegistrationBean registration = new ServletRegistrationBean(new MyBeautifulServlet(), urlMapping1, urlMapping2); 

     //registration.set... other properties may be here 
     return registration; 
    } 

在應用程序啓動,你就可以在日誌中看到:

INFO | localhost | org.springframework.boot.web.servlet.ServletRegistrationBean | Mapping servlet: 'MyBeautifulServlet' to [/mySuperApp/service1/*, /mySuperApp/service2/*]