JSP +HTML + Servlet 实现将用户名显示在登陆页面
分别创建 login/error.html/success.jsp使用jsp语法编写java代码文件,再通过loginServlet.java文件获取用户输入的数据
login.html
创建登陆界面
<form action="login" method="post">
<div>用户名<input type="text" name="username" /></div>
<div>密 码<input type="password" name="password" />
</div> <div>验证码<input type="text" name="verifycoide" maxlength="4"/></div>
<button>登录</button>
</form>
error.html
提示密码错误
<h1>验证码错误,请重新输入</h1>
返回按钮
<a href="login.html">重新登录</a>
success.jsp
<h1 id="wel">尊敬的会员:<%=request.getAttribute("username")%>,欢迎回来~</h1>
loginServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String userName = request.getParameter("username");
String passWord = request.getParameter("pw");
String verifyCode = request.getParameter("verifycode");
if ("1234".equals(verifyCode)) { //验证码验证
if ("rosin".equals(userName)&&"123456".equals(passWord)) { //输入用户名及密码
//将 ("userName","rosin");请求转发到 ("success.jsp") ,实现在html中显示变量
request.setAttribute("userName","rosin");
request.getRequestDispatcher("success.jsp").forward(request, response);
} else {
PrintWriter out = response.getWriter();
out.write("<h1>"+"密码输入错误,请重新输入"+"</h1>");
out.write("<br>");
out.write("<a href='login.html'>重新登陆</a>");
}
} else {
response.sendRedirect("error.html");
}
}