Как сделать объектную переменную из сервлета видимой в jsp? - PullRequest
0 голосов
/ 13 июня 2019

У меня есть сервлет, возвращающий логическое значение, которое я хочу отобразить в моем JSP, не знаю, какой код мне нужно использовать.

Вещи, которые я изучал, но еще не работал (JSTL)) и что бы это ни было, $ {serviceRequestData ['FN_Contact']}, является.

Имя сервлета - это CustomerExist, а метод в этом сервлете - customerExist.

package MainPackage;

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/CustomerExist")
public class CustomerExist extends HttpServlet  implements DBAccessVariables {
    private static final long serialVersionUID = 1L;


    public CustomerExist() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        customerExist(firstName, lastName);
    }

    private boolean customerExist(String firstName, String lastName) {
        boolean answer = false;
        try {
             Class.forName("com.mysql.cj.jdbc.Driver");

             Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);

             PreparedStatement ps = conn
                        .prepareStatement("select * from Customers WHERE FirstName = ? and LastName = ?");

             ps.setString(1, firstName);
             ps.setString(2, lastName);

             final ResultSet resultSet = ps.executeQuery();

             if (resultSet.next() == false) { 
                 answer = false;
                 } else 
                { 
                do { 
                    answer = true;
                    } while (resultSet.next()); 
                }            

             ps.close();
             conn.close();
          } catch(SQLException se) {
             se.printStackTrace();
          } catch(Exception e) {
             e.printStackTrace();
          }
        System.out.println(answer);
        return answer;
    }
}
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"
    import="MainPackage.*"
    %>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Customer Exist?</title>
</head>
<body>

<c:out value="${CustomerExist.customerExist}" default="default value of c:out"/>
<%-- <c:out value="${'Test'}" default="default value of c:out"/> --%>

</body>
</html>

Вышекод дает мне эту ошибку, когда в моем jsp "Возникла исключительная обработка [/CustomerExist.jsp]".

Я просто хочу, чтобы true или false отображались для пользователя.

1 Ответ

0 голосов
/ 13 июня 2019

Измените ваш метод doPost, setAttribute, чтобы запросить.

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        boolean exist = customerExist(firstName, lastName);
        request.setAttribute("customerExist", exist);
    }

В атрибуте get JSP

<c:out value="${customerExist}" default="default value of c:out"/>
...