简体   繁体   中英

Spring mvc controller doesn't work

I have simple Spring MVC project and as I see Controller doesn't work After running page http://localhost:8080/story/list shows HTTP Status 404 - But when I'm running TestDbServlet all works fine (mapped http://localhost:8080/TestDbServlet )

Project Structure Screenshot

web.xml file

 <?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 file

 <?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); } } } 

Looks like you forgot to add ContextLoaderListener thus your initial view resolver is not loaded.

Try to add following strings to your web.xml:

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

It should solve your issue. At least I have checked it on my local and it starts to work.

Also make sure that spring-web jar is added to your lib directory in war file. 在此处输入图片说明

Good luck.

Try this

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

Or if your spring version allows you:

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

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

hope this helps

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