This time, we will continue from the previous Basic Web application creation Servlet / JSP (login function). The aim of this article is to check whether you are logged in or not on the posting screen, and to handle the case when you are not.
Since the posting screen is displayed, create a model of posting information. It is assumed that the user name and text exist in the post.
Article.java
public class Article implements Serializable{
private String userName;
private String text;
Article(){}
Article(String userName,String text){
this.userName = userName;
this.text = text;
}
public String getUserName() {
return this.userName;
}
public String getText() {
return this.text;
}
}
Performs the process of confirming that you are logged in with this controller
--If you are logged in → Forward bulletin-board.jsp
--If you are not logged in → Redirect to login screen
BulletinBoard.java
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext application = this.getServletContext();
List<Article> articleList = (List<Article>) application.getAttribute("articleList"); // 1
if(articleList == null) {
articleList = new ArrayList<Article>();
application.setAttribute("articleList",articleList); // 2
}
HttpSession session = request.getSession();
User loginUser = (User) session.getAttribute("loginUser"); // 3
if(loginUser == null) {
response.sendRedirect("./login"); // 4
}else {
request.getRequestDispatcher("/WEB-INF/view/bulletin-board.jsp").forward(request, response); // 5
}
}
null
, set an empty article list in the application scopebulletin-board.jsp
<h2>This is the bulletin board screen.</h2>
<p><c:out value="${loginUser.name}"/>Is logged in.</p>
The second line prints who is logged in.
If you check the operation and log in, the bulletin board screen will be displayed If you are not logged in, you will be successful if you are redirected to the login page! If you want to delete the session scope once, write the following
request.getSession().removeAttribute("loginUser");
Next time, we will implement the logout function.
Recommended Posts