小编abh*_*bhi的帖子

获取java.lang.ClassNotFoundException:JUnit中的javax.servlet.ServletContext

我在我的应用程序中使用Sping MVC并为DAO编写JUnit测试用例.当我运行测试时,我收到错误:java.lang.ClassNotFoundException: javax.servlet.ServletContext.

在堆栈跟踪中,我看到此错误是在此期间引起的getApplicationContext.在我看来applicationContext,我还没有定义任何servlet.Servlet映射只在这里完成,web.xml所以我不明白为什么我会收到这个错误.

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

xmlns:tx="http://www.springframework.org/schema/tx">

<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close">
    <property name="driverClass" value="com.mysql.jdbc.Driver"/>
    <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/testdb"/>
    <property name="user" value="username"/>
</bean>

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource"/>
    <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
            <prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/myWorld_test</prop>
            <prop key="hibernate.connection.username">username</prop>
        </props>
    </property>
    <property name="packagesToScan">
        <list>
            <value>com.myprojects.pojos</value>
        </list>
    </property>
</bean>

<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
    <property name="sessionFactory" …
Run Code Online (Sandbox Code Playgroud)

java junit spring spring-mvc

30
推荐指数
2
解决办法
7万
查看次数

如何在Golang中处理纯文本HTTP Get响应?

我正在向返回纯文本响应的端点发出HTTP GET请求.

如何获取纯文本响应的字符串?

我的代码如下所示:

    url := "http://someurl.com"
    response,err := http.Get(url)
    if err != nil {
        log.Fatal(err)
    }
    defer response.Body.Close()

    responseString := //NOT SURE HOW TO GRAB THE PLAIN TEXT STRING
Run Code Online (Sandbox Code Playgroud)

rest http go

30
推荐指数
3
解决办法
2万
查看次数

简单的hibernate查询返回非常慢

我有以下hibernate查询:

Query query = session.createQuery("from MyHibernateClass");
List<MyHibernateClass> result = query.list();// executes in 7000ms
Run Code Online (Sandbox Code Playgroud)

当我在MySQL中记录正在执行的sql时,我看到了

select 
  myhibernat0_.myFirstColumn as myfirstcolumn92_, 
  myhibernat0_.mySecondColumn as mysecondcolumn92_, 
  myhibernat0_.mythirdcolumn as mythirdcolumn92_, 
  myhibernat0_.myFourthColumn as myfourthcolumn92_ 
from MyHibernateClass myhibernat0_ 
where (1=1);
Run Code Online (Sandbox Code Playgroud)

当在MyHibernateClass数据库表中的3500行的小数据集上测量jvm中的java代码时,这需要大约7000ms.

如果我在另一方面使用直接jdbc如下:

Statement statement = session.connection().createStatement();
ResultSet rs = statement.executeQuery("select * from MyHibernateClass");// 7ms
List<MyHibernateClass> result = convert(rs);// executes in 20ms
Run Code Online (Sandbox Code Playgroud)

我看到相同的sql进入数据库,但现在jvm中java代码的花费时间是7ms.

MyHibernateClass是一个带有getter和setter的简单java bean类,我没有使用特殊的resulttransformers,如示例中所示.我只需要该类的只读实例,并且不需要附加到hibernate会话.

我宁愿使用hibernate版本但不能接受执行时间.

补充信息:添加hibernate日志后我看到了

[2011-07-07 14:26:26,643]DEBUG [main] [logid: ] - 
  org.hibernate.jdbc.AbstractBatcher.logOpenResults(AbstractBatcher.java:426) - 
  about to open ResultSet (open ResultSets: 0, globally: 0)
Run Code Online (Sandbox Code Playgroud)

接下来是3500条以下日志语句

[2011-07-07 14:26:26,649]DEBUG [main] …
Run Code Online (Sandbox Code Playgroud)

java hibernate objectinstantiation

27
推荐指数
5
解决办法
5万
查看次数

Python:如何"杀死"一个类实例/对象?

我希望Roach类在达到一定量的"饥饿"时"死",但我不知道如何删除该实例.我的术语可能犯了一个错误,但我的意思是我在窗户上有很多"蟑螂",我希望特定的东西完全消失.

我会告诉你代码,但它很长.我将Roach类附加到Mastermind类的roach种群列表中.

python oop class

27
推荐指数
2
解决办法
8万
查看次数

Python unitest - 在测试中使用模块和类级别设置函数中定义的变量

Python unittest使用nosetests来试验Python Class和Module fixture,在我的测试中进行最小化设置.

我面临的问题是,我不确定如何使用我的测试中setupUpModulesetUpClass函数和函数中定义的任何变量(例如: - test_1).

这是我用来尝试的:

import unittest

def setUpModule():
    a = "Setup Module variable"
    print "Setup Module"

def tearDownModule():
    print "Closing Module"

class TrialTest(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        print a #<======
        b = "Setup Class variable"

    @classmethod
    def tearDownClass(cls):
        print "Closing Setup Class"

    def test_1(self):
        print "in test 1"
        print a #<======
        print b #<======

    def test_2(self):
        print "in test 2"

    def test_3(self):
        print "in test 3"

    def test_4(self): …
Run Code Online (Sandbox Code Playgroud)

python oop unit-testing nose python-unittest

24
推荐指数
1
解决办法
1万
查看次数

IntelliJ Python插件和运行类路径

我有一个位于/ home/myself/workspace/Project1的项目,我为此创建了一个来自Python 2.7.3 Virtualenv的SDK.
这个项目使用了我在可访问目录中的一些外部代码,例如/ home/myself/LIBRARY; 这个目录包含几个带代码,docs等的目录....
例如,/home/myself/LIBRARY/mymodule/immortin_util.py中有一个模块"important_util".

现在,我在SDK Classpath中添加了整个dir/home/myself/LIBRARY,在Editor窗口中它看起来很好.识别导入和调用,我还可以浏览LIBRARY目录中的代码.

问题是,当我尝试运行我的程序时,它在使用LIBRARY的第一次导入时失败!

Traceback (most recent call last):
   File "/home/myself/workspace/Project1/my_program.py", line 10, in <module>
      from mymodule import important_util as ut 
      ImportError: No module named mymodule
Run Code Online (Sandbox Code Playgroud)

我还尝试将相同的目录添加到Sources部分的"Global Libraries"部分......但没有运气.

我似乎无法找到将此代码添加到Run类路径的方法,我怎么能这样做?

python classpath intellij-idea pycharm

23
推荐指数
2
解决办法
2万
查看次数

java.lang.NoClassDefFoundError:org/json/JSONObject

我正在使用Eclipse IDE并正在编写一个servlet.servlet应该接受来自html文件的值并相应地返回JSON响应.

我的doPost()是:

protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        try
        {
        res.setContentType("application/json");
        res.setHeader("Cache-Control", "nocache");
            res.setCharacterEncoding("utf-8");

        PrintWriter out = res.getWriter();

        JSONObject json = new JSONObject();

        String un=req.getParameter("uname");
        String pw=req.getParameter("password");

        if(un.equals("xxx") && pw.equals("xxx"))            
            json.put("result", "success");
        else
            json.put("result", "fail");

        out.print(json.toString());
        }
        catch(Exception e){System.out.print( e.getMessage());}  
    }
Run Code Online (Sandbox Code Playgroud)

当我在Eclipse中运行这个servlet时,我得到一个文件下载对话框.

当使用Tomcat在Eclipse外部运行时,我收到错误:

root cause

java.lang.NoClassDefFoundError: org/json/JSONObject
    Server1.doPost(Server1.java:25)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)

root cause

java.lang.ClassNotFoundException: org.json.JSONObject
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1713)
    org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1558)
    Server1.doPost(Server1.java:25)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:647)
    javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
Run Code Online (Sandbox Code Playgroud)

Server1.doPost(Server1.java:25)行引用

JSONObject json = new JSONObject();
Run Code Online (Sandbox Code Playgroud)

我已将org.json.jar添加到构建路径中,并将其添加到部署路径中 Properties->Configure build path->Deployment assembly

java json servlets

23
推荐指数
2
解决办法
10万
查看次数

项目中hibernate.cfg.xml的位置?

我创建了一个具有以下结构的项目:

在此输入图像描述

HibernateUtil中:

public class HibernateUtil {

    private static final SessionFactory sessionFactory = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {
            // Create the SessionFactory from hibernate.cfg.xml
            Configuration  configuration = new Configuration().configure( "C:\\Users\\Nikolay_Tkachev\\workspace\\hiberTest\\src\\logic\\hibernate.cfg.xml");
            return new Configuration().configure().buildSessionFactory();
        } catch (Throwable ex) {
            // Make sure you log the exception, as it might be swallowed
            System.err.println("Initial SessionFactory creation failed." + ex);
            throw new ExceptionInInitializerError(ex);
        }
    }

    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

    public static void shutdown() {
        // Close caches and …
Run Code Online (Sandbox Code Playgroud)

java orm hibernate

21
推荐指数
2
解决办法
10万
查看次数

注入自动连接的依赖项失败; 嵌套异常是org.springframework.beans.factory.BeanCreationException:

我正在使用Spring,Hibernate,Struts和Maven创建Web应用程序.

运行mvn clean install命令时出现以下错误:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.project.action.PasswordHintActionTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.project.action.PasswordHintAction com.project.action.PasswordHintActionTest.action; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.project.action.PasswordHintAction] 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)}
Run Code Online (Sandbox Code Playgroud)

以下是具有Autowired依赖关系的类:

import com.opensymphony.xwork2.Action;
import org.project.model.User;
import org.proejct.service.UserManager;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.subethamail.wiser.Wiser;

import static org.junit.Assert.*;
public class PasswordHintActionTest extends BaseActionTestCase { …
Run Code Online (Sandbox Code Playgroud)

java spring struts hibernate spring-mvc

19
推荐指数
1
解决办法
16万
查看次数

@Autowired - 没有找到依赖于至少1个bean的类型的限定bean

目前,我在控制器和服务层之间的Autowire配置中遇到了问题.

我无法追查我的错误.

简单的日志信息

    SEVERE:   Exception while loading the app
    SEVERE:   Undeployment failed for context /OTT
    SEVERE:   Exception while loading the app : java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: org.springframework.beans.factory.NoSuchBeanDefinitionException: 
No qualifying bean of type [com.ott.service.EmployeeService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
Run Code Online (Sandbox Code Playgroud)

下面我还给出了Controller和Service Layer代码以及dispatcher-servlet.xml

调节器

package com.ott.controller;

import com.ott.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

    /**
     *
     * @author SPAR
     */
    @Controller
    public class AdminController {

        private …
Run Code Online (Sandbox Code Playgroud)

spring spring-mvc spring-annotations

18
推荐指数
3
解决办法
11万
查看次数