0

我有一些问题。我正在使用 Spring Tool Suit 构建一个应用程序,由 SpringMVC Maven 和 Hibernate 组成。我认为我的所有编码都可以或接近于良好,尽管我是春天的菜鸟。

在这里,我放了我项目的 2 个屏幕:

http://i.stack.imgur.com/AzhOd.png

http://i.stack.imgur.com/fBRId.png

在这里,我把我认为与该问题有关的文件

应用程序-config.mxl:

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


         <context:component-scan base-package="org.springframework.samples.service"/>

</beans>

通用控制器.java:

package controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import form.Egg;
import service.EggService;

@Controller
//@RequestMapping("/ChickenTest/**")
public class GeneralController {

    @Autowired
    EggService eggService;

    @RequestMapping(value="/index")
    public ModelAndView index(){
        ModelAndView mav = new ModelAndView();

        return mav;
    }

    //Index of Egg webpage
    @RequestMapping(value="/Egg/indexEgg")
    public ModelAndView indexEgg(){
        ModelAndView mav = new ModelAndView();

        return mav;
    }

    //Action of adding an Egg
    @RequestMapping(value="/Egg/addEgg", method = RequestMethod.POST)
    public ModelAndView addEgg(@ModelAttribute Egg egg){
        ModelAndView mav = new ModelAndView("/index");

        Egg eggAux = egg;
        eggService.addEgg(eggAux);

        return mav;
    }

    //View list of eggs
    @RequestMapping(value="/Egg/viewEggs", method = RequestMethod.POST)
    public ModelAndView viewEggs(){
        ModelAndView mav = new ModelAndView("/index");

        mav.getModelMap().addAttribute("eggList", eggService.viewEggs());

        return null;
    }



    @RequestMapping(value="/Chicken/indexChicken")
    ModelAndView indexChicken(){
        ModelAndView mav = new ModelAndView();

        return mav;
    }

    @RequestMapping(value="/Farm/indexFarm")
    ModelAndView indexFarm(){
        ModelAndView mav = new ModelAndView();

        return mav;
    }
}

网页.xml:

<?xml version="1.0" encoding="ISO-8859-1"?>
<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"
         id="WebApp_ID" version="2.5">

    <display-name>ChickenTest</display-name>

   <!--
        - Location of the XML file that defines the root application context.
        - Applied by ContextLoaderListener.
    -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/application-config.xml</param-value>
    </context-param>

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


    <!--
        - Servlet that dispatches request to registered handlers (Controller implementations).
    -->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/mvc-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

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

</web-app>

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


         <context:component-scan
            base-package="org.springframework.samples.web"/>


    <mvc:annotation-driven />

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <!-- Example: a logical view name of 'showMessage' is mapped to '/WEB-INF/jsp/showMessage.jsp' -->
            <property name="prefix" value="/WEB-INF/view/"/>
            <property name="suffix" value=".jsp"/>
    </bean>

</beans>

这是我尝试输入我的 jsp 之一时控制台输出的内容:

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.
[INFO] Scanning for projects...
[INFO]                                                                         
[INFO] ------------------------------------------------------------------------
[INFO] Building ChickenTest 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] >>> tomcat-maven-plugin:1.1:run (default-cli) @ ChickenTest >>>
[INFO] 
[INFO] --- maven-resources-plugin:2.5:resources (default-resources) @ ChickenTest ---
[debug] execute contextualize
[INFO] Using 'UTF-8' encoding to copy filtered resources.
[INFO] Copying 2 resources
[INFO] 
[INFO] --- maven-compiler-plugin:2.3.2:compile (default-compile) @ ChickenTest ---
[INFO] Compiling 16 source files to C:\Java\workspace2\ChickenTest\target\classes
[INFO] 
[INFO] <<< tomcat-maven-plugin:1.1:run (default-cli) @ ChickenTest <<<
[INFO] 
[INFO] --- tomcat-maven-plugin:1.1:run (default-cli) @ ChickenTest ---
[INFO] Running war on http://localhost:8080/ChickenTest
[INFO] Using existing Tomcat server configuration at C:\Java\workspace2\ChickenTest\target\tomcat
Nov 08, 2013 12:31:45 AM org.apache.catalina.startup.Embedded start
INFO: Starting tomcat server
Nov 08, 2013 12:31:45 AM org.apache.catalina.core.StandardEngine start
INFO: Starting Servlet Engine: Apache Tomcat/6.0.29
Nov 08, 2013 12:31:45 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring root WebApplicationContext
Nov 08, 2013 12:31:45 AM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization started
Nov 08, 2013 12:31:45 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing Root WebApplicationContext: startup date [Fri Nov 08 00:31:45 ART 2013]; root of context hierarchy
Nov 08, 2013 12:31:45 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [spring/application-config.xml]
Nov 08, 2013 12:31:45 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@767ae5: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
Nov 08, 2013 12:31:45 AM org.springframework.web.context.ContextLoader initWebApplicationContext
INFO: Root WebApplicationContext: initialization completed in 245 ms
Nov 08, 2013 12:31:45 AM org.apache.catalina.core.ApplicationContext log
INFO: Initializing Spring FrameworkServlet 'dispatcherServlet'
Nov 08, 2013 12:31:45 AM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcherServlet': initialization started
Nov 08, 2013 12:31:45 AM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing WebApplicationContext for namespace 'dispatcherServlet-servlet': startup date [Fri Nov 08 00:31:45 ART 2013]; parent: Root WebApplicationContext
Nov 08, 2013 12:31:45 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from ServletContext resource [/WEB-INF/mvc-config.xml]
Nov 08, 2013 12:31:45 AM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@132299b: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,mvcContentNegotiationManager,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#0,org.springframework.format.support.FormattingConversionServiceFactoryBean#0,org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#0,org.springframework.web.servlet.handler.MappedInterceptor#0,org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver#0,org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver#0,org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver#0,org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping,org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter,org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter,org.springframework.web.servlet.view.InternalResourceViewResolver#0,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; parent: org.springframework.beans.factory.support.DefaultListableBeanFactory@767ae5
Nov 08, 2013 12:31:46 AM org.springframework.web.servlet.FrameworkServlet initServletBean
INFO: FrameworkServlet 'dispatcherServlet': initialization completed in 384 ms
Nov 08, 2013 12:31:46 AM org.apache.coyote.http11.Http11Protocol init
INFO: Initializing Coyote HTTP/1.1 on http-8080
Nov 08, 2013 12:31:46 AM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080

最后,这是资源管理器在我尝试输入此 url http://localhost:8080/ChickenTest/index.jsp 时显示的内容

HTTP Status 404 - /ChickenTest/index.jsp

type Status report

message /ChickenTest/index.jsp

description The requested resource (/ChickenTest/index.jsp) is not available.

Apache Tomcat/6.0.29

谢谢阅读!如果您需要更多东西,我会与您联系!


更新1:

你好,我应用了这个解决方案:

First, your @Controller class is in

package controller;
so your DispatcherServlet config needs to have a component-scan on that package. So change yours to

<context:component-scan base-package="controller"/>
So that the <mvc:annotation-driven> gets applied and your @Controller class is added as a handler.

Now even if you do this, you still don't seem to have a handler method for the path

/ChickenTest/index.jsp
You'll want to either add a <welcome-file> to your web.xml and an index.jsp file in your /webapps folder or add a @RequestMapping handler method that can handler /index.jsp.

但现在控制台告诉我 GeneralController.class 上的 @Autowire 不起作用。

这是我的新错误:

SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'generalController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.chicken.service.EggService com.chicken.controller.GeneralController.eggService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.chicken.service.EggService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
4

1 回答 1

0

首先,你的@Controller班级在

package controller;

所以你的DispatcherServlet配置需要component-scan在那个包上有一个。所以改变你的

<context:component-scan base-package="controller"/>

这样就<mvc:annotation-driven>可以应用并将您的@Controller类添加为处理程序。

现在即使你这样做了,你似乎仍然没有路径的处理程序方法

/ChickenTest/index.jsp

您需要将 a 添加<welcome-file>到您的 web.xml 和index.jsp文件/webapps夹中的文件,或者添加一个@RequestMapping可以处理程序的处理程序方法/index.jsp


您现在得到的异常是(分解)

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'generalController': 
Injection of autowired dependencies failed; 

nested exception is org.springframework.beans.factory.BeanCreationException: 
Could not autowire field: com.chicken.service.EggService com.chicken.controller.GeneralController.eggService; 

nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [com.chicken.service.EggService] found for dependency: 
expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

因此,组件扫描无法为其创建 bean,GeneralController因为 Spring 上下文找不到EggService需要注入的 bean。唯一可能的原因是您的上下文中没有EggServicebean。要么你没有声明为 a <bean>,要么你component-scan没有扫描你的EggService类声明为 a的包@Component

于 2013-11-08T04:31:24.567 回答