gpt4 book ai didi

java - 为什么 Spring RequestMapping 没有 @Controller 就无法工作?

转载 作者:行者123 更新时间:2023-12-01 11:20:30 25 4
gpt4 key购买 nike

我有示例代码:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" version="3.0">

<servlet>
<servlet-name>springDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>springDispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

</web-app>

springDispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd">
<bean id="myController" class="biz.tugay.springWebOne.MyController"/>
</beans>

MyController.java

package biz.tugay.springWebOne;
/* User: koray@tugay.biz Date: 08/07/15 Time: 15:25 */

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class MyController {
@RequestMapping(value = "/hello")
public String helloWorld(){
return "index.jsp";
}
}

嗯,这段代码一切正常。但是当我删除

 @Controller

MyController 类我将得到:

HTTP ERROR 404

Problem accessing /hello. Reason:

Not Found

我没有使用组件扫描,我使用的是基于 xml 的配置。为什么需要 @Controller 注解?

最佳答案

来自 spring 引用文档 here

The @Controller annotation acts as a stereotype for the annotated class, indicating its role. The dispatcher scans such annotated classes for mapped methods and detects @RequestMapping annotations

因此,@Controller需要告诉调度程序扫描此类中的映射,而不仅仅是组件扫描。

关于java - 为什么 Spring RequestMapping 没有 @Controller 就无法工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31294068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com