完整的项目在github中,数据库使用postgresql,建表语句见项目文档。
下面我分块介绍一下struts2、hibernate、与页面部分的代码。
Struts2
UserAction.java
public class UserAction extends ActionSupport{ private String userid; private String password; private User user; private List<User> listUser; public String showuser() throws Exception{ this.setUserid(getUserid()); User userShow = UserDAO.getUser(userid); return SUCCESS; } public String login () throws Exception{ this.setUserid(getUserid()); this.setPassword(getPassword()); if (this.getUserid()==null||this.getUserid().length()==0){ System.out.println ("请输入userid!"); return ERROR; } else{ List listUserRw = UserDAO.checkUser(userid, password); if(listUserRw.size()>0){ System.out.println("账号密码正确,登陆成功!"); return SUCCESS; } else{ System.out.println("账号或密码错误!"); return ERROR; } } } //省略get set方法 }
hibernate
UserDAO.java
public static List<User> checkUser(String userId,String userPwd) { Transaction tx = null; List<User> list = null; try { Session session = HibernateSessionFactory.getSessionFactory() .openSession(); tx = session.beginTransaction(); Query query = session.createQuery("from User as u where u.userId=:userId and u.userPwd=:userPwd"); query.setString("userId", userId); query.setString("userPwd", userPwd); list = query.list(); tx.commit();} catch (Exception e) { e.printStackTrace(); tx.rollback(); } HibernateSessionFactory.closeSession(); return list; }
前端.jsp
<form action="login.action" method="post"> <input type="text" name="userid" class="username" placeholder="请输入您的用户名!">
<input type="password" name="password" class="password" placeholder="请输入您的用户密码!"> <button type="submit" class="submit_button">登录</button> <div class="error"><span>+</span></div>
</form>