简体   繁体   中英

Get data from db, java servlet

Hi I'm writting java servlet which should get DVDs depends on which user is logged in. I have method

    public List<Dvd> getDvdsByUserId(String user_id) throws SQLException {
    List<Dvd> dvds = new ArrayList<Dvd>();
    Connection connection = null;
    PreparedStatement preparedStatement = null;
    ResultSet resultSet = null;

    try {
        connection = getConnection();
        preparedStatement = connection.prepareStatement("SELECT * FROM sedivyj_dvd where user_id = ?;");
        preparedStatement.setString(1, user_id);
        resultSet = preparedStatement.executeQuery();

        while (resultSet.next()) {
            Dvd dvd = new Dvd();
            dvd.setId(resultSet.getInt("id"));
            dvd.setUser_id(resultSet.getString("user_id"));
            dvd.setName(resultSet.getString("name"));
            dvd.setBorrower(resultSet.getString("borrower"));
            dvd.setMail(resultSet.getString("mail"));
            dvd.setBorrow_date(resultSet.getString("borrow_date"));
            dvd.setBorrow_until(resultSet.getString("borrow_until"));
            dvds.add(dvd);
        }

    } catch (SQLException e) {
        throw e;
    } finally {
        cleanUp(connection, preparedStatement);
    }

    return dvds;
}

and I don't know how to set up logged user id in servlet's doGet method:

dvds = this.dvdDao.getDvdsByUserId();

loginServlet

 public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

private UserDao userDao;

@Override
public void init(ServletConfig config) throws ServletException {
    super.init(config);
    DbSettings dbSettings = new DbSettings();

    dbSettings.setServer(config.getServletContext().getInitParameter("dbServer"));
    dbSettings.setPort(Integer.valueOf(config.getServletContext().getInitParameter("dbPort")));
    dbSettings.setUser(config.getServletContext().getInitParameter("dbUser"));
    dbSettings.setPassword(config.getServletContext().getInitParameter("dbPassword"));
    dbSettings.setDatabase(config.getServletContext().getInitParameter("dbDatabase"));

    try {
        this.userDao = new UserDao(dbSettings);
    } catch (ClassNotFoundException e) {
        throw new ServletException("Unable to initialize DB driver", e);
    }
}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    try {
        if (getLoggedUser(request, response) != null) {
            response.sendRedirect("/list");
            return;
        }
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/login.jsp");
        dispatcher.forward(request, response);
    } catch (Exception e) {
        getServletContext().log("error", e);
    }
}


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    try {
        if (getLoggedUser(request, response) != null) {
            response.sendRedirect("/list");
            return;
        }
        String nickname = request.getParameter("nickname");
        String password = request.getParameter("password");

        if (nickname != null && password != null) {
            User user = userDao.getByLogin(nickname);
            if (user != null && UserUtil.checkLogin(user, password)) {
                HttpSession session = request.getSession(true);
                Long userId = user.getId();
                session.setAttribute("userId", userId);
                session.setAttribute("loggedUser", user);
                request.getSession().setAttribute("nickname", nickname);

                response.sendRedirect("/list");
            } else {
                request.setAttribute("message", "Login se nepovedl.");
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/login.jsp");
                dispatcher.forward(request, response);
            }
        } else {
            response.sendRedirect("/login");
        }
    } catch (Exception e) {
        getServletContext().log("error", e);
    }
}
public User getLoggedUser(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession(true);
    User user = (User) session.getAttribute("loggedUser");
    return user;
}
}

Does anybody have an idea please?

根据我对您需求的理解,首先验证用户名和密码是否匹配,然后将控件传递给servlet,以便在请求上设置用户ID。然后,您可以使用request.getParameter()在doGet()方法中获取用户ID。 ) 方法。

Get Logged User Id In Servlet Using Session.

HttpSession session=request.getSession(true); 
session.setAttribute("user", userLoggedId);


Later You can retrieve Session Data :

HttpSession session=request.getSession(true); 
String userId=(String)session.getAttribute("user");

This can be done in many ways. I think you are using form because in servlet you are calling doget() .So while calling the servlet from the form pass the userid also and in servlet you can use userid=request.getParameter("user");

The other way is to keep the user in session

After the login if you are calling any servlet or jsp page then keep the user there in session like this way

session.setAttribute("username","username");

and in the servlet you can retrieve by using

session.getAttribute("username");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM