Getting value from a servlet to insert into DB using hibernate
我有一个登录页面,它是一个JSP和一个servlet,在其中我使用request.getParameter从登录页面获取用户名。我现在想使用hibernate将用户名插入到mysql数据库中。在我的hibernate程序中,我如何访问用户名????
我的servlet是-
公共类LoginPage扩展HttpServlet {
1 2 3 4 5 6 | public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String username= request.getParameter("username"); System.out.println("Hi " + username); } |
} ??
和Hibernate程序是-
公共类HibernateTest {
1 2 3 4 5 6 7 8 9 10 11 12 | public static void main(String args[]){ Login name = new Login(); name.setUserName("");//////This line shows error. What should be inside"" SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(name); session.getTransaction().commit(); session.close(); } |
} ??
运行时,标记的行显示错误。"应该在其中。"如何从servlet检索用户名??
我在您的代码中看不到任何问题。如果两者都能正常工作,则只需将所有内容移至servlet类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String username= request.getParameter("username"); Login name = new Login(); name.setUserName(username); SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); session.beginTransaction(); session.save(name); session.getTransaction().commit(); session.close(); } |
当然,在一个强大的应用程序中,我们将添加层并应用一些设计模式...