想要使用applicationContext或WebApplicationContext在Servlet中使用Spring Bean。我怎样才能实现这一目标

时间:2017-03-24 07:26:36

标签: java spring jsp jpa servlets

==================的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中指定的位置是正确的

src / main / java - &gt;包com.firstApp.servlet MyServletLogin.java

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启动时,得到以下错误:

SEVERE:配置org.springframework.web.context.ContextLoaderListener类的应用程序侦听器时出错 java.lang.ClassNotFoundException:org.springframework.web.context.ContextLoaderListener     在org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)     在org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)     at org.apache.catalina.core.DefaultInstanceManager.loadClass(DefaultInstanceManager.java:532)     在org.apache.catalina.core.DefaultInstanceManager.loadClassMaybePrivileged(DefaultInstanceManager.java:514)     在org.apache.catalina.core.DefaultInstanceManager.newInstance(DefaultInstanceManager.java:142)     at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4854)     在org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5434)     在org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)     在org.apache.catalina.core.ContainerBase $ StartChild.call(ContainerBase.java:1559)     在org.apache.catalina.core.ContainerBase $ StartChild.call(ContainerBase.java:1549)     at java.util.concurrent.FutureTask.run(FutureTask.java:266)     在java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)     at java.util.concurrent.ThreadPoolExecutor $ Worker.run(ThreadPoolExecutor.java:617)     在java.lang.Thread.run(Thread.java:745)

2017年3月24日下午12:37:52 org.apache.catalina.core.StandardContext listenerStart 严重:由于先前的错误而跳过安装的应用程序侦听器 2017年3月24日下午12:37:52 org.apache.catalina.core.StandardContext startInternal 严重:错误listenerStart 2017年3月24日下午12:37:52 org.apache.catalina.core.StandardContext startInternal 严重:由于先前的错误,上下文[/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 Dependencies添加到部署程序集后,

能够解析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)

2 个答案:

答案 0 :(得分:1)

这看起来是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,错误可能会消失。

答案 1 :(得分:0)

您可以像下面这样更改上下文参数 1。

 <context-param>
       <param-name>contextConfigLocation</param-name>
       <param-value>/WEB-INF/spring.xml</param-value>
       </context-param>
(or)

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:/spring.xml</param-value>
    </context-param>

2。 右键单击项目 - &gt;部署程序集 - > Add-&gt;构建路径条目 - &gt; maven依赖

参考: HTTP Status 500 - Servlet.init() for servlet spring-dispatcher threw exception