Когда я вызываю doPost напрямую, он показывает мне страницу профиля правильным образом. Но после регистрации я открываю новую вкладку в Chrome Копировать URL «http://localhost:8080/17_servlets_jsp/profile» там и он показывает мне пустую страницуНе могу позвонить doPost из doGet
@WebServlet("/profile")
public class Profile extends HttpServlet {
**private String login;**
private HttpSession httpSession;
private User user;
private Role role;
public static Logger LOGGER = LogManager.getLogger(Profile.class.getName());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
httpSession = req.getSession();
try (PrintWriter out = resp.getWriter()) {
**if (httpSession.getAttribute("userLoggedIn") == null) {
out.println("<title>Login Page</title>");
out.println("<p><a href=\"index\">Please follow the link to login</a></p>");
} else {
login = (String) httpSession.getAttribute("uLogin");
doPost(req, resp);
}**
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
**login = req.getParameter("login");
user = new ImplUserDAO().findByLogin(login);**
httpSession = req.getSession();
resp.setContentType("text/html");
try (PrintWriter out = resp.getWriter()) {
out.println("<title>Profile page</title>");
if (user != null && user.getPassword().equals(req.getParameter("pass"))) {
role = new ImplRoleDAO().findById(user.getRoleId());
httpSession.setAttribute("userLoggedIn", true);
httpSession.setAttribute("uLogin",req.getParameter("login"));
httpSession.setAttribute("uPass",req.getParameter("pass"));
out.println("user id = " + user.getUserId());
out.println("login = " + user.getLogin());
out.println("password = " + user.getPassword());
out.println("role = " + role.getRoleName());
out.println("<form action=\"logout\" method=\"get\"/>" +
"<input type=\"submit\" value=\"Logout\"/>" +
"</form>");
if (role.getRoleName().equals("admin")) {
httpSession.setAttribute("isAdmin", true);
out.println("<a href=\"admin\">Go to admin page</a>");
}
} else {
out.println("Wrong login or password");
out.println("<a href=\"index\">Please follow the link to login</a>");
}
} catch (IOException | NullPointerException e) {
LOGGER.error(e);
}
}
}
Посещение HTTP: // локальный: 8080/17_servlets_jsp/профиль должен вызвать doGet, потому что это запрос както определение. Что вас беспокоит в таком поведении? –
Да. Я знал это, но когда я вызываю doGet этим действием, я ожидаю, что doPost, если пользователь войдет в систему, или «Пожалуйста, следуйте ссылке для входа», если пользователь не зарегистрирован. –
Избавиться от этих глупых блоков try-catch (это основная причина проблемы с пустой страницей) и переместить HTML-код в JSP (это основная причина того, что вы заставляете себя плохо работать). Избавьтесь от этих переменных экземпляра на основе запроса/сеанса (пока это не причина, но, безусловно, будет в будущем). Начните здесь, чтобы узнать, как правильно использовать сервлеты: http://stackoverflow.com/tags/servlets/info – BalusC