javaweb3显示登陆界面
程序员文章站
2022-04-18 16:11:49
...
实现效果为——
- 实现效果如果输入的登录名称是账号,密码是1234,那么点击登陆——输出你好登陆名称,否则,输出账号或密码错误
@WebServlet("login")
public class LoginController extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<form action='' method='post'>");
stringBuilder.append("登录名称:<input type='text' name='loginName' value=''><br>");
stringBuilder.append("登录密码:<input type='password' name='loginPwd' value=''><br>");
stringBuilder.append("<input type='reset' name='reset' value='取消'>");
stringBuilder.append("<input type='submit' name='submit' value='登录'>");
stringBuilder.append("</form>");
showMsg(resp, stringBuilder.toString());
}
//出现服务器错误 提示 Nullpointer 空指针 在.equals里面可能没有值
//loginName != Null 可以先判断有没有值
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String loginName = req.getParameter("loginName");
String loginPwd = req.getParameter("loginPwd");
String msg; //放在外面为扩大范围 不止在if里面可以用
//.equals是对象和对象之间的比较 loginName.equals()&&loginPwd.equls
if ("Chen".equals(loginName) && "123456".equals(loginPwd)) {
msg = "您好欢迎您," + loginName;
}
else {
msg = "账号或密码错误";
}
showMsg(resp, msg);
}
private void showMsg(HttpServletResponse resp,String msg) throws IOException {
resp.setCharacterEncoding("UTF-8");
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("<html>");
stringBuilder.append("<header>");
stringBuilder.append("<title>Test</title>");
stringBuilder.append("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\">");//可以在我们的网页中按F12查看 直接复制头文件
stringBuilder.append("</header>");
stringBuilder.append("<body>");
stringBuilder.append(msg);
stringBuilder.append("<body>");
stringBuilder.append("</html");
PrintWriter out = resp.getWriter();
out.println(stringBuilder.toString());
out.close();//因为会占用内存所以要清理一下
}
}
在自己的网页输入http://localhost:8080/login 就可以访问
上一篇: 显示登陆界面