为啥 doGet 不运行 processRequest?

Posted

技术标签:

【中文标题】为啥 doGet 不运行 processRequest?【英文标题】:Why won't doGet run processRequest?为什么 doGet 不运行 processRequest? 【发布时间】:2018-12-09 13:07:10 【问题描述】:

程序应该工作的方式是后台有一个 javaDB,servlet 可以从中提取。 servlet 从 index.jsp 中获取关键字,并使用该关键字搜索 DB 以获取与该关键字相关的信息。但是 doGet 方法甚至没有尝试在 try/catch 块中运行任何东西。我知道 doGet 方法正在运行,因为我尝试在其中加载测试代码并且它确实显示它,只是不会通过 try/catch 运行。

DBConnector.java

package edu.uwf.cs.dsa;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 *
 * @author Bernd
 */

public class DBConnector extends HttpServlet 

    private Context env;

    @Override
    public void init(ServletConfig config)
            throws ServletException 
        super.init(config);
        try 
            env = (Context) new InitialContext().lookup("java:comp/env");
         catch (NamingException e) 
            throw new ServletException(e.getMessage());
        
    

    private String getUrl() throws NamingException 
    
            return (String)env.lookup("jdbc:derby://localhost:1527/JA112");
    

    private Connection getConnection() 
            throws NamingException, ServletException, ClassNotFoundException, SQLException
    
            Class.forName((String)env.lookup("org.apache.derby.jdbc.EmbeddedDriver"));
            return DriverManager.getConnection(getUrl());
    

    private void getMovies(Connection conn, PrintWriter out) throws SQLException
    
            Statement stmt = conn.createStatement();

            ResultSet rs = stmt.executeQuery("SELECT * from Student");
            while (rs.next()) 
                out.print(rs.getString(1)); out.println("<br />");
                out.print(" " + rs.getString(2)); out.println("<br />");
                out.print(" " + rs.getString(3)); out.println("<br />");
                out.print(" " + rs.getString(4)); out.println("<br />");
                out.println(" " + rs.getString(5)); out.println("<br />");
            
    
    /**
     * 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, NamingException, ClassNotFoundException, SQLException 
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        Connection conn = getConnection();

      //  out.print("<html>\n <head>\n <body>\n<h1>test</h1>\n</body>\n</head>\n</html>");

        try 
            /* TODO output your page here. You may use following sample code. */
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet DBConnector</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet DBConnector at " + request.getContextPath() + "</h1>");
            out.println((String)env.lookup("driver")); 
            out.println("<br />");
            out.println(getUrl()); 
            out.println("<br />");
            out.println(conn);
            getMovies(conn,out);
            out.println("<br />");
            out.println("</body>");
            out.println("</html>");
         finally 
            out.close();
        
    

    // <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 
        try 
            processRequest(request, response);
         catch (Exception e) 
            Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, e);
        
    

    /**
     * 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 
        try 
            processRequest(request, response);
         catch (NamingException ex) 
            Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
         catch (ClassNotFoundException ex) 
            Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
         catch (SQLException ex) 
            Logger.getLogger(DBConnector.class.getName()).log(Level.SEVERE, null, ex);
        
    

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

index.jsp

<%-- 
    Document   : index
    Created on : Nov 21, 2012, 9:20:16 PM
    Author     : Bernd
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <form method="GET" action="/DBServlet/DBConnector">
            <h1>Movie Search</h1>
            Enter Keyword <input type="text" name="keyword" id="keyword">
            <input type="submit" value="submit" id="button">
        </form>
    </body>
</html>

【问题讨论】:

DBConnector如何在web.xml中定义? 【参考方案1】:

我最好的猜测是env变量在正常测试中被初始化为null,你需要在processRequest()方法上添加catch块,这样就很清楚这是错误,现在你只有finally 块,所以 Exception 它是隐藏且不清楚的。

添加块并查看异常后,您需要检查定义 java:comp/env 的配置文件,可能是拼写错误或类似的东西会导致真正的问题。

【讨论】:

以上是关于为啥 doGet 不运行 processRequest?的主要内容,如果未能解决你的问题,请参考以下文章

找不到脚本函数 doget,但我没有在我的代码上使用 doGet

servlet的生命周期,啥情况下调用doGet()和doPost()?

Servlet doGet 在简单的 get 方法上返回 404? [复制]

此 URL 不支持 HTTP 方法 GET,尽管它执行 doGet [重复]

继承了httpservlet重写service()与重写doget()dopost()区别

Servlet详解--doget与dopost区别