Complete the SelectServlet.java
In this step, you will learn how to complete the SelectServlet.java
file, which is responsible for handling the user query request and retrieving the user information from the database.
-
Open the SelectServlet.java
file located in the ServletMvc/src/main/java/org/labex/servlet
directory.
-
The SelectServlet
class should handle the user query request and retrieve the user information from the database. You can use the following code to achieve this:
package org.labex.servlet;
import org.labex.dao.UserDao;
import org.labex.entity.User;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SelectServlet extends javax.servlet.http.HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
// Receive parameters sent by the view
String username = request.getParameter("uname");
// create the JavaBean for database operations
UserDao userDao = new UserDao();
// Pass the parameters to the getUserByName method in userDao and pass in the query parameters
User user = userDao.getUserByName(username);
// Put user information into the session
request.getSession().setAttribute("user", user);
// Upon completion, redirect to the showUser.jsp page
request.getRequestDispatcher("/showUser.jsp").forward(request, response);
}
}
In this code, we first receive the username
parameter sent by the view. Then, we create a UserDao
object, which is responsible for interacting with the database. We call the getUserByName
method of the UserDao
object, passing in the username
parameter, to retrieve the user information. Finally, we store the user
object in the session and forward the request to the showUser.jsp
page.