簡體   English   中英

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

[英]java.lang.ClassNotFoundException: org.springframework.servlet.DispatcherServlet

大家好,我是Spring新手,Servlet,Jsp,Maven。 我正在嘗試通過遵循一些教程來實現Spring MVC。 我真的無法理解Spring MVC的工作流程,在學習了很多教程之后,我有了一些想法。 因此,我開始通過Spring MVC創建一個簡單的Web應用程序。 但我收到“ java.lang.ClassNotFoundException:org.springframework.servlet.DispatcherServlet”

經過大量搜索之后,我發現了類似的解決方案,我需要向POM.XML添加以下依賴

  • 彈簧芯
  • 春豆
  • 春天的背景
  • Servlet API
  • 春天webmvc
  • 彈簧網

我已經將所有這些依賴項添加到pom中。 我發現使用Project-properties-Deployment Assembly-Add-IVY的另一個解決方案。 但是單擊添加按鈕后,我沒有得到那個IVY文件夾。我不知道為什么,但是我正在使用JBOSS。 請不要關閉此問題。自上周以來,我一直面臨這些問題,但無法實現MVC。

請幫助我,這篇文章可以幫助很多新手,並且可以實現這些bcz,我已經將所有類與jsp一起包括在內。

目錄結構 在此處輸入圖片說明

POM文件

<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>

我正在使用XmlFilename-servlet.xml插入的Java類MvcConfiguration

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界面

public interface ContactDAO {

    public void saveOrUpdate(Contact contact);

    public void delete(int contactId);

    public Contact get(int contactId);

    public List<Contact> list();
}

ContactDAOImpl用於數據庫連接

/**
* 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類

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>

您的web.xml中有一個錯字:

org.springfarmework.servlet.DispatcherServlet
          ^^^

一定是

org.springframework.servlet.DispatcherServlet

更新:

另外,您還必須將org.springframework.web.servlet-3.2.13.RELEASE.jar添加到您的項目中:

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

發生此異常的原因:最有可能在tomcat啟動時未加載和部署與Spring MVC相關的必需jar文件。 但請注意:這些文件在您的類路徑中,因此在開發期間不會在Eclipse IDE中出現任何錯誤。 僅在運行時發生。

您需要在部署程序集中添加“ Maven依賴關系”

  1. 右鍵單擊您的項目,然后選擇屬性。
  2. 單擊部署程序集。
  3. 點擊添加
  4. 單擊“ Java構建路徑條目”
  5. 選擇Maven依賴項”
  6. 單擊完成。
  7. 再次重建應用程序。
  8. 重新啟動Tomcat

注意:這也適用於非Maven項目。 嘗試再次訪問URL,現在應該看不到任何錯誤

轉到項目的Java構建路徑,然后單擊訂單並導出,然后選擇Maven依賴項並應用。 現在以maven install運行並在服務器上運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM