Javaweb笔记05课后作业

对着背影说爱祢 提交于 2019-12-29 21:54:20

(1)使用Cookie简化用户登录
login.jsp界面

代码如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>登录界面</title>
</head>
<body>
<form action="index.jsp" method="post">
    用户名:<input type="text" name="user"/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>

index界面代码

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>欢迎您</title>
</head>
<body>
<%
  String user = request.getParameter("user");
  if(user != null && !user.trim().equals("")){
    Cookie cookie = new Cookie("user",user);
    cookie.setMaxAge(30);
    response.addCookie(cookie);
  }else{
    Cookie[] cookies = request.getCookies();
    if(cookies != null && cookies.length > 0){
      for(Cookie cookie:cookies){
        String cookieName = cookie.getName();
        if("user".equals(cookieName)){
          String val = cookie.getValue();
          user = val;
        }
      }
    }
  }
  if(user != null && !user.trim().equals("")){
    out.print("hello: " + user);
  }else{//否则重定向到登录界面
    response.sendRedirect("login.jsp");
  }
%>
</body>
</html>

效果图:
在这里插入图片描述
直接进入index.jsp界面,不用再提交
在这里插入图片描述

(3)网页计数器

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
  <title>Insert title here</title>
</head>
<body>
<%
  if(application.getAttribute("count")==null){
    application.setAttribute("count", new Integer(0));
  }
  Integer count = (Integer)application.getAttribute("count");
  application.setAttribute("count",new Integer(count.intValue()+1));
%>
<h2>
  欢迎来到本网页,此网页已被访问 <font color="#ff0000"><%=application.getAttribute("count") %></font>次。。。。
</h2>
</body>
</html>

每次刷新都会次数加一次
在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!