当前位置: 首页 > 知识库问答 >
问题:

希望使用applicationContext或WebApplicationContext在Servlet中使用Spring Bean。我怎样才能做到这一点

毕富
2023-03-14

================web.xml=====================

<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<display-name>loginBasic</display-name>
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:/spring.xml</param-value>
</context-param>

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

  <welcome-file-list>
    <welcome-file>siteMendorLogin.jsp</welcome-file>
  </welcome-file-list>

 <!--  <servlet>
        <servlet-name>siteMendorLogin</servlet-name>
        <servlet-class>com.firstApp.servlet.SiteMendorLogin</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>siteMendorLogin</servlet-name>
        <url-pattern>/site</url-pattern>
    </servlet-mapping> -->

  <session-config>
        <session-timeout>15</session-timeout>
  </session-config>

</web-app>

我把spring.xml放在src/main/resources文件夹中,希望web.xml中指定的位置是正确的

package com.firstApp.servlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.firstApp.spring.tx.model.User;
import com.firstApp.spring.tx.user.UserManager;

@WebServlet("/Site")
public class MyServletLogin extends HttpServlet{

    /**
     * 
     */
    private static final long serialVersionUID = 1L;
    private UserManager userManager;
    Map<String, String> userDetails= new HashMap<String, String>();
    @Override
    public void init(ServletConfig config) throws ServletException {
        WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        UserManager userManager = (UserManager) ctx.getBean("userManagerImpl");
        userDetails.put("mayank", "mayank");
    }

     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
         //TODO
         //check if cookies with user Credentials are already present 

//       
//
             userManager = (UserManager) ctx.getBean("userManagerImpl");

            List<User> list = userManager.findAllUsers();

         String uid=req.getParameter("userId");
         String uName=req.getParameter("userName"); 
         String userPass=req.getParameter("userPass"); 
         HttpSession session = req.getSession();


         if(userDetails.containsKey(uid) && userDetails.get(uid).equals(userPass)){
             session.setAttribute("userId", uid);
             session.setAttribute("userName", uName);
             Cookie cookie = new Cookie("credential", uid+":"+uName+":"+userPass);
             cookie.setMaxAge(100000);
             cookie.setPath("/callidus/");
             resp.addCookie(cookie);
             resp.sendRedirect("http://localhost:8081/callidus/CookieSent");
         }else{
             session.setAttribute("invalid", "Invalid User Id or password");
             resp.sendRedirect("siteMendorLogin.jsp");
         }

     }



}

sitemendorLogin.jsp如下所示

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>SiteMendor Login</title>
</head>
<body>
    <form action="Site" method="post">  
        <pre>UserId   :  <input type="text" name="userId"/><br/> </pre>
        <pre>UserName  :  <input type="text" name="userName"/><br/> </pre>
        <pre>Password  :  <input type="password" name="userPass"/><br/> </pre> 
        <input type="submit" value="login"/>  
    </form>  

</body>
</html>

我不确定,如果我做的方式是正确的,在tomcat启动时,得到以下错误:

严重:配置org.springframework.web.context.contextLoaderListener java.lang.ClassNotFoundException:org.springframework.web.context.context.contextLoaderListener在org.apache.catalina.loader.webappClassLoader.loadClass(webappClassLoader.java:1702)在org.apache.catalina.loader.webappClassLoader.loadClass(webappClassLoader.java:1547)aultInstanceManager.java:514)在org.apache.catalina.core.defaultInstanceManager.newInstance(DefaultInstanceManager.java:142)在org.apache.catalina.core.standardContext.listenerStart(StandardContext.java:4854)在org.apache.catalina.core.standardContext.startInstant(StandardContext.java:5434)在org.apache.catalina.util.LifecyCleBase.start(在java.util.concurrent.futuretask.run(futuretask.java:266)在java.util.concurrent.threadPoolExecutor.runworker(threadPoolExecutor.java:1142)在java.util.concurrent.threadPoolExecutor$worker.run(threadPoolExecutor.java:617)在java.lang.thread.run(threadPoolExecutor.java:745)

2017年3月24日12:37:52 PM org.apache.catalina.core.standardContext listenerStart严重:由于以前的错误而跳过安装应用程序侦听器2017年3月24日12:37:52 PM org.apache.catalina.core.standardContext start内部严重:错误listenerStart 2017年3月24日12:37:52 PM org.apache.catalina.core.standardContext start内部严重:Context[/com.myfirstapp]由于以前的错误启动失败

甚至没有得到我在web.xml中提到的欢迎文件(sitemendorlogin.jsp)

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

    <tx:annotation-driven />

    <context:component-scan base-package="com.firstApp.spring.tx.dao.impl" />
    <context:component-scan base-package="com.firstApp.spring.tx.user.impl" />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/poc_data" />
        <property name="username" value="root" />
        <property name="password" value="root" />
    </bean>

    <bean id="entityManagerFactory"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceUnitName" value="testPU" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean>

</beans>

======pom.xml=======

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.firstApp.spring.tx</groupId>
    <artifactId>com.myFirstApp</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>com.myFirstApp</name>
    <url>http://maven.apache.org</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <spring.version>3.2.5.RELEASE</spring.version>
        <hibernate.version>4.1.9.Final</hibernate.version>
    </properties>

    <dependencies>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>

        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.2.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.15</version>
        </dependency>

        <dependency>
    <groupId>jstl</groupId>
    <artifactId>jstl</artifactId>
    <version>1.2</version>
</dependency>

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.0.1</version>
</dependency>

        <dependency>
    <groupId>antlr</groupId>
    <artifactId>antlr</artifactId>
    <version>2.7.7</version>
</dependency>

    </dependencies>
</project>

将Maven依赖项添加到部署程序集后,程序集能够解决ContextLoaderListener错误,但在访问servlet中的服务bean时仍然存在问题,得到以下错误:

javax.servlet.ServletException: Servlet.init() for servlet com.firstApp.servlet.MyServletLogin threw exception
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    java.lang.Thread.run(Thread.java:745)
root cause 
java.lang.NullPointerException
    javax.servlet.GenericServlet.getServletContext(GenericServlet.java:125)
    com.firstApp.servlet.MyServletLogin.init(MyServletLogin.java:38)
    org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
    org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
    org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
    org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
    java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    java.lang.Thread.run(Thread.java:745)

共有1个答案

慕云
2023-03-14

这看起来是maven POM中缺少的一些依赖项。检查是否有以下依赖关系:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${spring.version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-web</artifactId>
    <version>${spring.version}</version>
</dependency>

还可以尝试将param-value更改为classpath*:spring.xml

根据更新后的错误:

init()方法缺少对super.init(config)的调用。添加这个调用来初始化servletContext,错误可能会消失。

 类似资料:
  • 问题内容: Objective- C声明一个类函数,在使用每个类之前,该函数对每个类都运行一次。除其他事项外,它通常用作交换方法实现(交换)的入口。 Swift 3.1不建议使用此功能,并显示警告: 方法“ initialize()”定义了Objective-C类的方法“ initialize”,不能保证它会由Swift调用,并且在以后的版本中将不允许使用 如何解决此问题,同时仍保持与当前使用入口

  • 有什么方法可以简化这段代码吗?我正好有一个白色的一块,想要得到它的位置 代码: 瓦片类: 件类:

  • 我使用Selenium,需要无休止地等待页面加载(因为加载需要几个小时),然后解析其中的数据。我该怎么做? 我使用这样的一些代码:

  • 问题内容: 我试图“ stopPropagation”以防止单击li内的元素(链接)时关闭TwitterBootstrap导航栏下拉菜单。 在Angular中,看起来像指令是执行此操作的地方?所以我有: …但是该方法不属于元素: 我把指令与 有什么建议么? 问题答案: “当前一些指令(即ng:click)停止事件传播。这阻止了与依赖于捕获此类事件的其他框架的互操作性。” - …并且能够在没有指令的

  • 我怎么能把这条线移到右边。我正在使用智能的想法,我使用了导致问题的自定义字体。