920每日博客

今天对Javaweb的用户登录类型进行判断的实现,以前使用过,但是没有发出来,今天讲一下我的想法,

首先是Java读取MySQL的:

public String login(int Id, String Password) throws SQLException {
String sql = "select * from user ";
Connection conn = Dbutil.getConnection();
Statement st = null;
List<UserBean> list = new ArrayList<>();
UserBean bean = null;
ResultSet rs = null;
try {
st = conn.createStatement();
st.executeQuery(sql);
rs = st.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String pass = rs.getString("password");
String type = rs.getString("type");
bean = new UserBean(id, pass, type);
list.add(bean);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
Dbutil.close(st, conn);
}
for(int i=0;i<list.size();i++){
if(list.get(i).getId()==Id&&list.get(i).getPass().equals(Password)){
return list.get(i).getType();
}
}
return "登录错误";
}
这样的写法不是很好,不过想法就是返回这个用户用户类型,如果密码输入错误或者没有这个id的用户就返回一个登录错误的字符串,然后是在servlet进行判断:
public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException, SQLException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
String id=request.getParameter("id");
String password=request.getParameter("password");
String res=dao.login(Integer.parseInt(id),password);
System.out.println(res+"RESSS");
if(res.equals("登录错误")){
PrintWriter out = response.getWriter();
out.print("<script>alert('登录失败!');window.location.href='Login.html'</script>");
}
else if(res.equals("用户")){

HttpSession session = request.getSession();
session.setAttribute("myid", id);
request.getRequestDispatcher("User.html").forward(request, response);
System.out.println(session.getAttribute("myid")+"session");
}
else if(res.equals("管理员")){

HttpSession session = request.getSession();
session.setAttribute("myid", id);
request.getRequestDispatcher("Manager.html").forward(request, response);
}

}
这里就是获得前台的登录时候的账号密码,然后根据读取数据库的用户类型返回的字符串进行判断,以此来跳转不同的用户界面

原文地址:https://www.cnblogs.com/ruangongwangxiansheng/p/14161602.html