Noobcanon
Noobcanon

Reputation: 9

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

Why do I get java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletRequest when I add @Controller to DummyController class?

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";
    }
}

When I remove the @Controller annotation from DummyController then main prints out the example's fine but if I put it back in then it throws:

Exception in thread "main" java.lang.NoClassDefFoundError: javax/servlet/http/HttpServletRequest at java.lang.Class.getDeclaredMethods0(Native Method)

I'm using this project:

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

All I've done is add Main and DummyController

Upvotes: 0

Views: 4672

Answers (3)

likaiguo.happy
likaiguo.happy

Reputation: 2298

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

Upvotes: 0

Babak Behzadi
Babak Behzadi

Reputation: 1256

Your dependency scope is 'provided', so when you build the war this dependency won't be added to the class path! Make sure the dependency exists on App Server lib path.

Upvotes: 1

kulatamicuda
kulatamicuda

Reputation: 1661

You are probably missing right dependencies, like:

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

Please note that your version could be 2.5, 3.0 or 3.1 - it depends on application server you are using. Also when you want to create executable war you should probably not use provided scope (depending on your servlet container).

Upvotes: 4

Related Questions