1

Не судите строго, я новичек. Мне нужно создать форму обратной связи на сайте, которая будет состоять из: имени, email, сообщения и кнопки Отправить. После нажатия на кнопку, сообщения должно приходить мне на email. Я создала contact.jsp:

    <html>
    <head>
        <title>Contact</title>
    </head>
    <body>
    <form action="ContactServlet" method="POST">
        <p>Name: <input name="name"></p>
        <p>Email: <input name="email"></p>
        <p>Message: <textarea name="message"></textarea></p>
        <p><input type="submit">
    </form>
    </body>
    </html>

И создала сервлет ContactServlet.java (пример нашла тут):


      public class ContactServlet extends HttpServlet {
            public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
    
            String name = request.getParameter("name");
            String email = request.getParameter("email");
            String message = request.getParameter("message");
            PrintWriter writer = response.getWriter();
    
            if(!message.equals(null)){
                String host = "smtp.gmail.com";
                int port = 587;
                String username = "username";
                String password = "password";
    
                Properties props = new Properties();
                props.put("mail.smtp.auth", "true");
                props.put("mail.smtp.starttls.enable", "true");
                Session session = Session.getDefaultInstance(props, null);
    
                String body = message;
    
                try {
                    MimeMessage m = new MimeMessage(session);
                    m.setSubject(name);
                    m.setFrom(new InternetAddress(email, null));
                    m.setText(body);
                    m.addRecipient(MimeMessage.RecipientType.TO, new InternetAddress(username, "me"));
    
    
                    Transport transport = session.getTransport("smtp");
                    transport.connect(host, port, username, password);
    
                    Transport.send(m);
    
                } catch (AddressException e) {
                    e.printStackTrace();
                } catch (javax.mail.MessagingException e) {
                    e.printStackTrace();
                }
    
    
                try {
                    writer.println("Message send!");
                } finally {
                    writer.close();
                }
    
            }
        }
    }

Файл pom.xml выглядит так:

    <dependencies>
        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
            <version>2.3.1</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.mail/mail -->
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
        </dependency>

    </dependencies>

Я запуталась совсем. После запуска Tomcat выдает очень много ошибок. Помогите, пожалуйста, разобраться.

Ошибки, заранее прошу прощения за такое полотно:

org.apache.tomcat.util.modeler.BaseModelMBean.invoke Exception invoking method [manageApp]
    java.lang.IllegalStateException: Error starting child

........

Caused by: org.apache.catalina.LifecycleException: Failed to start component 
[StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

........

Caused by: java.lang.NoClassDefFoundError: javax/mail/internet/AddressException

........

Caused by: java.lang.ClassNotFoundException: javax.mail.internet.AddressException

........

15-Feb-2021 14:04:09.214 SEVERE [RMI TCP Connection(2)-127.0.0.1] org.apache.tomcat.util.modeler.BaseModelMBean.invoke Exception invoking method [createStandardContext]

javax.management.RuntimeOperationsException: Exception invoking method [manageApp]

.......

Caused by: java.lang.IllegalStateException: Error starting child

[2021-02-15 02:04:09,301] Artifact hydroponics:war exploded: Error during artifact deployment. See server log for details.

........

Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[]]

........

Caused by: java.lang.NoClassDefFoundError: javax/mail/internet/AddressException

.......

Caused by: java.lang.ClassNotFoundException: javax.mail.internet.AddressException

.......

15-Feb-2021 14:04:16.771 INFO [Catalina-utility-2] org.apache.catalina.startup.HostConfig.deployDirectory Установка веб приложения в папку [D:\JAVA\tomcat\webapps\manager]

15-Feb-2021 14:04:17.738 INFO [Catalina-utility-2] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.

15-Feb-2021 14:04:18.212 WARNING [Catalina-utility-2] org.apache.catalina.util.SessionIdGeneratorBase.createSecureRandom Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [394] milliseconds.

15-Feb-2021 14:04:18.295 INFO [Catalina-utility-2] 
org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [D:\JAVA\tomcat\webapps\manager] has finished in [1В 524] ms
........
Note: further occurrences of HTTP request parsing errors will be logged at DEBUG level.

введите сюда описание изображения

как добавила в артифакт папку lib с бибилиотеками, сайт стал запускаться, но форма не работает все равно: введите сюда описание изображения

Connected to server

[2021-02-18 01:37:39,345] Artifact hydroponics:war exploded: Artifact is being deployed, please wait...

18-Feb-2021 13:37:41.197 INFO [RMI TCP Connection(3)-127.0.0.1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.

18-Feb-2021 13:37:41.474 WARNING [RMI TCP Connection(3)-127.0.0.1] org.apache.catalina.util.SessionIdGeneratorBase.createSecureRandom Creation of SecureRandom instance for session ID generation using [SHA1PRNG] took [241] milliseconds.

[2021-02-18 01:37:41,515] Artifact hydroponics:war exploded: Artifact is deployed successfully

[2021-02-18 01:37:41,516] Artifact hydroponics:war exploded: Deploy took 2,172 milliseconds

18-Feb-2021 13:37:49.187 INFO [Catalina-utility-1] org.apache.catalina.startup.HostConfig.deployDirectory Установка веб приложения в папку [D:\JAVA\tomcat\webapps\manager]

18-Feb-2021 13:37:50.324 INFO [Catalina-utility-1] org.apache.jasper.servlet.TldScanner.scanJars At least one JAR was scanned for TLDs yet contained no TLDs. Enable debug logging for this logger for a complete list of JARs that were scanned but no TLDs were found in them. Skipping unneeded JARs during scanning can improve startup time and JSP compilation time.

18-Feb-2021 13:37:50.363 INFO [Catalina-utility-1] org.apache.catalina.startup.HostConfig.deployDirectory Deployment of web application directory [D:\JAVA\tomcat\webapps\manager] has finished in [1В 177] ms

2
  • 1
    Неплохо бы было приложить эти ошибки. Не все здесь умеют ванговать. 15 фев 2021 в 14:20
  • Добавила в вопросе. 16 фев 2021 в 14:04

1 ответ 1

0

У тебя добавлена зависимость по спецификации mail, но очень устаревшая. Т.е.

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>mail</artifactId>
    <version>1.4</version>
</dependency>

лучше заменить на

<dependency>
    <groupId>javax.mail</groupId>
    <artifactId>javax.mail-api</artifactId>
    <version>1.6.2</version>
</dependency>
<dependency>
    <groupId>com.sun.mail</groupId>
    <artifactId>javax.mail</artifactId>
    <version>1.6.2</version>
</dependency>

Возможно из-за каких-то особенностей класса javax.mail.internet.AddressException указанной версии библиотеки он не может подгрузится, потому падает ошибка.


К тому же не очень понятно, как ты собираешь и деплоишь приложение. Если это mvn package + деплой war'ника на чистый tomcat, то на первый взгляд всё должно работать. Лучше прикрепить структуру получившегося war'ника (war - это zip-архив) к вопросу. Логи лучше выкладывать целиком и все, т.к. в tomcat несколько логов.

P.S. Твой contact.jsp на самом деле не содержит JSP-тегов/кода. Возможно стоит его сделать просто как contact.html

1
  • добавила, это то? 18 фев 2021 в 10:37

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.