Javaweb项目编程之实验六 使用JSP(二)MVC模式

  • Post author:
  • Post category:java




一、实验目标:

理解MVC模式的基本思想;理解两种模型:模型1及模型

熟练掌握MVC模式的编程。



二、实验内容:

1、继续完成上周未完成的作业;

2、请用模型2完成1个功能,功能自选,例如:登录、注册、计算税收或购物车等;

3、继续完善网上购图书程序,采用MVC模式,完成增加计算商品总价及添加商品数量等功能,用JavaBean改写,其中购物车和商品价格等内容都用JavaBean实现,JSP页面实现增加、删除所选图书,显示所选图书及其价格的功能。尽量用EL表达式或JSTL标签库,少用程序片及表达式。

购物车提示:javaBean:

Book.java:存储一本图书的信息

BookList.java:一条记录,用于记录订单的一条信息(可省略)

CartBook.java:购物车,用于存储用户所有购物信息

JSP:

index.jsp:购图书首页

addbook.jsp:添加一条图书信息至购物车。

delbook.jsp:删除一条图书信息至购物车

showCart.jsp:显示购物车的信息



实验代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>注册邮箱</title>
</head>
<body>
	<form action="dasedeal"method="post">
		<table>
			<tr>
				<td>您的学号:</td>
				<td><input type = "text" name = "UserNum"></td>
			</tr>
			<tr>
				<td>您的姓名:</td>
				<td><input type = "text" name = "UserName"></td>
			</tr>
			<tr>
				<td>您的密码:</td>
				<td><input type = "password" name = "Usercode"></td>
			</tr>
			<tr>
				<td> 性别: </td>
				<td>
					 <select name = "selectedComs">
				    	<option value="男"></option>
			            <option value="女"></option>     
		      		 </select>
				</td>
			</tr>
			<tr>
				<td><input type = "submit" value ="注册"></td>
				<td><input type = "reset" value ="重置"></td>
			</tr>
		</table>		
	</form>
</body>
</html>

package beanDemo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class dasedeal
 */
@WebServlet("/dasedeal")
public class dasedeal extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String UserNum = request.getParameter("UserNum");
		String UserName = request.getParameter("UserName");
		String Usercode = request.getParameter("Usercode");
		String selectedComs = request.getParameter("selectedComs");
		
//		if (isChinese(UserName)) {
		if ( (Usercode == null ||"".equals(Usercode))  || (UserName == null ||"".equals(UserName))) {
			request.getRequestDispatcher("fail.jsp").forward(request, response);
		}
		else {
			request.setAttribute("num",UserNum);
			request.setAttribute("name",UserName);
			request.setAttribute("select",selectedComs );
			request.getRequestDispatcher("success.jsp").forward(request, response);
		}
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

package beanDemo;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class dasedeal
 */
@WebServlet("/dasedeal")
public class dasedeal extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		String UserNum = request.getParameter("UserNum");
		String UserName = request.getParameter("UserName");
		String Usercode = request.getParameter("Usercode");
		String selectedComs = request.getParameter("selectedComs");
		
//		if (isChinese(UserName)) {
		if ( (Usercode == null ||"".equals(Usercode))  || (UserName == null ||"".equals(UserName))) {
			request.getRequestDispatcher("fail.jsp").forward(request, response);
		}
		else {
			request.setAttribute("num",UserNum);
			request.setAttribute("name",UserName);
			request.setAttribute("select",selectedComs );
			request.getRequestDispatcher("success.jsp").forward(request, response);
		}
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}
}

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>对不起,登录失败</title>
</head>
<body> 
	<h2>对不起,登录失败,请仔细检查数据是否填写正确!</h2>
</body>
</html>




运行结果:

在这里插入图片描述
在这里插入图片描述



购物车代码

package cc.test.Controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.annotation.WebServlet;
import cc.test.vo.*;
/**
 * 程序运行的首页
 * 在此对书库内容进行初始化
 * @author Administrator
 *
 */
@WebServlet("/index.do")
public final class InitServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public InitServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		HttpSession session=request.getSession();
		ArrayList<Book> bookList=null;//获取图书的相关信息		
		int num=0;//保存图书的本数
		//当第一次访问采购网页,session对象中还没有book购物车信息时,进行初始化。
	  	if (session.getAttribute("bookList")==null){
	     //在session对象中存储图书采购信息,将来可以换成从数据库中获取
	    	bookList=bookStoreInit();  			
	     //将图书信息存入session对象中
	  		session.setAttribute("bookList", bookList);
	  		session.setAttribute("sumNum", String.valueOf(num));	  		
	  	}
	  	//将生成的图书信息显示在网页上	  	
	  	response.sendRedirect("Shopping.jsp");
	}
	
	
	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request,response);
	}
	/**
	 * 初始化图书库
	 * 用一个列表来临时存储图书信息
	 * 以后此处可以改为从数据库中查询出图书信息
	 */
	private static ArrayList<Book> bookStoreInit(){
		ArrayList<Book> bookList=null;
		bookList = new ArrayList<Book>();
  		bookList.add(new Book("10101", "Java核心技术", "img\\10101.jpg", 0));
  		bookList.add(new Book("10102", "Java经典实例", "img\\10102.jpg", 0));
  		bookList.add(new Book("10103", "Java7", "img\\10103.jpg", 0));
  		bookList.add(new Book("10104", "JSP&Servlet", "img\\10104.jpg",0));		
		//System.out.print("init");
  		return bookList;
	}
	
	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}

package cc.test.Controller;

import java.io.IOException;

import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cc.test.vo.Book;
/**
 * Servlet implementation class DeleteServlet
 */
@WebServlet("/delete.view")
public class DeleteServlet extends HttpServlet { 
      
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response)
					throws ServletException, IOException {
		// TODO Auto-generated method stub
//		response.getWriter().append("Served at: ").append(request.getContextPath());
		ArrayList<Book> bookList = null;
		int bookNum = 0;
		int sumNum = 0;
		HttpSession session = request.getSession();
		
		String id = request.getParameter("id");
		String num1 = request.getParameter("num");
		int num = Integer.valueOf(num1);
//		int num = Integer.valueOf(request.getParameter("num"));
		
		if(id!=null) {
			bookList = (ArrayList<Book>)session.getAttribute("bookList");
			sumNum = Integer.parseInt((String)session.getAttribute("sunNum"));
			if(bookList != null) {
				for(int i= 0; i<bookList.size();i++) {
					Book book = bookList.get(i);
					if(id.equals(book.getBookId())) {
						bookNum = book.getBookNum() - num;
						bookList.get(i).setBookNum(bookNum);
					}
				}
				session.setAttribute("bookList", bookList);
				session.setAttribute("sumNum", String.valueOf(sumNum-num));
			}
		}
		response.setContentType("utf-8");
		response.sendRedirect("cart.veiw");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

package cc.test.Controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cc.test.vo.Book;

public class CarServlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
      /*判断得到session对象中存储的book信息是否为空
		不为空的前提下,读出Book数组中的内容,并将数目不为1的图书信息显示在网页上。
	  */
		HttpSession session=request.getSession();
		ArrayList<Book> bookList = (ArrayList<Book>)session.getAttribute("booList");
		
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print("<a href=index.do>返回首页</a>");
		
		out.println("<table border='1'>");
		if (bookList!=null) {
			for (Book book : bookList) {
				
				if (book.getBookNum()>0) {
					out.print("<tr>");
					out.print("<td><img src='"+book.getBookImg()+"'></td>");
					out.print("<td>"+book.getBookName()+"</td>");
					out.print("<td>共有"+book.getBookNum()+"本</td>");
					out.print("<td><a href=delete.view?id="+book.getBookId()+"&num=1>删除1本</a></td>");
					out.print("<td><a href=delete.view?id="+book.getBookId()+"&num="+book.getBookNum()+">删除所有</a></td>");
					out.print("</tr>");
				}
			} 
		}
		out.print("</table>");
		out.close();
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request,response);
	}

}

package cc.test.Controller;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cc.test.vo.Book;

public class ShopingServlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ArrayList<Book> bookList=null;
		int bookNum = 0;
		int sumNum=0;
		HttpSession session = request.getSession();
		
		//获取从Shopping.jsp传来的request对象中的ID号
		String id = request.getParameter("id");
		
        //在ID号不为空的情况下,获取Session对象中的购物车信息,Book对象数组。
		//找到数组中与ID对应的Book对象,将其属性bookNum数字加1
		//将数组写回session对象中去。
		if (id!=null){
			bookList = (ArrayList<Book>)session.getAttribute("bookList");
			sumNum=Integer.parseInt((String)session.getAttribute("sumNum"));
			if (bookList!=null) {
				for(int i=0;i<bookList.size();i++) {
					Book book = bookList.get(i);
					if (id.equals(book.getBookId())) {
						bookNum = book.getBookNum()+1;
						bookList.get(i).setBookNum(bookNum);
						System.out.println(book.getBookName()+"shoppingnum:"+bookNum);
					}
				}
				session.setAttribute("booList", bookList);
				session.setAttribute("sumNum", String.valueOf(sumNum+1));
			}
		}
				
		//跳转回Shopping.jsp
		response.setContentType("UTF-8");
		response.sendRedirect("Shopping.jsp");
		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doGet(request,response);
	}

	

}

package cc.test.vo;

public class Book {
	private String bookId;	//书号
	private String bookName;//书名
	String bookImg;			//书封面所在地址
	private int bookNum;	//购书本数

	public Book(String bookId, String bookName, String bookImg, int bookNum) {
		this.bookId = bookId;
		this.bookName = bookName;
		this.bookImg = bookImg;
		this.bookNum = 0;
	}

	public void setBookNum(int bookNum) {
		this.bookNum = bookNum;
	}

	public String getBookId() {
		return bookId;
	}

	public String getBookName() {
		return bookName;
	}

	public String getBookImg() {
		return bookImg;
	}

	public int getBookNum() {
		return bookNum;
	}

}

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@page import="cc.test.vo.Book" %>
<!-- 
   程序运行的首页是/index.do
-->
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>  
   <body>
    <img src="img/cart.jpg" height="60px" width="60px">
    <a href="cart.view">已采购
    <c:out value="${sumNum}" default="没有任何"/>本书籍
    </a><br>
   <br>
	<table border="1">    
   <%
      ArrayList<Book>  bookList=(ArrayList<Book>)session.getAttribute("bookList");
      for (Book book:bookList){ 
        out.println("<tr>") ; 
        out.println("<td> <img src='"+book.getBookImg()+ "'> </td>");
        String id=book.getBookId();
        out.println("<td> <a href=shopping.view?id="+id+">采购此书</a></td>");
        out.println("</tr>") ; 
       } 
    %>
   <%--  <c:forEach var="book" items="${bookList}">
    <tr>
    <td>
    <img src='${book.bookImg}'>
    </td>
    <td><a href="shopping.view?id='${book.bookId }'">采购此书</a></td></tr> 
    
    </c:forEach>--%>
    
    </table></body>
</html>





运行结果:

在这里插入图片描述

在这里插入图片描述



版权声明:本文为csq542586原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。