9.13

今天对我以前写的web实现登录功能的代码进行改进,实现了不用选择用户类型,程序可以自动选择登陆后的界面

servlet层函数

public void denglu(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException,SQLException{
request.setCharacterEncoding("utf-8");
String str=request.getParameter("id");
String s1=request.getParameter("password");
if(dao.denglu(str, s1).equals("0")) {
request.setAttribute("message", "用户不存在");
request.getRequestDispatcher("denglu.jsp").forward(request, response);
}
else if(dao.denglu(str, s1).equals("1")) {
request.setAttribute("message", "密码错误");
request.getRequestDispatcher("denglu.jsp").forward(request, response);
}
else {

request.setAttribute("message", "登陆成功");
if(dao.denglu(str, s1).equals("管理员"))
request.getRequestDispatcher("manager.jsp").forward(request, response);
else if(dao.denglu(str, s1).equals("员工")) {
HttpSession session = request.getSession();
session.setAttribute("id", str);
request.getRequestDispatcher("student.jsp").forward(request, response);
}
else {
HttpSession session = request.getSession();
session.setAttribute("id", str);
request.getRequestDispatcher("teacher.jsp").forward(request, response);
}
}
}

 

Dao层函数

public String denglu(String str,String s1) throws SQLException{
String ret="0";
String sql="select * from yonghu where id='"+str+"'";
Connection conn=Dbutil.getConnection();
PreparedStatement pt = conn.prepareStatement(sql);
Statement st=null;
ResultSet rs=null;
try
{
pt=conn.prepareStatement(sql);
rs=pt.executeQuery();
rs.next();
if(rs==null)ret="0";
else {
if(!rs.getString("password").equals(s1))ret="1";
else ret="2";
}
if(ret.equals("2")) {
if(rs.getString("type").equals("管理员"))ret="管理员";
else if(rs.getString("type").equals("员工"))ret="员工";
else ret="教师";
}
}catch(Exception e)
{
e.printStackTrace();
}
finally
{
Dbutil.close(rs, st, conn);
}
return ret;
}

这种方式就是在MySQL中除了用户id和密码外还要在加一列代表用户类型

posted @ 2021-09-13 15:01  王昊宁  阅读(159)  评论(0编辑  收藏  举报