Announcement

Collapse
No announcement yet.

Frage zu doPost()-Methode von Servlets

Collapse
X
  • Filter
  • Time
  • Show
Clear All
new posts

  • Frage zu doPost()-Methode von Servlets

    Ich habe einen ExtJS-Controller, von welchem aus ich einen AJAX-Request an ein Servlet sende. Die ExtJS-Klasse sieht so aus:

    Code:
    Ext.define('app.view.main.MainController', {
    extend: 'Ext.app.ViewController',
    
    alias: 'controller.main',
    
    onItemSelected: function (sender, record) {
    Ext.Msg.confirm('Confirm', 'Are you sure?', 'onConfirm', this);
    },
    
    onConfirm: function (choice) {
    if (choice === 'yes') {
    
    var xhttp = new XMLHttpRequest();
    xhttp.open("POST", "/mave/db", true);
    xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xhttp.send("text");
    
    }
    }
    });
    
    Die doPost-Methode des Servlets wird aufgerufen, das habe ich überprüft. Diese sieht wie folgt aus:
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    
    processRequest(request, response);
    
    
    }
    Was ich fragen wollte ist - wie gelange ich in der doPost-Methdode nun an den Text ("text"), welchen ich dem Servlet ja senden will?
    Zuletzt editiert von pkm; 11.09.2019, 09:14.
    𒍣𒌓𒋤𒁺
    www.ufocasebook.com

  • #2
    https://docs.oracle.com/javaee/6/api...tml#getReader()

    Den Stream in einen String o.a. speichern
    Christian

    Comment


    • #3
      Ich versuche nun den Inhalt des request-Objekts über einen Inputstream auszulesen, einem StringBuilder anzuhängen, um das Ergebnis dann in eine Datei zu speichern, was aber leider auch nicht klappt

      Code:
      /*
      
      * To change this license header, choose License Headers in Project Properties.
      
      * To change this template file, choose Tools | Templates
      
      * and open the template in the editor.
      
      */
      
      package com.mavenproject.mave;
      
      
      
      [JAVA]
      import java.io.BufferedWriter;
      
      import java.io.*;
      
      import java.io.PrintWriter;
      
      import javax.servlet.ServletException;
      
      import javax.servlet.http.HttpServlet;
      
      import javax.servlet.http.HttpServletRequest;
      
      import javax.servlet.http.HttpServletResponse;
      
      
      
      
      /**
      
      *
      
      * @author andfe
      
      */
      
      public class DB extends HttpServlet {
      
      
      
      
      /**
      
      * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
      
      * methods.
      
      *
      
      * @param request servlet request
      
      * @param response servlet response
      
      * @throws ServletException if a servlet-specific error occurs
      
      * @throws IOException if an I/O error occurs
      
      */
      
      protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      
      throws ServletException, IOException {
      
      response.setContentType("text/html;charset=UTF-8");
      
      try (PrintWriter out = response.getWriter()) {
      
      /* TODO output your page here. You may use following sample code. */
      
      out.println("<!DOCTYPE html>");
      
      out.println("<html>");
      
      out.println("<head>");
      
      out.println("<title>Servlet DB</title>");
      
      out.println("</head>");
      
      out.println("<body>");
      
      out.println("<h1>Servlet DB at " + request.getContextPath() + "</h1>");
      
      out.println("</body>");
      
      out.println("</html>");
      
      }
      
      }
      
      
      
      
      // <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);
      
      write(request);
      
      }
      
      
      
      
      /**
      
      * Returns a short description of the servlet.
      
      *
      
      * @return a String containing servlet description
      
      */
      
      @Override
      
      public String getServletInfo() {
      
      return "Short description";
      
      }// </editor-fold>
      
      
      
      
      
      
      private void write(HttpServletRequest request) {
      
      
      
      BufferedReader reader = null;
      
      
      
      String line;
      
      StringBuilder sb = new StringBuilder();
      
      try {
      
      
      
      reader = new BufferedReader(new InputStreamReader(request.getInputStream()));
      
      
      
      while ((line = reader.readLine()) != null) {
      
      sb.append(line);
      
      }
      
      } catch (IOException e) {
      
      e.printStackTrace();
      
      
      
      }finally {
      
      
      
      
      if (reader != null) {
      
      try {
      
      reader.close();
      
      } catch (IOException e) {
      
      e.printStackTrace();
      
      }
      
      }
      
      }
      
      
      
      try{
      
      
      
      BufferedWriter bw = new BufferedWriter(new FileWriter("C:\\Users\\andfe\\Desktop\\log.txt"));
      
      
      
      bw.write(sb.toString());
      
      
      
      
      bw.close();
      
      
      
      
      } catch (IOException e) {
      
      e.printStackTrace();
      
      }
      
      }
      
      
      
      
      }
      Zuletzt editiert von pkm; 11.09.2019, 09:16.
      𒍣𒌓𒋤𒁺
      www.ufocasebook.com

      Comment


      • #4
        Formatiere deinen Beitrag, wer soll sich das so ansehen?
        "was aber leider auch nicht klappt" ist kein Fehler

        https://www.baeldung.com/convert-input-stream-to-string
        Christian

        Comment


        • #5
          Wenn ich den Debugger richtig verstehe, dann werden durch den AJAX-call keine Daten gesendet, denn postData ist Null (siehe Anhang 1). Deswegen bekomme ich auch in der while-Schleife der write()-Methode eine IOException. Ich verstehe nur nicht, was an dem AJAX-call falsch ist.

          Code:
          import java.io.BufferedWriter;
          import java.io.*;
          import java.io.PrintWriter;
          import java.nio.charset.Charset;
          import java.nio.charset.StandardCharsets;
          import java.util.logging.FileHandler;
          import java.util.logging.Handler;
          import java.util.logging.Level;
          import java.util.logging.Logger;
          import java.util.logging.SimpleFormatter;
          import javax.servlet.ServletException;
          import javax.servlet.http.HttpServlet;
          import javax.servlet.http.HttpServletRequest;
          import javax.servlet.http.HttpServletResponse;
          import org.apache.commons.io.IOUtils;
          
          
          /**
           *
           * @author andfe
           */
          public class DB extends HttpServlet {
          
              private static final Logger logger = Logger.getLogger(DB.class.getName());
          
              /**
               * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
               * methods.
               *
               * @param request servlet request
               * @param response servlet response
               * @throws ServletException if a servlet-specific error occurs
               * @throws IOException if an I/O error occurs
               */
              protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                      throws ServletException, IOException {
                  response.setContentType("text/html;charset=UTF-8");
                  try (PrintWriter out = response.getWriter()) {
                      /* TODO output your page here. You may use following sample code. */
                      out.println("<!DOCTYPE html>");
                      out.println("<html>");
                      out.println("<head>");
                      out.println("<title>Servlet DB</title>");            
                      out.println("</head>");
                      out.println("<body>");
                      out.println("<h1>Servlet DB at " + request.getContextPath() + "</h1>");
                      out.println("</body>");
                      out.println("</html>");
                  }
              }
          
              // <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);
                  write(request);
              }
          
              /**
               * Returns a short description of the servlet.
               *
               * @return a String containing servlet description
               */
              @Override
              public String getServletInfo() {
                  return "Short description";
              }// </editor-fold>
          
          
              private void write(HttpServletRequest request) {
          
                  setup(logger);
                   logger.log(Level.SEVERE, "Logger set up.");
          
             InputStream inputStream = null;
          
             try{
                 logger.log(Level.SEVERE, "Now reading input stream.");
          
                     try {
          
                         inputStream = request.getInputStream();
          
                     } catch (IOException e) {
          
                      logger.log(Level.SEVERE, "Encountered IOException.");
                      e.printStackTrace();
          
                      }
          
          
             } catch(NullPointerException e){
          
                 logger.log(Level.SEVERE, "Encountered a NullPointerException.");
                 e.printStackTrace();
          
             }
          
                 if(inputStream == null){
          
                     logger.log(Level.SEVERE, "Inputstream is null.");
          
                 } else{
          
                  logger.log(Level.SEVERE, "Reading result.");
          
                  //String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8); Not like this.
                  StringBuilder sb = new StringBuilder();
          
                  byte[] buffer = new byte[1024];
                  int length;
                  try {
                      while ((length = inputStream.read(buffer)) != -1) {
                          sb.append(new String(buffer, 0, length));
                      }
                  } catch (IOException ex) {
                      logger.log(Level.SEVERE, "Encountered IOException.");
                  }
          
                  if(sb.length() == 0){
                    logger.log(Level.SEVERE, "Result empty.");
                  }
          
                   logger.log(Level.SEVERE, "Result read.");//But why empty?
          
          
              //new PersistEntity().persist(request.getContextPath());
          }       
              }
          
          ...
          So mache ich den AJAX-call:

          Code:
          Ext.define('app.view.main.MainController', {
              extend: 'Ext.app.ViewController',
          
              alias: 'controller.main',
          
              onItemSelected: function (sender, record) {
                  Ext.Msg.confirm('Confirm', 'Are you sure?', 'onConfirm', this);
              },
          
              onConfirm: function (choice) {
                  if (choice === 'yes') {  
          
                  var xhttp = new XMLHttpRequest();
                  xhttp.open('POST', '/mave/DB', true);
                  xhttp.setRequestHeader('Content-type', 'text/html; charset=ISO-8859-1');
                  xhttp.send('test');
          
                  }
              }
          });
          Attached Files
          𒍣𒌓𒋤𒁺
          www.ufocasebook.com

          Comment


          • #6
            DB ist eine Klasse. Die liegen üblicherweise im WEB-INF Verzeichnis. Das ist für den Clientzugriff gesperrt. Du musst das an eine JSP o.a senden

            Ein Ajax-Aufruf macht doch so keinen Sinn. Es soll doch eine bestehende Seite geändert werden
            Christian

            Comment


            • #7
              Danke für die Tipps. Jetzt funktioniert es wie folgt:

              Code:
              /**
               * This class is the controller for the main view for the application. It is specified as
               * the "controller" of the Main view class.
               *
               * TODO - Replace this content of this view to suite the needs of your application.
               */
              
              Ext.define('app.view.main.MainController', {
                  extend: 'Ext.app.ViewController',
              
                  alias: 'controller.main',
              
                  onItemSelected: function (sender, record) {
                      Ext.Msg.confirm('Confirm', 'Are you sure?', 'onConfirm', this);
                  },
              
                  onConfirm: function (choice) {
                      if (choice === 'yes') {  
              
                      var xhttp = new XMLHttpRequest();
                      xhttp.open('POST', '/mave/DB', true);
                      xhttp.setRequestHeader('Content-type', 'text/plain; charset=ISO-8859-1');
                      xhttp.send('dfdsfkjdsfkjsfdsjfsjfdkjl');
              
                      }
                  }
              });
              Code:
              /*
               * To change this license header, choose License Headers in Project Properties.
               * To change this template file, choose Tools | Templates
               * and open the template in the editor.
               */
              package com.mavenproject.mave;
              
              import java.io.*;
              import java.io.PrintWriter;
              import java.util.logging.FileHandler;
              import java.util.logging.Handler;
              import java.util.logging.Level;
              import java.util.logging.Logger;
              import java.util.logging.SimpleFormatter;
              import javax.servlet.ServletException;
              import javax.servlet.ServletInputStream;
              import javax.servlet.http.HttpServlet;
              import javax.servlet.http.HttpServletRequest;
              import javax.servlet.http.HttpServletResponse;
              
              /**
               *
               * @author andfe
               */
              public class DB extends HttpServlet {
              
                  private static final Logger LOGGER = Logger.getLogger(DB.class.getName());
              
                  /**
                   * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
                   * methods.
                   *
                   * @param request servlet request
                   * @param response servlet response
                   * @throws ServletException if a servlet-specific error occurs
                   * @throws IOException if an I/O error occurs
                   */
                  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                          throws ServletException, IOException {
                      response.setContentType("text/html;charset=UTF-8");
                      try (PrintWriter out = response.getWriter()) {
                          /* TODO output your page here. You may use following sample code. */
                          out.println("<!DOCTYPE html>");
                          out.println("<html>");
                          out.println("<head>");
                          out.println("<title>Servlet DB</title>");
                          out.println("</head>");
                          out.println("<body>");
                          out.println("<h1>Servlet DB at " + request.getContextPath() + "</h1>");
                          out.println("</body>");
                          out.println("</html>");
                      }
                  }
              
                  // <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 {
                          //doPost(request, response);//Do I need this??
                  }
              
                  /**
                   * 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 {
              
                      write(request);
                  }
              
                  /**
                   * Returns a short description of the servlet.
                   *
                   * @return a String containing servlet description
                   */
                  @Override
                  public String getServletInfo() {
                      return "Short description";
                  }// </editor-fold>
              
                  private void write(HttpServletRequest request) {
              
                      LoggerSetup.getInstance().doSetup(LOGGER);
                      //setup(LOGGER);
              
                      LOGGER.log(Level.SEVERE, "Logger set up.");
              
                      ServletInputStream inputStream = null;
              
                      try {
                          LOGGER.log(Level.SEVERE, "Now reading input stream.");
              
                          try {
              
                              inputStream = request.getInputStream();
              
                          } catch (IOException e) {
              
                              LOGGER.log(Level.SEVERE, "Encountered IOException 1.");
              
                          }
              
                      } catch (NullPointerException e) {
              
                          LOGGER.log(Level.SEVERE, "Encountered a NullPointerException.");
              
                      }
              
                      if (inputStream == null) {
              
                          LOGGER.log(Level.SEVERE, "Inputstream is null.");
              
                      } else {
              
                          LOGGER.log(Level.SEVERE, "Reading result.");
              
                          //String result = IOUtils.toString(inputStream, StandardCharsets.UTF_8); Not like this.
                          StringBuilder sb = new StringBuilder();
              
                          byte[] buffer = new byte[1024];
                          int length;
                          try {                            
                              while ((length = inputStream.readLine(buffer, 0, buffer.length)) != -1) {
                                  sb.append(new String(buffer, 0, length));
                              }
                              inputStream.close();
              
                          } catch (IOException ex) {
                              LOGGER.log(Level.SEVERE, "Encountered IOException 2.");
                          }
              
                          if (sb.length() == 0) {
                              LOGGER.log(Level.SEVERE, "Result empty.");
                          }
              
                          LOGGER.log(Level.SEVERE, "Result read.");
              
              
                      }
                  }
              
              }
              𒍣𒌓𒋤𒁺
              www.ufocasebook.com

              Comment

              Working...
              X