Servlet 不重定向到 JSP 页面

Posted

技术标签:

【中文标题】Servlet 不重定向到 JSP 页面【英文标题】:Servlet not directing to JSP page 【发布时间】:2014-12-05 18:56:26 【问题描述】:

我们需要使用 Java、html、Bean 和 JSP 编写 Web 应用程序。问题是我从未上过 HTML 或 CSS 课程。

我有一个名为 index.html 的基本 HTML 页面,它在带有提交按钮的文本字段中获取用户的名字和姓氏。当我按下提交时,我收到“页面无法显示错误”。我已经将我的代码与我的导师进行了比较,它非常相似,所以我不确定我做错了什么。任何帮助将不胜感激。

另外,不要介意我可怕的格式。

index.html

<!DOCTYPE html>
<html>
    <head>
        <title>Final Project</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <h1>Welcome to Banking by Tyler Weaver</h1>
        <h4>Please Enter your First and Last Name</h4>
        <form action="BankingControl" method="POST">
            <input type="hidden" name="action" value="Menu">   
            First Name:
            <input type="text" name="FirstName" required/> <br></>
            Last Name:
            <input type="text" name="LastName" required/> <br></>
            <input type="submit" value="Login"/>  
        </form>
    </body>
</html>

BankingControl.java

import beans.User;
import database.mysql;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.logging.Level;
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 utilities.ErrorLogger;

@WebServlet(name = "BankingControl", urlPatterns = "/BankingControl")
public class BankingControl extends HttpServlet 

    private static final String mysqlPrefix = "jdbc:mysql://";
    private static final String hostname = "cs3db.bloomu.edu";
    private static final String databaseName = "CS3";
    private static final String databaseURL = mysqlPrefix + hostname + "/" + databaseName;
    private static final String userName = "tgw46366";
    private static final String password = "tgw46366";

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
        response.setContentType("text/html;charset=UTF-8");

        //Creates mysql database connection with specified information
        MySQL mysql = new MySQL(databaseURL, userName, password);

        //The URL where processor will send.
        String JSP_URL = "/index.html";

        //Tries making a connection to the database
        try (Connection conn = mysql.getConnection()) 
            ErrorLogger.log(Level.INFO, "Database Connection Obtained");

            //Retrieve action from page
            String action = request.getParameter("action").trim();
            //If action is null, make it menu
            if (action == null) 
                action = "Menu";
            

            User user = new User();
            user.setFirstName(request.getParameter("firstName").trim());
            user.setLastName(request.getParameter("lastName").trim());
            request.setAttribute("User", user);

            //Check to see if action is menu
            if (action.equalsIgnoreCase("Menu")) 
                //Place to send information
                JSP_URL = "/Menu.jsp";

                ErrorLogger.log(Level.INFO, "User " + user.getFirstName() + " "
                        + user.getLastName()
                        + " logged in - Menu Page Returned");
             else if (action.equalsIgnoreCase("NewCustomer")) 
                JSP_URL = "/NewCustomer.jsp";

                ErrorLogger.log(Level.INFO, "New Customer Selected");
             else if (action.equalsIgnoreCase("NewAccount")) 
                JSP_URL = "/NewAccount.jsp";

                ErrorLogger.log(Level.INFO, "New Account Selected");
             else if (action.equalsIgnoreCase("AccountTransaction")) 
                JSP_URL = "/Transaction.jsp";

                ErrorLogger.log(Level.INFO, "Account Transaction Selected");
             else if (action.equalsIgnoreCase("Logout")) 
                JSP_URL = "/index.html";

                ErrorLogger.log(Level.INFO, "Logout Selected");
             else 
                ErrorLogger.log(Level.WARNING,
                        "Invalid Option -- index.html Returned");
            

            //If connection cannot be made, throw here
         catch (SQLException ex) 
            ErrorLogger.log(Level.SEVERE,
                    "Not Making a Database Connection at this Time", ex);
        

        //forward to correct JSP
        getServletContext()
                .getRequestDispatcher(JSP_URL)
                .forward(request, response);
    

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
        processRequest(request, response);
    

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException 
        processRequest(request, response);
    

    @Override
    public String getServletInfo() 
        return "Short description";
    


MySQL.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.logging.Level;
import utilities.ErrorLogger;

public class MySQL 

    private final String databaseURL;
    private final String userName;
    private final String password;

    public MySQL(String databaseURL, String userName, String password) 
        this.databaseURL = databaseURL;
        this.userName = userName;
        this.password = password;
        initDB();
    

    private void initDB() 
        try 
            Class.forName("com.mysql.jdbc.Driver").newInstance(); //Not needed for MySQL - here for show only
         catch (ClassNotFoundException ex) 
            ErrorLogger.log(Level.SEVERE, "Could not find the class com.mysql.jdbc.Driver \n"
                    + "Program will now exit. ", ex);
            System.exit(1);
         catch (InstantiationException ex) 
            ErrorLogger.log(Level.SEVERE, "Could not instaniate the class com.mysql.jdbc.Driver \n"
                    + "Program will now exit. ", ex);
            System.exit(1);
         catch (IllegalAccessException ex) 
            ErrorLogger.log(Level.SEVERE, "Could not access the class com.mysql.jdbc.Driver \n"
                    + "Program will now exit. ", ex);
            System.exit(1);
        
        try 
            Connection conn = DriverManager.getConnection(databaseURL, userName, password);
            conn.close();
         catch (SQLException ex) 
            ErrorLogger.log(Level.SEVERE, "Could not connect to the database. "
                    + "Database string = "
                    + databaseURL + " user =  " + userName + " password " + password, ex);
            System.exit(1);
        
    

    public Connection getConnection() 
        Connection conn = null;
        try 
            conn = DriverManager.getConnection(databaseURL, userName, password);
         catch (SQLException e) 
            ErrorLogger.log(Level.SEVERE, "Could not connect to the database. "
                    + "Database string = "
                    + databaseURL + " user =  " + userName + " password " + password);
            System.exit(1);
        
        return conn;
    

    public void closeConnection(Connection connection) 
        if (connection != null) 
            try 
                connection.close();
             catch (SQLException e) 
                ErrorLogger.log(Level.SEVERE, "SQL Exception is thrown while "
                        + "trying to close a Connection object. The connection "
                        + "object was not null.", e);
            
        
    


ErrorLogger.java

import java.io.IOException;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.logging.FileHandler;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.Logger;

public class ErrorLogger 

    private static final String errorFileName = "SQLErrorLogger";
    public static boolean showLogInErrorWindow = true;

    private static Logger errorLogger;

    private static void initializeLogging() throws IOException 
        String logFile = getLogfileName();
        errorLogger = Logger.getLogger(logFile);
        Handler handler = new FileHandler(logFile);
        handler.setFormatter(new java.util.logging.SimpleFormatter());
        if (showLogInErrorWindow) 
            errorLogger.setUseParentHandlers(true);
         else 
            errorLogger.setUseParentHandlers(false);
        
        errorLogger.addHandler(handler);
    

    private static String getFormattedDate(Date date) 
        DateFormat format;
        format = new SimpleDateFormat("MM-dd-yyyy");

        return (format.format(date));
    

    private static String getFormattedTime(Date date) 
        DateFormat format;
        format = new SimpleDateFormat("hh.mm.a");

        return (format.format(date));
    

    private static String getDateTime(Date date) 
        String sDateTime = getFormattedDate(date) + "_"
                + getFormattedTime(date);
        return sDateTime;
    

    private static String getLogfileName() 
        String logFileName = errorFileName;

        Date date = new Date(System.currentTimeMillis());
        String sFormattedDateTime = getDateTime(date);
        logFileName += "_" + sFormattedDateTime;
        logFileName += ".log";

        return logFileName;
    

    public static String getNewLogFileName(String logFileBase, String logFileExt) 
        String logFile = logFileBase;
        Date date = new Date(System.currentTimeMillis());
        String sFormattedDateTime = getDateTime(date);
        logFile += "_" + sFormattedDateTime;
        logFile += logFileExt;
        return logFile;
    

    public static void log(Level level, String message, Throwable ex) 
        if (errorLogger == null) 
            initLogger();
        
        errorLogger.log(level, message, ex);
    

    public static void log(Level level, String message) 
        if (errorLogger == null) 
            initLogger();
        
        errorLogger.log(level, message);
    

    private static void initLogger() 
        try 
            initializeLogging();
         catch (IOException ex) 
            errorLogger = Logger.getLogger(getLogfileName());//Will not write to a file
            errorLogger.log(Level.SEVERE, "Could not create a file handler for teh error logger");
        
    

    public static void main(String[] args) 
        ErrorLogger.log(Level.SEVERE, "Test error Message");
    


除了示例数据库和信息之外,这应该是重现错误的最低要求。所有 JSP 页面都单独加载,但它不会从 index.html 开始。这使得调试应用程序的其余部分变得困难。任何帮助将不胜感激。

目录:


错误图片!

【问题讨论】:

您应该提供完整的 web.xml 以及错误的含义(检查控制台 - 服务器返回错误或浏览器根本不想连接)。伙计们,请尽最小的努力! 我想看看你可能拥有的目录结构和其他控制器。您正在重定向到一个资源,但我不知道该资源是否与 root 位于同一目录中,还是位于其他位置?干杯。 @MichalWilkowski 如何显示 web.xml?我将在上面列出我的目录结构! 顺便说一句,当从 index.html 转到 jsp 时,您的 url 是否如您所愿?我有一种感觉,你的转发是相对的而不是绝对的,所以它实际上发送到一个不正确的 url。 我从 index.html 转到 BankingControl servlet,它将把它定向到一个 jsp。在使用相同结构时,我将 URL 完全按照我的导师放置的方式记录下来。 【参考方案1】:

只是在这里给出一个答案,以防有人遇到这个问题。问题是由于缺少 jars 而发生的内部服务器错误。

【讨论】:

以上是关于Servlet 不重定向到 JSP 页面的主要内容,如果未能解决你的问题,请参考以下文章

servlet中sendRedirect重定向问题

重定向进入空白页面而不重定向到路由 Laravel 5.8

jsp重定向和转发

如何重定向到 Servlet 过滤器中的当前页面?

java web 的重定向问题

条件满足后,私有路由不重定向