Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
691 views
in Technique[技术] by (71.8m points)

servlets - HTTP Status 405 - HTTP method GET is not supported by this URL & The specified HTTP method is not allowed for the requested resource

When I open my browser (Chrome) on http://localhost:8084/Staff_Member_office_hours_management/EmailSendingServlet, then I see "service" from doService() being logged on console and my thread works correctly, however I don't see "It Works" from doGet() being logged and I get the following error in the browser:

HTTP method GET is not supported by this URL

How is this caused and how can I solve it?

I have the following servlet:

import java.io.IOException;
import static java.lang.System.out;
import java.security.SecureRandom;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static org.apache.coyote.http11.Constants.a;
 
/**
 * A servlet that takes message details from user and send it as a new e-mail
 * through an SMTP server.
 *
 * @author www.codejava.net
 *
 */
@WebServlet("/EmailSendingServlet")
public class EmailSendingServlet extends HttpServlet {
    
    private String host;
    private String port;
    private String user;
    private String pass;
    private static final Random RANDOM = new SecureRandom();
    public static final int PASSWORD_LENGTH = 8;
    public static String generateRandomPassword()
  {
      // Pick from some letters that won't be easily mistaken for each
      // other. So, for example, omit o O and 0, 1 l and L.
      String letters = "abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789+@";

      String pw = "";
      for (int i=0; i<PASSWORD_LENGTH; i++)
      {
          int index = (int)(RANDOM.nextDouble()*letters.length());
          pw += letters.substring(index, index+1);
      }
      return pw;
  }
    public void init() {
        // reads SMTP server setting from web.xml file
        ServletContext context = getServletContext();
        host = context.getInitParameter("host");
        port = context.getInitParameter("port");
        user = context.getInitParameter("user");
        pass = context.getInitParameter("pass");
        
    }
 
    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        response.setContentType("registeration.jsp");
        String recipient = request.getParameter("mail");
        String id = request.getParameter("id");
        String subject = "Temporary Password to your account";
        String content = generateRandomPassword();
 
        String resultMessage = "";
        try {
            
                Class.forName("com.mysql.jdbc.Driver");
                String urldb = "jdbc:mysql://localhost:3306/staffmember";
                String userdb = "root";
                String passworddb = "";
                String Line;
                Connection Con = null;
                Statement Stmt = null;
                PreparedStatement preparedStatement = null;
                Con = DriverManager.getConnection(urldb, userdb, passworddb);
                Stmt = Con.createStatement();
                //out.print("mmmmmm");
                String query4 = "UPDATE student SET password = '" + content + "' WHERE id = '" + id + "';";
                preparedStatement = Con.prepareStatement(query4);
                int rows3 = preparedStatement.executeUpdate(query4);
            } catch (SQLException cnfe) {
                System.err.println("Exception: " + cnfe);
            } catch (ClassNotFoundException ex) {
            Logger.getLogger(EmailSendingServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
 
        try {
            EmailUtility.sendEmail(host, port, user, pass, recipient, subject,
                    content);
            resultMessage = "The e-mail was sent successfully";
        } catch (Exception ex) {
            ex.printStackTrace();
            resultMessage = "There were an error: " + ex.getMessage();
        } finally {
            request.setAttribute("Message", resultMessage);
            getServletContext().getRequestDispatcher("/Result.jsp").forward(
                    request, response);
        }
    }
   
}

I have another the following servlet:

import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.servlet.http.HttpSession;

public class registeration extends HttpServlet {

   
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        response.setContentType("text/html");
        String id = request.getParameter("id");
        String name = request.getParameter("name");
        String mail = request.getParameter("mail");
        String phone = request.getParameter("mobile");
        String password ="";
        response.setContentType("text/html;charset=UTF-8");
        Connection con = null;
        Statement stmt = null;
        ResultSet RS = null;
        PreparedStatement pst = null;
        boolean status = true;

       
        try (PrintWriter out = response.getWriter()) {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/staffmember";
            String user = "root";
            String passworddb = "";
            con = DriverManager.getConnection(url, user, passworddb);
           
             //out.println("Registered Successfully 1");
            if (mail != null && mail.trim().length() > 0) {
            stmt = con.createStatement();
            String fetchEmail = "Select mail from student where mail=" + "'" + mail + "'";
            ResultSet rs = stmt.executeQuery(fetchEmail);
             //out.println("Registered Successfully 2");
            if (!rs.next()) {
                String sql = "insert into student values('" + name + "','" + mail + "','" + phone + "','" +id + "','" + password +"')";
                status = stmt.execute(sql);
                out.println("Registered Successfully");
                response.sendRedirect("EmailSendingServlet");
                out.println("Click " + "<a href="login.jsp">Here</a>" + " to signin");
                
            } else {
                out.print("<span id="msg" style="color:red;">" + mail + "</span>" + " is already registered. Click "
                        + " <a href="login.jsp">Here</a>" + " to signin");
                

            }
        } else {
            String sql = "insert into student values('" + name + "','" + mail + "','" + phone + "' ,'" + id + "','" + password +"')";
            status = stmt.execute(sql);
            out.println("Registered Successfully");
            out.print("Click " + "<a href="login.jsp">Here</a>" + " to signin");
        }
            
        } catch (Exception e) {
        out.println(e);
    } finally {
        try {
            con.close();
        } catch (SQLException e) {
        }

    }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>FileUploadPdf</servlet-name>
        <servlet-class>FileUploadPdf</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>Search</servlet-name>
        <servlet-class>Search</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>showStaff</servlet-name>
        <servlet-class>showStaff</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>makeReservation</servlet-name>
        <servlet-class>makeReservation</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>canelTransaction</servlet-name>
        <servlet-class>canelReservation</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>cancelReservation</servlet-name>
        <servlet-class>cancelReservation</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>notification</servlet-name>
        <servlet-class>notification</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>messagetostaff</servlet-name>
        <servlet-class>messagetostaff</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>LoginServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>registerat

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

It is probably because you have not overriden doGet method in EmailSendingServlet. This class has overriden only doPost method. You have to move your code to doGet overridden method from doPost.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...