Spring MVC Controller映射不起作用

时间:2016-11-23 06:55:46

标签: java spring spring-mvc tomcat web-applications

我正在开发一个spring-mvc项目。经过多次尝试,我无法在春天映射控制器。因此,以下网址始终返回为404未找到。

http://localhost:8080/EcommerceBookStore/rest/welcome

这是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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>EcommerceBookStore</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>
  
    <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                /WEB-INF/applicationContext.xml,
                /WEB-INF/Ecommerce-servlet.xml
            </param-value>
    </context-param>
    
 	<servlet>
        <servlet-name>Ecommerce</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Ecommerce</servlet-name>
        <url-pattern>/rest/</url-pattern>
    </servlet-mapping>
   
   

  
<!--  <servlet>
    <servlet-name>Ecommerce</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.java.Client</param-name>
        <param-value>com.java.Client</param-value>
    </init-param>
    <init-param>
    	<param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
    	<param-value>true</param-value>
  	</init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>-->
  
  
</web-app>

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

	
	
	<mvc:default-servlet-handler/>
	
    <mvc:annotation-driven>
        <mvc:argument-resolvers>
            <bean class="org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver" />
        </mvc:argument-resolvers>
    </mvc:annotation-driven>

    <!-- bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WebContent" />
        <property name="suffix" value=".jsp" />
    </bean-->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.UrlBasedViewResolver">
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<property name="prefix" value="/WEB-INF/jsp/" />
		<property name="suffix" value=".jsp" />
	</bean>
    <mvc:annotation-driven />
    <context:component-scan base-package="com.webspider"/>
	
    <mvc:resources mapping="/Resources/**" location="/Resources/" />
   

</beans>

这是

<?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:security="http://www.springframework.org/schema/security"
       xmlns:webflow-config="http://www.springframework.org/schema/webflow-config"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security.xsd http://www.springframework.org/schema/webflow-config http://www.springframework.org/schema/webflow-config/spring-webflow-config.xsd">

	<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource"
		id="dataSource">
		<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
		<property name="url" value="jdbc:mysql://localhost:3306/Ecommerce"></property>
		<property name="username" value="root"></property>
		<property name="password" value="pass"></property>
	</bean>
	
    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" >
        <property name="dataSource" ref="dataSource"></property>
        <property name="hibernateProperties" >
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
            </props>
        </property>
        <property name="packagesToScan">
            <list>
                <value>com.webspider</value>
            </list>
        </property>
    </bean>

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

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="10240000" />
    </bean>

    <security:http auto-config="true">
        <security:intercept-url pattern="/admin/**" access="ROLE_ADMIN" />
        <security:intercept-url pattern="/customer/**" access="ROLE_USER" />
        <security:form-login
            login-page="/login"
            default-target-url="/product/productList"
            authentication-failure-url="/login?error"
            username-parameter="username"
            password-parameter="password" />
        <security:logout
            logout-success-url="/login?logout" />
    </security:http>

    <security:authentication-manager>
        <security:authentication-provider>
            <security:jdbc-user-service
                    data-source-ref="dataSource"
                    authorities-by-username-query="SELECT username, authority FROM authorities WHERE username = ?"
                    users-by-username-query="SELECT username, password, enabled FROM users WHERE username = ?" />
        </security:authentication-provider>
    </security:authentication-manager>

    <webflow-config:flow-executor id="flowExecutor" flow-registry="flowRegistry" />
    
    <webflow-config:flow-registry id="flowRegistry" base-path="/WEB-INF/flows">
        <webflow-config:flow-location path="/checkout/checkout-flow.xml" id="checkout" />
    </webflow-config:flow-registry>

    <bean id="flowHandlerMapping" class="org.springframework.webflow.mvc.servlet.FlowHandlerMapping">
        <property name="flowRegistry" ref="flowRegistry" />
    </bean>

    <bean id="flowHandlerAdapter" class="org.springframework.webflow.mvc.servlet.FlowHandlerAdapter">
        <property name="flowExecutor" ref="flowExecutor" />
    </bean>

</beans>

这是helloworld控制器

    package com.webspider.Controller;


    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.servlet.ModelAndView;

   /*
    * author: Crunchify.com
    * 
    */

@Controller
public class HelloWorld {

    @RequestMapping("/welcome")
    public ModelAndView helloWorld() {

        String message = "<br><div style='text-align:center;'>"
                + "<h3>********** Hello World, Spring MVC Tutorial</h3>This message is coming from CrunchifyHelloWorld.java **********</div><br><br>";
        return new ModelAndView("welcome", "message", message);
    }
}

这是tomcat输出

Nov 23, 2016 12:41:14 AM org.apache.catalina.startup.VersionLoggerListener log
INFO: Command line argument: -Dfile.encoding=UTF-8
Nov 23, 2016 12:41:14 AM org.apache.catalina.core.AprLifecycleListener lifecycleEvent
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: /Users/atishpatra/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.
Nov 23, 2016 12:41:15 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-nio-8080"]
Nov 23, 2016 12:41:15 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Nov 23, 2016 12:41:15 AM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-nio-8009"]
Nov 23, 2016 12:41:15 AM org.apache.tomcat.util.net.NioSelectorPool getSharedSelector
INFO: Using a shared selector for servlet write/read
Nov 23, 2016 12:41:15 AM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 972 ms
Nov 23, 2016 12:41:15 AM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Nov 23, 2016 12:41:15 AM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/8.0.38
Nov 23, 2016 12:41:18 AM org.apache.jasper.servlet.TldScanner scanJars
INFO: At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.
Nov 23, 2016 12:41:18 AM org.apache.catalina.core.ApplicationContext log
INFO: No Spring WebApplicationInitializer types detected on classpath
Nov 23, 2016 12:41:18 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'Ecommerce'
Nov 23, 2016 12:41:18 AM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'Ecommerce': initialization started
Nov 23, 2016 12:41:18 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'Ecommerce-servlet': startup date [Wed Nov 23 00:41:18 CST 2016]; root of context hierarchy
Nov 23, 2016 12:41:18 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/Ecommerce-servlet.xml]
Nov 23, 2016 12:41:19 AM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping' with a different definition: replacing [Root bean: class [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
Nov 23, 2016 12:41:19 AM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter' with a different definition: replacing [Root bean: class [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
Nov 23, 2016 12:41:19 AM org.springframework.beans.factory.support.DefaultListableBeanFactory registerBeanDefinition
INFO: Overriding bean definition for bean 'mvcUriComponentsContributor' with a different definition: replacing [Root bean: class [org.springframework.web.servlet.config.AnnotationDrivenBeanDefinitionParser$CompositeUriComponentsContributorFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Root bean: class [org.springframework.web.servlet.config.AnnotationDrivenBeanDefinitionParser$CompositeUriComponentsContributorFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
Nov 23, 2016 12:41:19 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/**] onto handler 'org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler#0'
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Nov 23, 2016 12:41:20 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for @ControllerAdvice: WebApplicationContext for namespace 'Ecommerce-servlet': startup date [Wed Nov 23 00:41:18 CST 2016]; root of context hierarchy
Nov 23, 2016 12:41:20 AM org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter initControllerAdviceCache
INFO: Looking for @ControllerAdvice: WebApplicationContext for namespace 'Ecommerce-servlet': startup date [Wed Nov 23 00:41:18 CST 2016]; root of context hierarchy
Nov 23, 2016 12:41:20 AM org.springframework.web.servlet.handler.AbstractUrlHandlerMapping registerHandler
INFO: Mapped URL path [/Resources/**] onto handler 'org.springframework.web.servlet.resource.ResourceHttpRequestHandler#0'
Nov 23, 2016 12:41:20 AM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'Ecommerce': initialization completed in 2089 ms
Nov 23, 2016 12:41:21 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-nio-8080"]
Nov 23, 2016 12:41:21 AM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-nio-8009"]
Nov 23, 2016 12:41:21 AM org.apache.catalina.startup.Catalina start
INFO: Server startup in 5855 ms

我没有在tomcat输出中看到任何错误。我期待类似的东西出现

INFO:映射的URL路径[/ welcome]到处理程序HelloWorld。

我不知道出了什么问题。任何人都可以指出我错过了什么吗?

提前致谢。

2 个答案:

答案 0 :(得分:0)

我想你在这里好坏参半:

如果您的项目名称已经休息,并且您将其部署为rest.war,那么您在web.xml中不需要这一行

<url-pattern>/rest/</url-pattern>

将其更改为

<url-pattern>/</url-pattern>

但如果您使用ROOT.war运行它并且想要/在网址中休息,那么您必须执行以下操作:

@Controller
@RequestMapping("/rest")
public class HelloWorld {

然后使用以下网址访问: 本地主机:8080 //其余/欢迎

答案 1 :(得分:0)

尝试以下,

@RequestMapping("/welcome", method = RequestMethod.GET)
public ModelAndView helloWorld() {...

确保您的映射是,

<servlet-mapping>
    <servlet-name>Ecommerce</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

将您的默认servlet名称自定义为

 <mvc:default-servlet-handler default-servlet-name="Ecommerce"/>

尝试访问的网址:localhost:8080 /电子商务/欢迎