Learn Servlet-JSP By Building A Social Network Website — Part XVII

Sera Ng.
Tech Training Space
6 min readOct 30, 2020

Apply the AJAX technique to implement adding a new post and comment features

Task 24: Implement Adding a New Post

In the last task, we built the feature that loaded a list of posts as well as associated comments.

In this task, we are going to implement a feature that allows users to add a new post.

AJAX techniques have been used for recent tasks. But all of those AJAX responses were JSP contents which were reasonable because those features contained quite a lot of data required in HTML formats.

However, there are some cases that we don’t need to return a response of HTML tags. Rather, a JSON format would be more appropriate.

In this task and the next ones, we will use JSON as the exchanged data between the client and the server for convenient usage.

As discussed previously, JSON basically is a text format in form of JavaScript objects. One of the advantages of such a text format is that it can also be converted to a specific language object such as a Java object.

For that reason, we need a JAVA library to convert data to JSON before sending back to the web browser.

Step 1:

There are many Java JSON-converted libraries out there, but we are going to use Google Gson.

In your pom.xml file, add the following dependency in the <dependencies> tags:

Then, don’t forget to download declared dependencies.

Step 2:

We need to implement a service method to save post data in the database

In the PostService class, create a new method called addNewPost() with the following implementation:

We just need to provide two parameters:

  • The author id, which is the id of the currently signed-in user
  • The content, which is the text the currently signed-in user has added

The tbl_post also needs to store the creation date for a post, we get the current system date time for that purpose by calling the System.currentTimeMillis() method.

Step 3:

In the package net.learnbyproject.controller, create a new servlet called PostController mapped by the URL pattern “/posts”. Then, implement the processRequest() method as follows:

Since the response of this controller is not a JSP file, rather a JSON object containing data that will inform the web browser of the result of the success or failure of the request, we need to store the result in a Java object so that it can be converted to JSON form before sending back to the web browser.

JSON data is in form of key and value, therefore, using a Map collection should be equivalent:

Map<String, String> options = new HashMap<>();

There are two parameters that will be sent to this controller:

Once the new post has been added to the database successfully, we add a key “result” with the value of “OK” to the map object:

options.put(“result”, “OK”);

Otherwise, with the same key, but the value will be “FAILED”:

options.put(“result”, “FAILED”);

Next, before sending back to the client, we need to convert the Map instance into JSON form using Gson library:

String json = new Gson().toJson(options);

Finally and very important, we need to establish a JSON content type so that the web browser can accept a JSON response. That is because by default the web browser accepts a content type of text/html, and if the result is in different formats, the response will be rejected.

response.setContentType(“application/json”);
response.setCharacterEncoding(“UTF-8”);
response.getWriter().write(json);

Step 4:

The final step in the task will be to update the front-end code so that we can send an adding-new-post request to the server-side.

Open the news-feed.jsp file, in the <script> tags, add the following event handler for the add new post button:

There are some declarations you might want to pay attention to:

In the ajax() function, we supplied the options:

Now, everything is ready for a test.

Don’t forget to clean and build your project.

Check out the complete source code if you get stuck:

https://github.com/stackera/learn-servlet-jsp/blob/main/Task24_AddPost.zip

Task 25: Implement Adding Comments

In the last task, we implemented a feature supporting users to add new posts. In this task, we are going to provide new functionalities that allow users to comment on a post.

Step 1: adding a service method

In the PostService class, create a new method called addNewComment() with the following implementation:

Note that since comments need to be associated with a certain post when adding a new comment, the associated post, which represented by the post’s id, must be inserted as well.

Step 2: updating controller

In the PostController servlet, update the processRequest() method with a new else if {} block as follows:

Most of the code keeps unchanged. I have added a new else if {} block to check if the coming request is “add-comment”. If it is, then we need to get two parameters:

Then, we invoke the service method addNewComment() to insert new data into the database.

Since in both cases of inserting a new post and comment, we will need to create a JSON key of “result” with the associated value as “OK”, I have moved the line of code

options.put(“result”, “OK”);

out of the if block to apply for both if and else-if blocks.

Step 3: updating front-end code

In the news-feed.jsp file, locate the tag segment <div class=”user-post-reply-form”> .. </div> and make a change as follows:

What has been updated is that in the <button> tag, the new attribute “post-id” is added with the value as the associated post’s value.

It is crucial to attach post id to the add comment button because there might have many post sections on the news feed page. Each of those posts’ ids needs to be kept somewhere, which is the <button> tags in our case, so that when the add-new-comment button in that post section is clicked, that post’s id needs to be sent along with the new comment’s content to the server as well.

Next, scroll down and update the <script> tags with the code of handling add new comment button’s event as follows:

The event handler for adding new comment has some declarations that we need to discuss a little bit in details:

$(‘.user-post-reply-form button’)

This selector means that we catch events of the button that is a child of the element having the class name as “user-post-reply-form”. This needs to be done because there are many add new comment buttons in the news feed page, not just one. That’s why we cannot add an id attribute to the add new comment button and use that id as the selector.

$(this).attr(‘post-id’)

Each time an add-new-comment button is clicked, we need to get the post’s id of the current clicked button.

$(this).parent().siblings(‘.user-post-reply-editor’).html();

This is the tricky one. This line of code returns the content of the comment a user has just inputted. Let’s take a look at the HTML segment:

To retrieve the comment’s content, we need to get the content of the <div> tag which has the class value as “user-post-reply-editor”. However, the $(this) selector refers to the <button> tag, which is the child of the <span>, which is a sibling of the <div> tag with the class as “user-post-reply-editor”. Again, we cannot assign an id for this <div> tag because there might be many these kinds of <div> tags on the news feed page.

Therefore, we use the selector $(this).parent() to refer to the <span> tag; then, invoke the method siblings(‘.user-post-reply-editor’) to find the sibling tag which has the class as “user-post-reply-editor”. And that will return the current conteneditable div we are looking for. Finally, we just need to call the html() to retrieve its content.

The ajax() method’s options are quite similar to the one we had in the adding-new-post task. So I believe you can comprehend yourselves.

And everything is ready for adding a new comment on a post.

The complete source code for this task:

https://github.com/stackera/learn-servlet-jsp/blob/main/Task25_AddComment.zip

--

--