如何通过类级别RequestMapping调用请求映射方法级别


问题内容

我用spring做了一个简单的程序。当我不使用类级别的RequestMapping时,我得到了方法级别的RequestMapping的答案。但是我想同时使用类级别和方法级别的RequestMapping。

这是我的控制器代码

package com.birthid;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
@RequestMapping("/classLevel")
public class Controaller1 
{
     @RequestMapping("/spring")
     public ModelAndView display(@RequestParam("name") String name)
     {
         ModelAndView model=new ModelAndView("view");
         model.addObject("msg", name);
         return model;
     }      
}

HTML代码

<html>
<head>
   <meta http-equiv="content-type" content="text/html; charset=UTF-8">
   <title>Hello App Engine</title>
</head>

<body>
   <h1>valith web application!</h1>
   <form action="/classLevel" method="get">
      name:<input type="text" name="name"/><br>
      <input type="submit" value="clik me"/>
   </form>
</body>
</html>

当我在地址栏中输入该网址时。我得到确切的输出。http:localhost:8888/classLevel/spring?name=john

但是,当我按我在html页面中设计的按钮时,这给出了错误。


问题答案:

好吧,简单的问题出在您的表单操作上,您action="/classLevel"应该将其归为action="/classLevel/spring"原因是因为您的方法具有/springRequestMapping,所以请更改:

<form action="/classLevel" method="get">

至 :

<form action="/classLevel/spring" method="get">

因为和url测试一样,方法调用应该是:/classLevel/spring

请参阅 Spring Docs的
使用@RequestMapping映射请求
一节以获取更多信息。 __