(1)第一个页面main.jsp,用表单输入用户姓名。
代码如下:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>欢迎界面</title>
</head>
<body>
<h1>欢迎来到本页面,请输入您的名字</h1>
<form action="book.jsp" method="post">
<input type="text" name="username">
<input type="submit" value="发送">
</form>
</body>
</html>
(2)写book.jsp,用表单让用户选择书籍。
代码如下:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>挑选书籍</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
//获取sesion的姓名
String name1=(String)session.getAttribute("username");
//获取表单的名字
String name2 = request.getParameter("username");
//设置session属性username,值为name
if(name1 == null&&name2!=null){
session.setAttribute("username", name2);
}else{//不为空时,修改姓名
out.print(name1+" * "+name2);
if(name1!=name2&&name2!=null){
session.setAttribute("username", name2);
}
}
%>
<form action="count.jsp" method="post">
<p>点击超链接,连接到main.jsp的页面,去修改名字。<a href="main.jsp">欢迎去main.jsp!</a></p>
<p>选择您要购买的书籍:</p>
<input name="book" type="checkbox" value="Java教程"/>Java教程
<input name="book" type="checkbox" value="数据库原理"/>数据库原理
<input name="book" type="checkbox" value="操作系统"/>操作系统
<input name="book" type="checkbox" value="C语言"/>C语言
<input name="book" type="checkbox" value="数据结构"/>数据结构
<br/>
<input type="submit" id="btn" value="提交"><br/>
<p>去结账:<a href="count.jsp">欢迎去count.jsp!</a></p>
</form>
</body>
</html>
(3)最后写count.jsp显示用户名和选择的书籍。
代码如下:
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8" import="java.util.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>结账处</title>
</script>
</head>
<body>
<p>这里是结账处,您的姓名以及选择的书籍:</p>
<%
request.setCharacterEncoding("utf-8");
String username = (String)session.getAttribute("username");
out.print("您的姓名:" + username);
%>
<p> 购物车中的商品:</p>
<%
//checked[]获取表单上的所选书籍
String []check=request.getParameterValues("book");
//获取session里的所选书籍
LinkedList checkedbook=(LinkedList)session.getAttribute("book");
//创建一个集合list
LinkedList <String>list = new LinkedList<String>();
if(check!=null){
Collections.addAll(list,check);
}
if(checkedbook!=null){
list.addAll(checkedbook);
}
session.setAttribute("book",list);
for(int i=0;i<list.size();i++){
//list.get(i);
out.print(list.get(i));
%>
<br/>
<%
}
%>
<p>连接到book.jsp的页面,继续购买书籍:<a href="book.jsp">欢迎去book.jsp!</a></p>
<p>连接到main.jsp的页面,去修改名字:<a href="main.jsp">欢迎去main.jsp!</a></p>
<form action="clear.jsp" method="post">
<input type="submit" value="清空"/>
</form>
</body>
</html>
(5)最后是清空,clear.jsp.
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>clear session</title>
</head>
<body>
<%
//清空session
session.invalidate();
%>
<script type="text/javascript">
history.go(-1);
</script>
</body>
</html>