我在使用带注释的 Controller 和 Spring MVC 时遇到了一个奇怪的问题。我试图将带注释的 Controller 用于 Spring 随其文档一起提供的示例 MVC 应用程序。我用的是2.5版本。
当我在类型级别指定@RequestMapping 时,我得到“HTTP ERROR: 500 处理程序 [Controller 类名称] 没有适配器:您的处理程序是否实现了受支持的接口(interface),如 Controller?
如果我将它包含在方法级别,它可以正常工作而不会出现问题。添加或删除上下文文件的默认句柄适配器没有任何区别:
最后,我求助于在 Controller 级别使用 @RequestMapping,在方法级别使用 @RequestMapping,并且成功了。任何人都知道可能是什么问题?
示例代码如下:
这没有用:
@Controller
@RequestMapping("/*")
public class InventoryController {
protected final Log logger = LogFactory.getLog(getClass());
@Autowired
private ProductManager productManager;
public ModelAndView inventoryHandler() {
String now = (new java.util.Date()).toString();
logger.info("returning hello view with " + now);
Map<String, Object> myModel = new HashMap<String, Object>();
myModel.put("now", now);
myModel.put("products", this.productManager.getProducts());
return new ModelAndView("hello", "model", myModel);
}
}
这有效:
@Controller
public class InventoryController {
protected final Log logger = LogFactory.getLog(getClass());
@Autowired
private ProductManager productManager;
@RequestMapping("/hello.htm")
public ModelAndView inventoryHandler() {
String now = (new java.util.Date()).toString();
logger.info("returning hello view with " + now);
Map<String, Object> myModel = new HashMap<String, Object>();
myModel.put("now", now);
myModel.put("products", this.productManager.getProducts());
return new ModelAndView("hello", "model", myModel);
}
}
这也有效:
@Controller
@RequestMapping("/*")
public class InventoryController {
protected final Log logger = LogFactory.getLog(getClass());
@Autowired
private ProductManager productManager;
@RequestMapping( method = RequestMethod.GET, value = "/hello.htm" )
public ModelAndView inventoryHandler() {
String now = (new java.util.Date()).toString();
logger.info("returning hello view with " + now);
Map<String, Object> myModel = new HashMap<String, Object>();
myModel.put("now", now);
myModel.put("products", this.productManager.getProducts());
return new ModelAndView("hello", "model", myModel);
}
}
任何想法,这里发生了什么?我做了很多搜索,但没有解决方案。我也试过 2.5.6,问题类似。
最佳答案
您需要将 @RequestMapping
放在方法上,因为将它放在类上的信息不够——Spring 需要知道调用哪个方法来处理请求。
如果您的类只有一个方法,那么可以理解,您可能认为它会选择那个方法,但事实并非如此。
考虑到带注释的 Controller 的好处之一是您可以根据需要在您的类中拥有尽可能多的 @RequestMapping
-带注释的方法。
关于java - Spring MVC 和带注释的 Controller 问题 :,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1974963/