将表单提交到与数据库交互的Servlet导致空白页面

时间:2011-05-18 11:49:49

标签: jsp servlets

我已使用检查用户名和密码

的bean和servlet编写此代码以从jsp登录

来自mysql数据库。

以下代码:

index.jsp:


<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <style type="text/css">
            body {
                background-color:#AFC7C7;
                padding: 0;
                margin: 0;
            }
            div.wrapper {
                margin-left: 10%;
                margin-right: 10%;
                background-color:#6D7B8D;
                height: 620px;
                padding-top:0px;
                border: thin solid #000000;
            }

            div#image{
                padding-top:1%;
                padding-bottom:1%;
            }
            div#adminlogin{
                width:35%;
                height:50%;
                background-color:#AFC7C7;
                border-width:thin;
                border-style:solid;
                border-color:#000000;
                margin: 0 auto;
                text-align:left;
                overflow: hidden;
                padding: 5px;
            }

            hr {
                height:1px;
                color:#000000;
                background-color:#000000;
                width:99%;
                margin-left: 0 ;
                margin-right: auto ;
                border-style:solid;
            }

            .inputtext {
                width: 350px;
                height: 30px;
                Font-Family:Arial;
                Font-Size:18px
            }

        </style>

        <script language="javascript" type="text/javascript">
            function clearText(field){

                if (field.defaultValue == field.value) field.value = '';
                else if (field.value == '') field.value = field.defaultValue;

            }

        </script>
    </head>
    <body>
        <div class="wrapper">
            <div id="image">
                <p>
                    <img src="${pageContext.request.contextPath}/images/sms1.gif"
                         alt="banner"
                         width=98%
                         height=300
                         /></p>
            </div><!--end of image div-->
            <div id=adminlogin >
                <p>Administrator Login</p>
                <hr/>
                <form method=POST action=loginJsp.jsp>
                    <label>Username<br/>
                        <input type="text" class="inputtext" name="usrnm" value="Your Username"
                               onFocus="clearText(this)" onBlur="clearText(this)"/></label><br/>
                        <br/>
                        <label>Password<br/>
                        <input type="password" class="inputtext" name="pwd" value="Your Password"
                               onFocus="clearText(this)" onBlur="clearText(this)"/></label><br/>
                        <br/>
                    <input type="submit" value="Login"/>
                    <a href="url">Forgotten?</a>
                </form>
            </div><!--end of admin login div-->
        </div>
    </body>
</html>

loginJsp.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
    "http://www.w3.org/TR/html4/loose.dtd">

<%@ page language="Java" import="java.sql.*" %>

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Login stuff</title>
    </head>
    <body>
        <jsp:useBean id="login" scope="request" class="pack1.loginHandle" >
            <jsp:setProperty name="login" property="usrnm" value = "<%=request.getParameter("usrnm")%>"/>
            <jsp:setProperty name="login" property="pwd" value = "<%=request.getParameter("pwd")%>" />
        </jsp:useBean>
        <jsp:forward page="/adminCheck">
            <jsp:param name="usrnm" value="<%=login.getUsrnm()%>" />
            <jsp:param name="pwd" value="<%=login.getPwd()%>" />
        </jsp:forward>
        <%--<h1>Hello, <jsp:getProperty name="login" property="usrnm" />!</h1>--%>
    </body>
</html>

loginBean.java:

public class loginBean {

    public String usrnm;
    public String pwd;
    /**
     * Get the value of usrnm
     *
     * @return the value of usrnm
     */
    public String getUsrnm() {
        return usrnm;
    }

    public String getPwd() {
        return pwd;
    }
    /**
     * Set the value of usrnm
     *
     * @param usrnm new value of usrnm
     */
    public void setUsrnm(String usrnm) {
        this.usrnm = usrnm;
    }

        public void setPwd(String pwd) {
        this.pwd = pwd;
    }


}

adminCheck.java:

import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;

/**
 *
 * @author ken
 */
public class adminCheck extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {

        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        System.out.println("Checking admin login");
        Connection conn = null;
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "mvs_user";
        String dbDriver = "com.mysql.jdbc.Driver";
        String dbUser = "root";
        String dbPass = "";
        String username = "";
        String userpass = "";
        String strQuery = "";
        Statement st = null;
        ResultSet rs = null;
        HttpSession session = req.getSession(true);
        try {
            Class.forName(dbDriver).newInstance();
            conn = DriverManager.getConnection(url + dbName, dbUser, dbPass);
            if (req.getParameter("usrnm") != null && req.getParameter("username") != ""
                    && req.getParameter("pwd") != null && req.getParameter("password") != "") {
                username = req.getParameter("usrnm").toString();
                userpass = req.getParameter("pwd").toString();
                strQuery = "select * from user where username='" + username + "' and  password='" + userpass + "'";
                System.out.println(strQuery);
                st = conn.createStatement();
                rs = st.executeQuery(strQuery);
                int count = 0;
                while (rs.next()) {
                    session.setAttribute("username", rs.getString(2));
                    count++;
                }
                if (count > 0) {
                    res.sendRedirect("adminHome.jsp");
                } else {
                    res.sendRedirect("index.jsp");
                }
            } else {
                res.sendRedirect("login.jsp");
            }
            System.out.println("Connected to the database");
            conn.close();
            System.out.println("Disconnected from database");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

adminHome.jsp:

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <h1>Hello World!</h1>
    </body>
</html>

问题是浏览器只显示loginJsp.jsp的空白页面,但我希望它在adminHome.jsp中显示Hello World。问题出在哪里?请帮我解决问题。

1 个答案:

答案 0 :(得分:3)

您需要正确处理异常。取代

    } catch (Exception e) {
        e.printStackTrace(); // Or System.out.println(e);
    }

通过

    } catch (Exception e) {
        throw new ServletException("Login failed", e);
    }

这样你就不再面对空白页了。现在,您将获得一个默认错误页面,其中包含有关问题原因的完整堆栈跟踪。您当然也可以直接挖掘服务器日志以找到刚刚打印而不是重新抛出的堆栈跟踪。

您的问题有几种可能的原因。可能是ClassNotFoundExceptionSQLException。所有这些都应该足够自我解释。

另见:


无关具体问题,使用<jsp:useBean> Scriptlets 也不是最好的做法。彻底阅读How to avoid Java code in JSP files?