JSP и сервлет ошибка с getAttribute пользователя после входа в систему - PullRequest
0 голосов
/ 14 сентября 2018
<% Cliente currentUser = (Cliente) session.getAttribute("username"); %>
<h2>   Username <%= currentUser.getUsername()   %></h2>

Я хочу получить имя пользователя, как только я вошел в систему. Как я могу решить или исправить регистрацию сервлета?

Это логин сервлета. В чем проблема, которая не заставляет меня сохранять имя пользователя после логина?

@WebServlet("/Login")
public class Login extends HttpServlet {

    private static final long serialVersionUID = 1L;

    public Login() {
        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 username = request.getParameter("username");
        String pass = request.getParameter("password");
        try {
            Utente utente = (Utente) Query.TrovaCliente(username, pass);
            if (utente == null) {
                request.getRequestDispatcher("loginError.jsp").forward(request, response);
            } else {
                HttpSession session = request.getSession();
                synchronized (session) {
                    session.setAttribute("utente", utente);
                }
                request.getRequestDispatcher("index.jsp").forward(request, response);
            }
        } catch (SQLException e) {
            request.getRequestDispatcher("loginError.jsp").forward(request, response);
            e.printStackTrace();
        }
    }
}

1 Ответ

0 голосов
/ 14 сентября 2018

Вы уверены, что можете преобразовать атрибут сеанса "username" в Cliente?

<% Cliente currentUser = (Cliente) session.getAttribute("username"); %>
<h2>   Username <%= currentUser.getUsername()   %></h2> // <-- here you get a NullPointer

, что означает, что currentUser равно null, и вы не можете вызывать какую-либо функцию для него,Возможно, вы могли бы сначала распечатать то, что у вас есть в сеансе

<h2> session attribute: <%=session.getAttribute("username"); %> </h2>

, чтобы убедиться, что сеанс действительно содержит тот атрибут, который вы ищете, и что он может быть приведен к объекту Cliente.

РЕДАКТИРОВАТЬ

Из того, что я вижу, вы установили весь объект utente (который, я полагаю, ваш пользовательский объект) в сеансе с помощью клавиши "utente".Атрибут "username" по-прежнему отсутствует.

Что вы можете сделать, это

 <% Utente currentUser = (Utente ) session.getAttribute("utente"); %>
 <h2>   Username <%= currentUser.getUsername()   %></h2> 

, если у класса Utente есть метод getUsername.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...