java - 请求的资源不可用 - Spring MVC

标签 java spring spring-mvc tomcat

我正在开发基于 Spring MVC 的小型学生应用程序,它应该通过 rest web 服务在 mysql 数据库上实现简单的 CRUD 学生操作。

web.xml:

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

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

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

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

    <context:property-placeholder location="classpath:database.properties" />
    <context:component-scan base-package="com.training.dao" />
    <context:component-scan base-package="com.training.service" />
    <context:component-scan base-package="com.training.controller" />
    <context:component-scan base-package="com.training.bean" />
    <context:component-scan base-package="com.training.dto" />

    <tx:annotation-driven transaction-manager="hibernateTransactionManager" />

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

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${database.driver}" />
        <property name="url" value="${database.url}" />
        <property name="username" value="${database.user}" />
        <property name="password" value="${database.password}" />
    </bean>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedClasses">
            <list>
                <value>com.training.bean.StudentBean</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
            </props>
        </property>
    </bean>

    <bean id="hibernateTransactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>
</beans> 

StudentsController.java:

  package com.training.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

import com.training.bean.StudentBean;
import com.training.dto.ResponseDTO;
import com.training.service.StudentService;

@RestController
@RequestMapping(value = "/student")
@EnableWebMvc
public class StudentController {

    @Autowired
    StudentService studentService;

    ResponseDTO responseDTO;

    @RequestMapping(value = "/get/{id}", method = RequestMethod.GET)
    public @ResponseBody ResponseDTO getStudent(@PathVariable("id") int studentId) {

        try {
            StudentBean student = studentService.getStudent(studentId);
            responseDTO = studentService.converToDTO(true, "success", student, null);
        } catch (Exception e) {
            responseDTO = studentService.converToDTO(false, e.getMessage(), null, null);
        }

        return responseDTO;
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public @ResponseBody ResponseDTO createStudent(@RequestBody StudentBean student) {

        try {
            studentService.addStudent(student);
            responseDTO = studentService.converToDTO(true, "success", null, null);
        } catch (Exception e) {
            responseDTO = studentService.converToDTO(false, e.getMessage(), null, null);
        }
        return responseDTO;
    }

    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    public @ResponseBody ResponseDTO deleteStudent(@PathVariable("id") int studentId) {

        try {
            studentService.deleteStudent(studentId);
            responseDTO = studentService.converToDTO(true, "success", null, null);
        } catch (Exception e) {
            responseDTO = studentService.converToDTO(false, e.getMessage(), null, null);
        }
        return responseDTO;
    }

    @RequestMapping(value = "/getAll", method = RequestMethod.GET)
    public @ResponseBody ResponseDTO getAllStudents() {

        try {
            java.util.List<StudentBean> students = studentService.getAllStudents();
            responseDTO = studentService.converToDTO(true,"success", null, students);
        } catch (Exception e) {
            responseDTO = studentService.converToDTO(false,e.getMessage(), null, null);
        }
        return responseDTO;
    }

    @RequestMapping(value = "/about")
    public String aboutPage() {
        return "about";
    }
}

现在当我打电话时

localhost:8080/student/getAll

或响应的任何映射方法

HTTP Status 404 - /student/getAll The requested resource is not available.

这是 catalina.out,那里没有错误:

    Oct 22, 2016 10:23:17 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
    INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/mvc-dispatcher-servlet.xml]
INFO: Mapped "{[/about/app]}" onto public java.lang.String com.training.controller.AboutController.aboutPage()
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/delete/{id}],methods=[GET]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.deleteStudent(int)
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/get/{id}],methods=[GET]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.getStudent(int)
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/getAll],methods=[GET]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.getAllStudents()
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/about]}" onto public java.lang.String com.training.controller.StudentController.aboutPage()
Oct 22, 2016 10:23:20 AM org.springframework.web.servlet.handler.AbstractHandlerMethodMapping$MappingRegistry register
INFO: Mapped "{[/student/add],methods=[POST]}" onto public com.training.dto.ResponseDTO com.training.controller.StudentController.createStudent(com.training.bean.StudentBean)
Oct 22, 2016 10:23:21 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for @ControllerAdvice: WebApplicationContext for namespace 'dispatcher-servlet': startup date [Sat Oct 22 10:23:17 EEST 2016]; root of context hierarchy
Oct 22, 2016 10:23:21 AM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcher': initialization completed in 3912 ms
Oct 22, 2016 10:23:21 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Oct 22, 2016 10:23:21 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Oct 22, 2016 10:23:21 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 7653 ms

最佳答案

@EnableWebMvc适用于 Spring 配置类(即用 @Configuration 注释的类)。它对您的 Controller 没有任何影响。来自@EnableWebMvc Javadoc 页面的第一行(强调我的):

Adding this annotation to an @Configuration class imports the Spring MVC configuration from WebMvcConfigurationSupport...

由于您使用的是 XML 配置而不是 Java 注释驱动的配置,只需将其添加到您的 mvc-dispatcher-servlet.xml 中:文件:

<mvc:annotation-driven/>

如果没有激活此配置,Spring 会尝试路由到与您的请求映射同名的 View 。由于它不存在,您会收到 404 Not Found 错误。

关于java - 请求的资源不可用 - Spring MVC,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40189547/

相关文章:

java - XPath:如何正确实现XpathResolver

java - android studio更新到3.0.1版本后报错

java - 如何顺利设置布局高度

java - 在 spring 中用 mockings 替换深层次的 Autowiring 依赖

java - 确保基于 Spring 消息传递的 websocket 服务的安全

java - 在基于 Spring MVC 的 Web 应用程序中,如何判断用户是否提交了具有更改值的表单?

java - 我根据 xsd 验证 xml 后如何列出所有错误?

spring - 在springboot中使用gradle时,加载依赖项遇到sun.security.validator.validatorexception。我不知道怎么解决

java - 无法从spring项目连接到mysql数据库

java - 未找到默认构造函数;嵌套异常是 java.lang.NoSuchMethodException 与 Spring MVC?