【问题标题】:Java Spring Web MVC application: Failed to create controllerJava Spring Web MVC 应用程序:无法创建控制器
【发布时间】:2022-01-27 18:14:40
【问题描述】:

我希望有人可以帮助我,我开始使用 Spring MVC。

我有一个带有以下包的 java spring MVC Web 应用程序:com.app.controllercom.app.modelocom.app.servicio、y com.app.repositorio。在repositorio 包中我有UsuarioRepositorio 接口,在servicio 包中我有UsuarioServicio 类。控制器使用UsuarioServicio 类,而这个使用UsuarioRepositorio 接口。控制器在其构造函数中初始化UsuarioServicio 对象。运行项目时显示此错误:

该模块尚未部署。 有关详细信息,请参阅服务器日志。

[Payara 5.2021.10] [GRAVE] [] [javax.enterprise.system.core] [tid: _ThreadID=90 _ThreadName=admin-thread-pool::admin-listener(1)] [timeMillis: 1643303084394] [级别值:1000] [[ 加载应用程序时出现异常:java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: java.lang.NoSuchMethodException: com.app.controller.UsuarioController.() ]]

UsuarioRepositorio接口

package com.app.repositorio;

import com.app.modelo.UsuarioModelo;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UsuarioRepositorio extends JpaRepository<UsuarioModelo, Integer>{
    
    Optional<UsuarioModelo> porUsuario(String CodigoUsuario);
    
    Optional<UsuarioModelo> porUsarioEstatus(String CodigoUsuario, boolean EstatusLogeado);

    Optional<UsuarioModelo> porUsuarioIntentos(String CodigoUsuario, int CantidadIntentos);
}

UsuarioServicio

package com.app.servicio;

import com.app.modelo.UsuarioModelo;
import com.app.repositorio.UsuarioRepositorio;
import org.springframework.stereotype.Service;

@Service
public class UsuarioServicio {
    private final UsuarioRepositorio repouser;
    
    public UsuarioServicio(UsuarioRepositorio ru){
        repouser = ru;
    }
    
    public UsuarioModelo registrarUsuario (String usuario){
        if (usuario == null){
            return null;
        }else{
            UsuarioModelo usermodel = new UsuarioModelo();
            usermodel.setCodigoUsuario(usuario);
            return repouser.save(usermodel);
        }
    }
    
    public UsuarioModelo autentica(String usuario){
        return repouser.porUsuario(usuario).orElse(null);
    }
}

Controller

package com.app.controller;

import com.app.modelo.UsuarioModelo;
import com.app.servicio.UsuarioServicio;
import com.app.repositorio.UsuarioRepositorio;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class UsuarioController {

    private UsuarioServicio userserv;
        
    public UsuarioController(UsuarioServicio us){
        userserv = us;
    }
    
    @GetMapping("/index")
    public String getLoginPage(Model modelo) {
        modelo.addAttribute("loginrequest", new UsuarioModelo());
        return "index";
    }
    
    @PostMapping("/index")
    public String login(@ModelAttribute UsuarioModelo usermod){
        UsuarioModelo logeduser = userserv.autentica(usermod.getCodigoUsuario());
        logeduser = logeduser == null ? userserv.registrarUsuario(usermod.getCodigoUsuario()) : logeduser;
        return logeduser == null  ? "error_page" : "redirect:/index";
    }
}

我认为错误可能是由于 dispatcher-servlet.xml 文件配置错误,因为我从控制器中删除了 UsuarioServicio 并且应用程序运行正常

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

    <!--
    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.
    -->
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.htm">UsuarioController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/jsp/"
        p:suffix=".jsp" />

    <!--
    The index controller.
    
    <bean name="indexController"
        class="org.springframework.web.servlet.mvc.ParameterizableViewController"
        p:viewName="index" />-->
    
    <bean name="UsuarioController" class="com.app.controller.UsuarioController"/>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0" 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">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</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:p="http://www.springframework.org/schema/p"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">

    <!--bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    p:location="/WEB-INF/jdbc.properties" />

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource"
    p:driverClassName="${jdbc.driverClassName}"
    p:url="${jdbc.url}"
    p:username="${jdbc.username}"
    p:password="${jdbc.password}" /-->

    <!-- ADD PERSISTENCE SUPPORT HERE (jpa, hibernate, etc) -->

</beans>

application.properties

spring.datasource.url=jdbc:sqlserver://XXXXXX;databaseName=XXXXX
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.username=XXXXXX
spring.datasource.password=XXXXXX

spring.jpa.properties.hibernate.dialeg = org.hibernate.dialect.sqlserver

我这样修改了 dispatcher-servlet:

<bean name="UsuarioController" 
    class="com.app.controller.UsuarioController">
        <constructor-arg type="com.app.servicio.UsuarioServicio" 
        value="us"/>
</bean>

现在错误是这样的:

加载应用程序时出现异常:java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: org.springframework.beans.factory.UnsatisfiedDependencyException: 创建 bean 时出错在 ServletContext 资源 [/WEB-INF/dispatcher-servlet.xml] 中定义了名称“UsuarioController”:通过构造函数参数 0 表示的不满足依赖关系:无法将 [java.lang.String] 类型的参数值转换为所需的类型 [com. app.servicio.UsuarioServicio]:无法将类型“java.lang.String”的值转换为所需类型“com.app.servicio.UsuarioServicio”;嵌套异常是 java.lang.IllegalStateException:无法将类型“java.lang.String”的值转换为所需类型“com.app.servicio.UsuarioServicio”:找不到匹配的编辑器或转换策略]]

我已经像这样更新了 dispatcher-servlet.xml 文件

    <bean name="UsuarioServicio" class="com.app.servicio.UsuarioServicio" id="us"/>
<bean name="UsuarioController" class="com.app.controller.UsuarioController">
    <constructor-arg type="com.app.servicio.UsuarioServicio" ref="UsuarioServicio" />
</bean>

像这样

   <bean name="UsuarioServicio" class="com.app.servicio.UsuarioServicio" id="us"/>
<bean name="UsuarioController" class="com.app.controller.UsuarioController">
    <constructor-arg ref="UsuarioServicio" />
</bean>

这两种情况的错误都是新的

加载应用程序时出现异常:java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: java.lang.NoSuchMethodException: com.app.servicio.UsuarioServicio .()]]

我这样修改了 dispatcher-servlet:

<jpa:repositories base-package="com.app.repositorio"/>
    <bean name="UsuarioServicio" class="com.app.servicio.UsuarioServicio" id="us">
        <constructor-arg ref="UsuarioRepositorio"/>
    </bean>
    <bean name="UsuarioController" class="com.app.controller.UsuarioController">
        <constructor-arg type="com.app.servicio.UsuarioServicio" ref="UsuarioServicio" />
    </bean>

我得到了这个错误

加载应用程序时出现异常:java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: org.xml.sax.SAXParseException;行号:36;列号:59; El prefijo "jpa" para el elemento "jpa:repositories" no está enlazado.]]

然后我像这样删除了前缀“jap”

<repositories base-package="com.app.repositorio"/>
<bean name="UsuarioServicio" class="com.app.servicio.UsuarioServicio" id="us">
    <constructor-arg ref="UsuarioRepositorio"/>
</bean>
<bean name="UsuarioController" class="com.app.controller.UsuarioController">
    <constructor-arg type="com.app.servicio.UsuarioServicio" ref="UsuarioServicio" />
</bean>

错误是这样的

加载应用程序时出现异常:java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: org.xml.sax.SAXParseException;行号:36;列号:55; cvc-complex-type.2.4.a:Se ha encontrado contenido no válido a partir del elemento 'repositories'。参见 esperaba uno de '{"http://www.springframework.org/schema/beans":import, "http://www.springframework.org/schema/beans":alias, "http://www.springframework .org/schema/beans":bean, WC[##other:"http://www.springframework.org/schema/beans"], "http://www.springframework.org/schema/beans":beans }'.]]

我做了一些研究,发现在 dispatcher-servlet 中需要做一些配置

dispatcher-servle.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:p="http://www.springframework.org/schema/p"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd 
       http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
       http://www.springframework.org/schema/data/jpa https://www.springframework.org/schema/data/jpa/spring-jpa-2.6.xsd 
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-5.3.xsd" >

    <!--
    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.
    -->
    
    <mvc:annotation-driven conversion-service="UsuarioServicio"/>
    
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.htm">UsuarioController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />

    <!--
The index controller.

<bean name="indexController"
    class="org.springframework.web.servlet.mvc.ParameterizableViewController"
    p:viewName="index" />-->
    
    <context:component-scan base-package="com.app.repositorio" />
    <jpa:repositories base-package="com.app.repositorio"/>
     
    <bean id="UsuarioRepositorio" class="com.app.servicio.UsuarioServicio" >
       
    </bean>
    
    <bean id="UsuarioServicio" class="com.app.servicio.UsuarioServicio">
        <constructor-arg name="ur" ref="UsuarioRepositorio"/>
    </bean>
    <bean name="UsuarioController" class="com.app.controller.UsuarioController">
        <constructor-arg ref="UsuarioServicio"/>
    </bean>
</beans>

现在错误似乎与这一行有关

org.xml.sax.SAXParseException;行号:46;列号:54; cvc-complex-type.2.4.c: El comodín 巧合 es estricto, pero no se ha encontrado ninguna declaración para el elemento 'context:component-scan'。

我在 UsuarioRepositorio 接口中添加了这一行 @ComponentScan(basePackages = { "com.app.repositorio" }) ,现在文件是这个

UsuarioRepositorio 接口

package com.app.repositorio;

import com.app.modelo.UsuarioModelo;
import java.util.Optional;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

@Repository
@ComponentScan(basePackages = { "com.app.repositorio" })
public interface UsuarioRepositorio extends JpaRepository<UsuarioModelo, Integer>{
    
    Optional<UsuarioModelo> porUsuario(String CodigoUsuario);
    
    Optional<UsuarioModelo> porUsarioEstatus(String CodigoUsuario, boolean EstatusLogeado);

    Optional<UsuarioModelo> porUsuarioIntentos(String CodigoUsuario, int CantidadIntentos);
}

【问题讨论】:

  • 能否提供applicationContext.xml文件的内容?
  • 另外,能否请您提供 Spring Data JPA 配置以提供 UsuarioRepositorio 接口的实现?
  • 谢谢,添加applicationContext.xml文件,才发现项目没有Spring Data JPA配置
  • 感谢您的帮助!我按照你的建议做了,有结果了,还是看不到原因
  • 再次感谢您的帮助。我试过这个建议,有结果。我认为错误不仅在 dispatcher-servlet.xml

标签: java spring servlets


【解决方案1】:

更正

下面的修正是从低层到高层排序的。

更正 #1:持久层:激活 Spring Data JPA 存储库 bean 支持

添加jpa XML 命名空间:

xmlns:jpa="http://www.springframework.org/schema/data/jpa"

通过添加以下内容更新xsi:schemaLocation XML 架构位置:

http://www.springframework.org/schema/data/jpa https://www.springframework.org/schema/data/jpa/spring-jpa.xsd

然后添加repositories元素:

<jpa:repositories base-package="com.app.repositorio" />

结果:

每个 bean 都在一个派生自接口名称的 bean 名称下注册,因此UserRepository 的接口将在userRepository 下注册。

——Spring Data JPA - Reference Documentation.

因此,这应该为我们的案例提供usuarioRepositorio bean。

更多详细信息和完整示例,请参见页面:Spring Data JPA - Reference Documentation

更正#2:应用服务层:添加UsuarioServicio bean

usuarioRepositorio bean 的引用用于usuarioServicio bean。

<bean id="usuarioServicio" class="com.app.servicio.UsuarioServicio">
    <constructor-arg ref="usuarioRepositorio" />
</bean>

请注意idref 属性值的大小写:usuarioServiciousuarioRepositorio

更正 #3:集成层:更新 UsuarioController bean

usuarioServicio bean 的引用用于usuarioController bean。

<bean id="usuarioController" class="com.app.controller.UsuarioController">
    <constructor-arg ref="usuarioServicio" />`
</bean>

请注意idref 属性值的大小写:usuarioControllerusuarioServicio

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-24
    • 2013-06-09
    • 1970-01-01
    • 2021-06-02
    • 2014-07-16
    • 1970-01-01
    • 2012-02-05
    相关资源
    最近更新 更多