背景与需求
模拟数据库doUser.jsp中存在 ss 用户
一、用户在注册页userCreate.jsp中 注册新用户 ,数据传入 模拟数据库 doUser.jsp 进行验证
如果重名的话,转发到 注册网页userCreate.jsp
如果不重名的话, 重定向到 网站主页index.jsp
二、需求
将用户名存放到cookie中,然后再将 该用户名从cookie中读取取来,放入到 用户名:对话框中 ,
很久以后,再次打开网页时,用户名显示填好,不需要重新再输入。
模拟数据库 doUser.jsp
<body>
<%
request.setCharacterEncoding("utf-8");
String username = request.getParameter("username");
String pwd = request.getParameter("password");
String email = request.getParameter("email");
String[] hobbys = request.getParameterValues("hobby");
%>
用户名:
<%
if(username!=null && !username.equals("")){
if(username.equals("ss")){
//不能在进行注册(此处模拟数据库)
// request对象存储 数据,然后再前台网页显示
request.setAttribute("mess", "已存在,请重新注册");
//转发
request.getRequestDispatcher("userCreate.jsp").forward(request, response);
}else{
//注册成功
//session对象存储数据,然后在前台网页显示,使用session而不用request 是因为 下文用到了 重定向,
//重定向的第二次请求,request实现不了,request只能实现一次请求中的操作
session.setAttribute("mess", "注册成功1");
//建立一个cookie对象
Cookie cookkie=new Cookie("username",username);
//加上 / ,使cookkie的作业域是扩展到WebRoot,而不是当前同级的当前网页和下级网页
cookkie.setPath("/");
//设置cookie的有效期,单位是秒
cookkie.setMaxAge(3600);
//添加cookie到服务器
response.addCookie(cookkie);
//使用重定向
response.sendRedirect(request.getContextPath()+"/index.jsp");
}
%>
<%=username %>
<%}else{
out.println("用户名未填写!");
} %>
主页 index.jsp中代码
<div class="main-top">
<div class="logo"><a href=""><span>新闻大视野</span></a></div>
<div class="login-box">
<%
//使用 session对象 读取已经保存的数据
Object o=session.getAttribute("mess");
out.print(session.getId());
//使用cookie对象 读取数据
String username="";
Cookie[] cooks=request.getCookies();
if(cooks!=null && cooks.length!=0){
for(int i=0;i<cooks.length;i++){
System.out.println(cooks[i].getName());
//如果 遍历 数组得到的数据 等于 之前保存到cookie里的KEY:username的话,获得该值VALUE
if(cooks[i].getName().equals("username")){
username=cooks[i].getValue();
}
}
}
%>
<%=o %>
<label>用户名</label><input type="text" name="uname" value="<%= username%>"/><label>密码</label><input type="text" name="upassword" /><button>登录</button>
</div>
<div class="nav">
<ul class="clearfix">
<li><a href="#">首页</a></li>
<li><a href="#">国内</a></li>
如何使用转发和重定向实现注册成功和失败时页面的跳转(上)以及如何通过cookie实现保存用户名信息?
最新推荐文章于 2021-02-16 16:03:29 发布