【问题标题】:Spring MVC 3.0 404 errorSpring MVC 3.0 404 错误
【发布时间】:2011-10-04 17:07:14
【问题描述】:

我正在尝试使用动态 Web 项目在 Eclipse 中使用 Spring MVC 3.0 构建应用程序。我能够进入初始页面,但我无法从那里导航到任何其他页面而不会出现 404 错误,并且我没有在控制器类中遇到任何断点。如果有什么我遗漏的,请告诉我。谢谢!

applicationContext.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"  xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

    <!-- Activates various annotations to be detected in bean classes -->
    <context:annotation-config />

    <!-- Scans the classpath for annotated components that will be auto-registered 
        as Spring beans. For example @Controller and @Service. Make sure to set the 
        correct base-package -->
    <context:component-scan base-package="src" />

    <!-- Configures the annotation-driven Spring MVC Controller programming 
        model. Note that, with Spring 3.0, this tag works in Servlet MVC only! -->
    <mvc:annotation-driven />

    <!-- Load Hibernate related configuration -->
    <import resource="hibernate-context.xml" />

</beans>

spring-servlet.xml 代码:

<?xml version="1.0" encoding="UTF-8"?>
<beans xsi:schemaLocation=" http://www.springframework.org/schema/beans 
       ...
        xmlns:mvc="http://www.springframework.org/schema/mvc"  
        xmlns:aop="http://www.springframework.org/schema/aop" 
        xmlns:context="http://www.springframework.org/schema/context" 
        xmlns:p="http://www.springframework.org/schema/p" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns="http://www.springframework.org/schema/beans"> 

    <bean
        class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />

    <bean
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />


    <!-- Declare a view resolver -->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
           <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
           <property name="prefix" value="/WEB-INF/jsp"/>
           <property name="suffix" value=".jsp"/>
        </bean>


</beans>

web.xml 代码:

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

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

    <servlet-mapping>
        <servlet-name>spring</servlet-name>
        <url-pattern>/SpringHibernateExample/*</url-pattern>
    </servlet-mapping>

     <welcome-file-list>
        <welcome-file>/jsp/personspage.jsp</welcome-file>
    </welcome-file-list>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

</web-app>

MainController.java 代码:

package controller;

import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import service.PersonService;
import domain.Person;

/**
 * Handles and retrieves person request
 */
@Controller
@RequestMapping("/main")
public class MainController {

    protected static Logger logger = Logger.getLogger("controller");

    @Resource(name = "personService")
    private PersonService personService;

    /**
     * Handles and retrieves all persons and show it in a JSP page
     * 
     * @return the name of the JSP page
     */
    @RequestMapping(value = "/persons", method = RequestMethod.GET)
    public String getPersons(Model model) {

        logger.debug("Received request to show all persons");

        // Retrieve all persons by delegating the call to PersonService
        List<Person> persons = personService.getAll();

        // Attach persons to the Model
        model.addAttribute("persons", persons);

        // This will resolve to /WEB-INF/jsp/personspage.jsp
        return "personspage";
    }

    /**
     * Retrieves the add page
     * 
     * @return the name of the JSP page
     */
    @RequestMapping(value = "/persons/add", method = RequestMethod.GET)
    public String getAdd(Model model) {
        logger.debug("Received request to show add page");

        // Create new Person and add to model
        // This is the formBackingOBject
        model.addAttribute("personAttribute", new Person());

        // This will resolve to /WEB-INF/jsp/addpage.jsp
        return "addpage";
    }

    /**
     * Adds a new person by delegating the processing to PersonService. Displays
     * a confirmation JSP page
     * 
     * @return the name of the JSP page
     */
    @RequestMapping(value = "/persons/add", method = RequestMethod.POST)
    public String add(@ModelAttribute("personAttribute") Person person) {
        logger.debug("Received request to add new person");

        // The "personAttribute" model has been passed to the controller from
        // the JSP
        // We use the name "personAttribute" because the JSP uses that name

        // Call PersonService to do the actual adding
        personService.add(person);

        // This will resolve to /WEB-INF/jsp/addedpage.jsp
        return "addedpage";
    }

    /**
     * Deletes an existing person by delegating the processing to PersonService.
     * Displays a confirmation JSP page
     * 
     * @return the name of the JSP page
     */
    @RequestMapping(value = "/persons/delete", method = RequestMethod.GET)
    public String delete(
            @RequestParam(value = "id", required = true) Integer id, Model model) {

        logger.debug("Received request to delete existing person");

        // Call PersonService to do the actual deleting
        personService.delete(id);

        // Add id reference to Model
        model.addAttribute("id", id);

        // This will resolve to /WEB-INF/jsp/deletedpage.jsp
        return "deletedpage";
    }

    /**
     * Retrieves the edit page
     * 
     * @return the name of the JSP page
     */
    @RequestMapping(value = "/persons/edit", method = RequestMethod.GET)
    public String getEdit(
            @RequestParam(value = "id", required = true) Integer id, Model model) {
        logger.debug("Received request to show edit page");

        // Retrieve existing Person and add to model
        // This is the formBackingOBject
        model.addAttribute("personAttribute", personService.get(id));

        // This will resolve to /WEB-INF/jsp/editpage.jsp
        return "editpage";
    }

    /**
     * Edits an existing person by delegating the processing to PersonService.
     * Displays a confirmation JSP page
     * 
     * @return the name of the JSP page
     */
    @RequestMapping(value = "/persons/edit", method = RequestMethod.POST)
    public String saveEdit(@ModelAttribute("personAttribute") Person person,
            @RequestParam(value = "id", required = true) Integer id, Model model) {
        logger.debug("Received request to update person");

        // The "personAttribute" model has been passed to the controller from
        // the JSP
        // We use the name "personAttribute" because the JSP uses that name

        // We manually assign the id because we disabled it in the JSP page
        // When a field is disabled it will not be included in the
        // ModelAttribute
        person.setId(id);

        // Delegate to PersonService for editing
        personService.edit(person);

        // Add id reference to Model
        model.addAttribute("id", id);

        // This will resolve to /WEB-INF/jsp/editedpage.jsp
        return "editedpage";
    }

}

personspage.jsp 代码:

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>People Page</title>
</head>
<body>
<h1>Persons</h1>

<c:url var="addUrl" value="/main/persons/add" />
<table style="border: 1px solid; width: 500px; text-align:center">
    <thead style="background:#fcf">
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Money</th>
            <th colspan="3"></th>
        </tr>
    </thead>
    <tbody>
    <c:forEach items="${persons}" var="person">
            <c:url var="editUrl" value="/persons/edit?id=${person.id}" />
            <c:url var="deleteUrl" value="/persons/delete?id=${person.id}" />
        <tr>
            <td><c:out value="${person.firstName}" /></td>
            <td><c:out value="${person.lastName}" /></td>
            <td><c:out value="${person.money}" /></td>
            <td><a href="${editUrl}">Edit</a></td>
            <td><a href="${deleteUrl}">Delete</a></td>
            <td><a href="${addUrl}">Add</a></td>
        </tr>
    </c:forEach>
    </tbody>
</table>

<c:if test="${empty persons}">
    There are currently no persons in the list. <a href="${addUrl}">Add</a> a person.
</c:if>

</body>
</html>

【问题讨论】:

    标签: model-view-controller spring http-status-code-404


    【解决方案1】:

    这可能是您的问题:

    <context:component-scan base-package="src" />
    

    您应该为“base-package”输入您的基本包名称。例如

    <context:component-scan base-package="com.stackoverflow.project" />
    

    其中“com.stackoverflow.project”是您在控制器中使用的包名称。

    例如:控制器类:

    package com.stackoverflow.project.controller
    
    @Controller
    public class DashboardController { ...
    

    希望对您有所帮助。

    【讨论】:

    • 谢谢,这很有帮助,但是,如果我在 src 下只有一个名为 controller 的文件夹(如我的控制器类中所示),那么基本包应该是什么?它应该是“控制器”吗?如果是,Spring 是否能够看到我的其他类?
    猜你喜欢
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2012-06-05
    • 2011-08-16
    • 2013-09-18
    • 2013-08-14
    • 2014-05-15
    相关资源
    最近更新 更多