@Controller导致java.lang.NoClassDefFoundError:javax / servlet / http / HttpServletRequest

时间:2014-12-30 17:08:31

标签: java spring spring-mvc servlets spring-data

为什么在将java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletRequest添加到@Controller课程时会收到DummyController

it.cspnet.firstspringmvc.controller.Main

   public static void main(String args[]) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("jpaContext.xml");
        Servizi servizi = ctx.getBean(Servizi.class);
        Utente utente = new Utente();
        utente.setUserName("test");
        utente.setPassword("test");
        Utente utenteInDb = servizi.login(utente);

        for (Ordine ordine : utenteInDb.getOrdini()) {
            System.out.println("ordine: " + ordine);
        }
    }

it.cspnet.firstspringmvc.controller.DummyController

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.servlet.http.HttpServletRequest;

@Controller
public class DummyController {

    @RequestMapping(value = "/dummy", method = {RequestMethod.GET})
    public String get(Model model, HttpServletRequest request) {
        return "dummy";
    }
}

当我从 DummyController 中删除@Controller注释时,main会打印出example的罚款,但如果我把它放回去,那么它会抛出:

  

线程“main”中的异常java.lang.NoClassDefFoundError:   javax / servlet / http / HttpServletRequest at   java.lang.Class.getDeclaredMethods0(Native Method)

我正在使用这个项目:

https://github.com/ivansaracino/spring-mvc-jparepository-example.git

我所做的就是添加主要 DummyController

3 个答案:

答案 0 :(得分:4)

您可能缺少正确的依赖关系,例如:

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <scope>provided</scope>
        <version>3.1.0</version>
    </dependency>           

请注意您的版本可能是2.5,3.0或3.1 - 这取决于您使用的应用程序服务器。此外,当您想要创建可执行文件时,您可能不应该使用提供的范围(取决于您的servlet容器)。

答案 1 :(得分:1)

您的依赖范围是“已提供”,因此在构建战争时,此依赖关系不会添加到类路径中!确保App Server lib路径上存在依赖关系。

答案 2 :(得分:0)

&#13;
&#13;
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <!--<scope>provided</scope>-->
    <version>3.1.0</version>
</dependency>
&#13;
&#13;
&#13;