login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>登录</title> </head> <body> <form action="loginServlet" method="post"> 姓名:<input type="text" name="uname"><br> 密码:<input type="password" name="upwd"><br> <button>登录</button> <%-- 获取后台设置在作用域中的数据,并显示 --%> <%-- <span style="color: red;font-size: 12px"><%=request.getAttribute("msg")%></span>--%> <%-- 选择使用EL表达式上面那个表达式会出现默认的null --%> <span style="color: red;font-size: 12px">${msg}</span> </form> </body> </html>
loginServlet.java
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/loginServlet") public class loginServlet extends HttpServlet { @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置编译格式 request.setCharacterEncoding("UTF-8"); //接收参数 String uname=request.getParameter("uname"); String upwd=request.getParameter("upwd"); //判断参数是否为空 if(uname==null|| "".equals(uname.trim())){ //提示用户信息不能为空 request.setAttribute("msg","用户姓名不能为空"); //请求转发,跳转到login.jsp页面 request.getRequestDispatcher("login.jsp").forward(request,response); return; } if(upwd==null|| "".equals(upwd.trim())){ //提示用户信息不能为空 request.setAttribute("msg","用户密码不能为空"); //请求转发,跳转到login.jsp页面 request.getRequestDispatcher("login.jsp").forward(request,response); return; } //账号密码是否正确 假如是uname=hmy upwd=123456 if(!"hmy".equals(uname)||!"123456".equals(upwd)){ request.setAttribute("msg","登录失败"); //请求转发,跳转到login.jsp页面 request.getRequestDispatcher("login.jsp").forward(request,response); return; } //登录成功:跳转到首页 request.getSession().setAttribute("uname",uname); response.sendRedirect("index.jsp"); } }
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> <h2>欢迎<%=session.getAttribute("uname")%>登录</h2> </body> </html>
标签:登录,request,用户,upwd,uname,jsp,import,login,页面 From: https://www.cnblogs.com/hmy22466/p/16794257.html