简体   繁体   中英

The requested resource is not available - Spring MVC

I am developing small student app, based on Spring MVC which should implement simple CRUD students operations via rest web services onto mysql database.

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";
    }
}

Now when I call for example

localhost:8080/student/getAll

or any of the mapped methods the reponse is

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

Here is catalina.out, no errors there:

    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 applies to Spring configuration classes (ie classes annotated with @Configuration ). It's not having any effect on your controller. From the first line of the @EnableWebMvc Javadoc page (emphasis mine):

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

Since you're using XML configuration instead of Java Annotation driven configuration, simply add this to your mvc-dispatcher-servlet.xml: file:

<mvc:annotation-driven/>

As is, without this configuration active, Spring is trying to route to a view with the same name as your request mapping. Since it doesn't exist, you're getting the 404 Not Found error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM