[Java] Basic Web application creation Servlet/JSP (Post screen)

1 minute read

Introduction

This time, I will continue the Basic Web application creation Servlet/JSP (login function). The purpose of this article is to check whether you are logged in or not on the posting screen, and to process when you do not.

Execution environment

  • Eclipse 4.16
  • Tomcat9
  • Java11

1. Creating a model for posting

Since the posting screen is displayed, create a model of posting information. It is assumed that the post has a user name and text.

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;
}
}

2. Request processing controller for articles

Check if 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
}
}
  1. Get from application scope
  2. If 1 is null, set empty article list to application scope
  3. Get from session scope
  4. If you are not logged in, redirect to the login screen
  5. If you are logged in, display the bulletin board screen

3. Creating a view on the bulletin board screen

bulletin-board.jsp


<h2> This is the bulletin board screen. </h2>
<p><c:out value="${loginUser.name}"/> is logged in. </p>

The second line prints out who is logged in.

4. Execution

If you check the operation and log in, the bulletin board screen is displayed If you are not logged in, you will be redirected to the login page and you will be successful! If you want to delete the session scope once, enter the following

request.getSession().removeAttribute(“loginUser”);

Finally

Next time, we will implement the logout function.