简体   繁体   中英

java.lang.ClassNotFoundException: org.springframework.servlet.DispatcherServlet

Hi all I am new in Spring, Servlet ,Jsp ,Maven. I am trying to implement Spring MVC by following some tutorial. I am really not able to understand the flow how Spring MVC works and after learning lot of tutorial I have some idea. So I started creating a simple web app through Spring MVC. but I am getting "java.lang.ClassNotFoundException: org.springframework.servlet.DispatcherServlet"

after searching a lot I found similar solution that I need to add following dependency to POM.XML

  • spring-core
  • spring-beans
  • spring-context
  • servlet-api
  • spring-webmvc
  • spring-web

I have added all these dependency to my pom. The another solution which I found to use the Project-properties-Deployment Assembly-Add- IVY. but I ma not getting that IVY folder after after clicking on add button I dont no why but I am using JBOSS Please dont close this question I have been facing these issue since last week but could not implement MVC.

Please please help me This post can help lot of people who are new and can implement these bcz i have included all the classes along with jsp.

Directory Structure 在此处输入图片说明

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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany.app</groupId>
  <artifactId>my-app</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>my-app</name>
  <url>http://maven.apache.org</url>

  <properties>
    <java.version>1.7</java.version>
    <spring.version>3.2.13.RELEASE</spring.version>
    <cglib.version>2.2.2</cglib.version>
 </properties> 


  <dependencies>
       <!-- Spring Core & MVC -->
  <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>3.2.13.RELEASE</version>
  </dependency>

  <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>3.2.13.RELEASE</version>
  </dependency>

   <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>3.2.13.RELEASE</version>
    </dependency>

    <dependency>
        <groupId>commons-logging</groupId>
        <artifactId>commons-logging-api</artifactId>
        <version>1.1</version>
        <exclusions>
                <exclusion>
                    <groupId>javax.servlet</groupId>
                    <artifactId>servlet-api</artifactId>
                </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>3.2.13.RELEASE</version>
    </dependency>

     <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>3.2.13.RELEASE</version>
    </dependency>


    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-orm</artifactId>
        <version>3.2.13.RELEASE</version>
        <type>jar</type>
        <scope>compile</scope>
    </dependency>

    <!-- CGLib for @Configuration -->
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>2.1_2</version>
        <scope>runtime</scope>
    </dependency>

    <!-- Servlet Specifiaction -->

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
   <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency> 

    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>3.0.7.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
  </dependencies>
</project>

WEB.XML

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="WebApp_ID">
    <display-name>my-app</display-name>


    <servlet>
        <servlet-name>HomeController</servlet-name>
        <servlet-class>org.springfarmework.servlet.DispatcherServlet</servlet-class>


         <init-param>
        <param-name>contextClass</param-name>
        <param-value>
            org.springframework.web.context.support.AnnotationConfigWebApplicationContext
        </param-value>
    </init-param>
        <load-on-startup>1</load-on-startup>

    </servlet>

    <servlet-mapping>
            <servlet-name>HomeController</servlet-name>
            <url-pattern>*.*</url-pattern>
    </servlet-mapping>

    <welcome-file-list>
        <!-- <welcome-file>index.html</welcome-file> -->
        <welcome-file>ContactForm.jsp</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>

I am using java class MvcConfiguration insted of XmlFilename-servlet.xml

MvcConfiguration

@EnableWebMvc
@ComponentScan(basePackages="net.codejava.spring")
@Configuration

public class MvcConfiguration extends WebMvcConfigurerAdapter {

    /* @Bean
        public ViewResolver getViewResolver(){
            InternalResourceViewResolver resolver = new InternalResourceViewResolver();
            resolver.setPrefix("/WEB-INF/");
            resolver.setSuffix(".jsp");
            return resolver;
        }*/

     @Bean
    public InternalResourceViewResolver getInternalResourceViewResolver(){
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/");
        resolver.setSuffix(".jsp");
        return resolver;
    }

     @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
        }

     @Bean
        public DataSource getDataSource() {
            DriverManagerDataSource dataSource = new DriverManagerDataSource();
            dataSource.setDriverClassName("oracle.jdbc.driver.OracleDriver");
            dataSource.setUrl("jdbc:oracle://localhost:1521/orcl");
            dataSource.setUsername("system");
            dataSource.setPassword("admin");

            return dataSource;
        }

     @Bean
        public ContactDAO getContactDAO() {
            return new ContactDAOImpl(getDataSource());
        }
}

HomeController.java

@Controller
public class HomeController {

    @Autowired
     private ContactDAO contactDAO;

    @RequestMapping(value="/")
    public ModelAndView listContact(ModelAndView model) throws IOException{
        List listContact = (List) contactDAO.list();
        model.addObject("listContact", listContact);
        model.setViewName("home");

        return model;
    }

    @RequestMapping(value = "/newContact", method = RequestMethod.GET)
    public ModelAndView newContact(ModelAndView model) {
        Contact newContact = new Contact();
        model.addObject("contact", newContact);
        model.setViewName("ContactForm");
        return model;
    }

    @RequestMapping(value = "/saveContact", method = RequestMethod.POST)
    public ModelAndView saveContact(@ModelAttribute Contact contact) {
        contactDAO.saveOrUpdate(contact);
        return new ModelAndView("redirect:/");
    }

    @RequestMapping(value = "/deleteContact", method = RequestMethod.GET)
    public ModelAndView deleteContact(HttpServletRequest request) {
        int contactId = Integer.parseInt(request.getParameter("id"));
        contactDAO.delete(contactId);
        return new ModelAndView("redirect:/");
    }

    @RequestMapping(value = "/editContact", method = RequestMethod.GET)
    public ModelAndView editContact(HttpServletRequest request) {
        int contactId = Integer.parseInt(request.getParameter("id"));
        Contact contact = contactDAO.get(contactId);
        ModelAndView model = new ModelAndView("ContactForm");
        model.addObject("contact", contact);

        return model;
    }
}

ContactDAO interface

public interface ContactDAO {

    public void saveOrUpdate(Contact contact);

    public void delete(int contactId);

    public Contact get(int contactId);

    public List<Contact> list();
}

ContactDAOImpl for database connectivity

/**
* An implementation of the ContactDAO interface.
* @author Barun Kumar
*
*/

public class ContactDAOImpl implements ContactDAO {

    private JdbcTemplate jdbcTemplate;

    public ContactDAOImpl(DataSource dataSource) {
        jdbcTemplate = new JdbcTemplate(dataSource);
    }

    public void saveOrUpdate(Contact contact) {
        // TODO Auto-generated method stub
        System.out.println("Save or update method");
        if(contact.getId()>0)
        {
            //Update
            String sql = "UPDATE contact SET name=?, email=?, address=?, "
                    + "telephone=? WHERE contact_id=?";
        jdbcTemplate.update(sql, contact.getName(), contact.getEmail(),
                contact.getAddress(), contact.getTelephone(), contact.getId());
        }
        else {
            // insert
            String sql = "INSERT INTO contact (name, email, address, telephone)"
                        + " VALUES (?, ?, ?, ?)";
            jdbcTemplate.update(sql, contact.getName(), contact.getEmail(),
                    contact.getAddress(), contact.getTelephone());
            }   
    }

    public void delete(int contactId) {
        // TODO Auto-generated method stub
        System.out.println("Delete method");

        String sql="DELETE FROM contact WHERE contact_id=?";
        jdbcTemplate.update(sql, contactId);

    }

    public Contact get(int contactId) {
        // TODO Auto-generated method stub
        System.out.println("Get method");
        String sql = "SELECT * FROM contact WHERE contact_id=" + contactId;
        return jdbcTemplate.query(sql, new ResultSetExtractor<Contact>() {

            public Contact extractData(ResultSet rs) throws SQLException,
                    DataAccessException {
                if (rs.next()) {
                    Contact contact = new Contact();
                    contact.setId(rs.getInt("contact_id"));
                    contact.setName(rs.getString("name"));
                    contact.setEmail(rs.getString("email"));
                    contact.setAddress(rs.getString("address"));
                    contact.setTelephone(rs.getString("telephone"));
                    return contact;
                }

                return null;
            }

        });
    }

    public List<Contact> list() {
        // TODO Auto-generated method stub
        System.out.println("List");
         String sql = "SELECT * FROM contact";
            List<Contact> listContact = jdbcTemplate.query(sql, new RowMapper<Contact>() {

                public Contact mapRow(ResultSet rs, int rowNum) throws SQLException {
                    Contact aContact = new Contact();

                    aContact.setId(rs.getInt("contact_id"));
                    aContact.setName(rs.getString("name"));
                    aContact.setEmail(rs.getString("email"));
                    aContact.setAddress(rs.getString("address"));
                    aContact.setTelephone(rs.getString("telephone"));

                    return aContact;
                }
            });
        return listContact;
    }
}

Contact.java Bean class

public class Contact {

    private int id;
    private String name;
    private String email;
    private String address;
    private String telephone;

    public Contact()
    {
        System.out.println("the default contructor");
    }

     public Contact(String name, String email, String address, String telephone) {
            this.name = name;
            this.email = email;
            this.address = address;
            this.telephone = telephone;
        }
}

ContactForm.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<div align="center">
        <h1>New/Edit Contact</h1>
        <form:form action="saveContact" method="post" modelAttribute="contact">
        <table>
            <form:hidden path="id"/>
            <tr>
                <td>Name:</td>
                <td><form:input path="name" /></td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><form:input path="email" /></td>
            </tr>
            <tr>
                <td>Address:</td>
                <td><form:input path="address" /></td>
            </tr>
            <tr>
                <td>Telephone:</td>
                <td><form:input path="telephone" /></td>
            </tr>
            <tr>
                <td colspan="2" align="center"><input type="submit" value="Save"></td>
            </tr>
        </table>
        </form:form>
    </div>
</body>
</html>

Home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Contact Manager Home</title>
</head>
<body>

<div align="center">
            <h1>Contact List</h1>
            <h3><a href="/newContact">New Contact</a></h3>
            <table border="1">

                <th>No</th>
                <th>Name</th>
                <th>Email</th>
                <th>Address</th>
                <th>Telephone</th>
                <th>Action</th>

                <c:forEach var="contact" items="${listContact}" varStatus="status">
                <tr>
                    <td>${status.index + 1}</td>
                    <td>${contact.name}</td>
                    <td>${contact.email}</td>
                    <td>${contact.address}</td>
                    <td>${contact.telephone}</td>
                    <td>
                        <a href="/editContact?id=${contact.id}">Edit</a>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <a href="/deleteContact?id=${contact.id}">Delete</a>
                    </td>

                </tr>
                </c:forEach>             
            </table>
        </div>
    </body>
</body>
</html>

You have a typo in your web.xml:

org.springfarmework.servlet.DispatcherServlet
          ^^^

It must be

org.springframework.servlet.DispatcherServlet

UPDATE:

Also you have to add org.springframework.web.servlet-3.2.13.RELEASE.jar to your project:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>3.2.13.RELEASE</version>
</dependency>

Why this exception happened: Most probably the necessary Spring MVC related jar files are not loaded and deployed on tomcat startup. But note: these files are in your classpath and hence you are not getting any error in Eclipse IDE during development time. Happens only during runtime.

You need to add the "Maven Dependency" in the Deployment Assembly

  1. right click on your project and choose properties.
  2. click on Deployment Assembly.
  3. click add
  4. click on "Java Build Path Entries"
  5. select Maven Dependencies"
  6. click Finish.
  7. Rebuild Application again.
  8. Restart Tomcat

Note: This is also applicable for non maven project. Try accessing URL again and you shouldn't see any error now

Goto to Java build path of your project aand click order and export and select Maven dependencies and apply. Now run as maven install and run on server.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM