📜  Spring MVC-简单的网址处理程序映射示例

📅  最后修改于: 2020-11-11 06:29:38             🧑  作者: Mango


以下示例显示了如何通过Spring Web MVC框架使用简单URL处理程序映射。 SimpleUrlHandlerMapping类有助于分别使用其控制器显式映射URL。


   
      
      
   

   
      
         
            welcomeController           
            helloController
         
      
   

   

     

例如,使用上面的配置,如果是URI

  • /helloWorld.htm被请求,DispatcherServlet会将请求转发到HelloController

  • /welcome.htm是请求的,DispatcherServlet会将请求转发到WelcomeController

首先,让我们拥有一个运行良好的Eclipse IDE,并考虑以下步骤,以使用Spring Web Framework开发基于动态表单的Web应用程序。

Step Description
1 Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter.
2 Create Java classes HelloController and WelcomeController under the com.tutorialspoint package.
3 Create view files hello.jsp and welcome.jsp under the jsp sub-folder.
4 The final step is to create the content of the source and configuration files and export the application as explained below.

HelloController.java

package com.tutorialspoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class HelloController extends AbstractController{
  
   @Override
   protected ModelAndView handleRequestInternal(HttpServletRequest request,
      HttpServletResponse response) throws Exception {
      ModelAndView model = new ModelAndView("hello");
      model.addObject("message", "Hello World!");
      return model;
   }
}

WelcomeController.java

package com.tutorialspoint;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class WelcomeController extends AbstractController{
  
   @Override
   protected ModelAndView handleRequestInternal(HttpServletRequest request,
      HttpServletResponse response) throws Exception {
      ModelAndView model = new ModelAndView("welcome");
      model.addObject("message", "Welcome!");
      return model;
   }
}

TestWeb-servlet.xml



   
      
      
   

   
      
         
            welcomeController           
            helloController
         
      
   

   

      

hello.jsp

Hello World
   
   
      

${message}

welcome.jsp

Welcome
   
   
      

${message}

完成创建源文件和配置文件后,导出应用程序。右键单击您的应用程序,使用“导出”→“ WAR文件”选项,然后将您的TestWeb.war文件保存在Tomcat的webapps文件夹中。

现在,启动Tomcat服务器,并确保您能够使用标准浏览器从webapps文件夹访问其他网页。尝试使用URL- http:// localhost:8080 / TestWeb / helloWorld.htm ,如果Spring Web Application一切正常,我们将看到以下屏幕。

Spring Controller类名处理程序映射1

尝试使用URL http:// localhost:8080 / TestWeb / welcome.htm ,如果Spring Web Application一切正常,您应该看到以下结果。

Spring Controller类名处理程序映射2