Spring mvc 控制器不工作

Spring mvc controller doesn't work

我有一个简单的 Spring MVC 项目,据我所知,控制器不起作用 运行 页面 http://localhost:8080/story/list 后显示 HTTP 状态 404 - 但是当我 运行 TestDbServlet 时一切正常(映射 http://localhost:8080/TestDbServlet

Project Structure Screenshot

web.xml 文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="
         http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <display-name>jeremy</display-name>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>

    <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/applicationContext.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>

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

    <!--component scanning-->
    <context:component-scan base-package="com.aalegz.jeremy" />

    <!-- Add support for conversion, formatting and validation support -->
    <mvc:annotation-driven/>

    <!--Define Spring MVC View resolver-->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!--Step 1: Define database / DataSource connection pool-->
    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
          destroy-method="close">
        <property name="driverClass" value="com.mysql.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/stories_manager?useSSL=false" />
        <property name="user" value="manager" />
        <property name="password" value="manager" />

        <!-- these are connection pool properties for C3P0 -->
        <property name="minPoolSize" value="5" />
        <property name="maxPoolSize" value="20" />
        <property name="maxIdleTime" value="30000" />
    </bean>

    <!--Step 2: Setup Hibernate Session Factory-->
    <bean id="sessionFactory"
          class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="packagesToScan" value="com.aalegz.jeremy.entity" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
            </props>
        </property>
    </bean>

    <!--Step 3: Setup Hibernate transaction manager-->
    <bean id="myTransactionManager"
          class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>

    <!--Step 4: Enable configuration of transactional behavior based on annotations-->
    <tx:annotation-driven transaction-manager="myTransactionManager"/>

</beans>

StoryController.java @Controller class

package com.aalegz.jeremy.controller;

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

@Controller
@RequestMapping("/story")
public class StoryController {

    @RequestMapping("/list")
    public String listStories(Model theModel) {
        System.out.println("Showing page..");
        return "list-stories";
    }
}

TestDbServlet

package com.aalegz.testdb;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;

@WebServlet("/TestDbServlet")
public class TestDbServlet extends javax.servlet.http.HttpServlet {

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        //setuo connection variables
        String user = "manager";
        String password = "manager";

        String jdbcUrl = "jdbc:mysql://localhost:3306/stories_manager?useSSL=false";
        // ?serverTimezone=UTC
        String driver = "com.mysql.jdbc.Driver";

        //get connection to database

        try {

            PrintWriter out = response.getWriter();

            out.println("Connecting to DB: " + jdbcUrl);

            Class.forName(driver);

            Connection myConn = DriverManager.getConnection(jdbcUrl, user, password);

            out.println("Connection successful!");

            myConn.close();

        } catch (Exception e) {
            e.printStackTrace();
            throw new ServletException(e);
        }
    }
}

试试这个

package com.aalegz.jeremy.controller;

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

@Controller
@RequestMapping("/story")
public class StoryController {

    @GetMapping("/list", produces = "application/json")
    public @ResponseBody String listStories(Model theModel) {
        System.out.println("Showing page..");
        return "list-stories";
    }
}

或者如果您的 spring 版本允许您:

@RestController
@RequestMapping("story")
public class StoryController {

    @GetMapping("/list", produces = "application/json")
    public String listStories(Model theModel) {
        System.out.println("Showing page..");
        return "list-stories";
    }
}

希望这对您有所帮助

您似乎忘记添加 ContextLoaderListener,因此未加载您的初始视图解析器。

尝试将以下字符串添加到您的 web.xml:

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

它应该可以解决您的问题。 至少我已经在本地检查过了,它开始工作了。

还要确保 spring-web jar 已添加到 lib 目录中的 war 文件中。

祝你好运。