简体   繁体   English

从db,java servlet获取数据

[英]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 嗨,我正在编写应获取DVD的java servlet,具体取决于登录的用户。我有方法

    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: 而且我不知道如何在servlet的doGet方法中设置记录的用户ID:

dvds = this.dvdDao.getDvdsByUserId();

loginServlet 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"); 我认为您使用的是表单,因为在servlet中您正在调用doget() 。因此,从表单中调用servlet时也要传递用户ID,而在servlet中,您可以使用userid=request.getParameter("user"); doget()

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 登录后,如果您正在调用任何servlet或jsp页面,则以这种方式将用户保持在会话中

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

and in the servlet you can retrieve by using 在servlet中,您可以使用

session.getAttribute("username");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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