请求未映射到控制器

时间:2016-06-15 10:16:20

标签: spring spring-mvc http-status-code-404 request-mapping

当我使用url .. http://localhost:8080/springdemo/hello ..它显示404未找到错误..我已经将我的java文件放在src / main / java中,就像在Maven项目中一样。我的控制器代码如下: -

package org.abhishek;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import java.lang.System;

@Controller
public class HelloWorldController {
    @RequestMapping(value="/hello", method = RequestMethod.GET)
    public ModelAndView helloWorld() {
        System.out.println("hello**");
        String message = "Hello World, Spring MVC @ Javatpoint";
        return new ModelAndView("hello", "message", message);
    }
}

下面给出的Web.xml文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="java.sun.com/xml/ns/javaee"; xmlns:xsi="w3.org/2001/XMLSchema-instance"; xsi:schemaLocation="java.sun.com/xml/ns/javaee java.sun.com/xml/ns/javaee/web-app_2_5.xsd">;
    <servlet>
        <servlet-name>spring</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
</web-app>

我把这行System.out.println()用于调试目的,我发现这个方法没有用上面提到的url执行...即。 http://localhost:8080/springdemo/hello。请提前回答。谢谢。

1 个答案:

答案 0 :(得分:1)

这是推测性的,但是你的web.xml文件中可能存在映射问题,这会导致Spring控制器甚至没有被命中(尽管有一个正确的@RequestMapping注释)。您的web.xml文件应具有以下servlet映射:

<servlet>
    <servlet-name>springServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>springServlet</servlet-name>
    <url-pattern>/springdemo/*</url-pattern>
</servlet-mapping>

现在将您的网址粘贴到网络浏览器中,看看是否可以点击它:

http://localhost:8080/springdemo/hello