JSP第八次作业
1.登陆
输入用户名密码,判断用户名和密码相同,登陆成功,session中保存用户的用户名,进入主页main.jsp,主页有一个退出按钮,点击,回到登陆页login.jsp。要求:退出登录后,如果在浏览器直接输入主页main.jsp,访问不了,直接跳到登陆页。
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <html> <head> <title></title> </head> <body> <form name="Login" action="dologin.jsp" method="post"> 用户名:<input type="text" name="uname"><br> 密码: <input type="password" name="password"> <br> <input type="button" value="登录" onclick="login()"> </form> <script type="text/javascript"> function login() { if (Login.uname.value == "") { alert("账号不能为空!"); return; } if (Login.password.value == "") { alert("密码不能为空!"); return; } Login.submit(); } </script> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <html> <head> <title>e</title> </head> <body> <% request.setCharacterEncoding("utf-8"); String uname = request.getParameter("uname"); String pwd = request.getParameter("password"); if(uname.equals(pwd)){ session.setAttribute("uname", pwd); request.getRequestDispatcher("main.jsp"); }else{ response.sendRedirect("error.jsp"); } %> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <html> <head> <title></title> </head> <body> <% String uname = (String) session.getAttribute("uname"); if (uname == null) response.sendRedirect("login.jsp"); %> 欢迎你<%=uname%><br> <br> <a href="exit.jsp">退出登录</a> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<html>
<head>
<title></title>
</head>
<body>
<h1>登陆失败!!</h1>
<% response.setHeader("refresh", "5;url=login.jsp"); %>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <html> <head> <title></title> </head> <body> <% session.invalidate(); response.setHeader("refresh", "5;url=login.jsp"); %> <h1>退出登录成功!</h1> </body> </html>
2.购物车
和上一题一起,在main.jsp中做一个购物车,里面显示3个商品名和价格 每一个后面有一个加入购物车按钮,main.jsp中有一个按钮(或者超链接)可以显示购物车。(选作:在购物车中加删除按钮删除商品)
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <html> <head> <title></title> </head> <body> <% String uname = (String) session.getAttribute("uname"); if (uname == null) response.sendRedirect("login.jsp"); %> 欢迎你<%=uname%><br> <br> <a href="exit.jsp">退出登录</a> 商品展示: <br> 欢迎购买玩具: <br> <form action="show.jsp" method="post"> 请选择要加入购物车的商品:<br> <input type="checkbox" name="list" value="悠悠球">悠悠球 50<br> <input type="checkbox" name="list" value="魔方">魔方 10<br> <input type="checkbox" name="list" value="奥特曼">奥特曼 30 <br> <input type="submit" value="加入购物车"> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <html> <head> <title></title> </head> <body> <h2>购物车添加的商品有:</h2> <% request.setCharacterEncoding("utf-8"); String listName[] = request.getParameterValues("list"); if (listName == null) { out.print("购物车为空!"); } else { for (int i = 0; i < listName.length; i++) { out.print("(" + (i + 1) + ")" + listName[i] + "<br>"); } } %> </body> </html>