实现功能介绍:
实现登录的功能:
如果登录成功转入数据展示页面。
如果登录失败,转入登录页面,并提示信息 用户名密码错误的 数据展示页面做一个判断,并提示
登录信息输入错误,请重新输入。
如果不登录直接访问,请转入到登录页面,并提示请先登录再访问。
代码展示:
登录页面代码展示:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录页</title>
</head>
<body>
<p style="color: red ;font-size:12px"; >
<!--登录信息有误提示-->
<%=request.getAttribute("error")==null?"":request.getAttribute("error")%>
<!--未登录提示-->
<%=request.getAttribute("error1")==null?"":request.getAttribute("error1")%>
</p>
<form method="post" action="login.do">
<p>用户名:<input type="text" name="username"> </p>
<p>密码: <input type="text" name="password"></p>
<p><input type="submit" name="登录"></p>
</form>
</body>
</html>
后端servlet代码展示:
登录部分:
@WebServlet(urlPatterns = "/login.do")
public class loginServlet extends HttpServlet {
StudentDao studentDao = new StudentDao();
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req,resp);
resp.sendRedirect("login.jsp");
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
Student instance = studentDao.findInstance(username, password);
if (null == instance){
req.setAttribute("error","登录信息输入错误,请再次尝试!");//此错误信息只在本页面有效,故存入request作用域
// resp.sendRedirect("login.jsp");
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}else {
req.getSession().setAttribute("username",username);//将用户名存入session作用域并展示
resp.sendRedirect("Studentlist.jsp");
}
}
}
数据展示部分:
@WebServlet(urlPatterns = "/StudentList.do")
public class StudentListServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req,resp);
doPost(req,resp);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// System.out.println(req.getAttribute("username"));
if (req.getAttribute("username") == null){
req.setAttribute("error1","请先登录在查看数据!!!!");//此提示信息应只在本页面有效,故存入request作用域
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}else {
resp.sendRedirect("Studentlist.jsp");
}
}
}
效果展示:
首页:
1:直接点击数据展示:
转入登录页面并提示请先登录再查看数据(只在本页面有效)
2:点击登录填写错误信息:
重新进入登录页面,并提示输入信息错误,重新尝试;(只在本页面有效)
3:登录填写正确信息:
左上角提示欢迎您xxx(并且此信息存入了session作用域,在这个浏览器都可显示)