【Jsp】第三课 Servlet常用对象(综合案例)

2023-04-11 09:17:11

概述

本次文章基于第三章的ServletConfig,ServletContext,HttpServletRequest,HttpServletResponse对象完成一个图书订阅系统的购买图书和查看图书购买记录功能。

搭建项目主页面

创建一个动态网站项目,在src中新建包com.book.servlet.

在包中,新建HomeServlet作为主页。效果图如下:

为了让一访问项目根路径地址就默认进入HomeServlet,这里需要将 HomeServlet的虚拟地址写入web.xml文件中作为默认的首页地址。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Day07Jsp</display-name>
  <welcome-file-list>
    <welcome-file>HomeServlet</welcome-file>
  </welcome-file-list>
</web-app>

HomeServlet中要完成超链接的显示,这里需要在该Servlet中定义两个静态数据,使用java注解的方式进行定义,代码如下:

package com.book.servlet;

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

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

/**
 * Servlet implementation class HomeServlet
 */
@WebServlet(urlPatterns = "/HomeServlet",
initParams = {
		@WebInitParam(name = "buy",value = "购买图书"),
		@WebInitParam(name = "selectOrder",value = "查看订单")
})
public class HomeServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HomeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
   

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
	}

	/**
	 * @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);
	}

}

然后在类中的空白处,重写init方法,用于加载两个静态数据,因这两个静态数据需要在其他方法中被使用,因此定义成全局变量。代码如下:

再重写init方法,并通过两个静态数据,存储至全局变量。

@Override
    public void init(ServletConfig config) throws ServletException {
    	buy=config.getInitParameter("buy");
    	selectOrder=config.getInitParameter("selectOrder");
    	
    }

 因浏览器访问服务器默认使用Get请求,这里我们在diGet方法中编写两个超链接发送给浏览器上显示:

/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//当浏览器访问该Servlet的时候,servlet将静态数据发给浏览器显示
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw=response.getWriter();
		pw.append("<div align='center'>");
		pw.append("<a href=''>"+buy+"</a>&nbsp;");
		pw.append("<a href=''>"+selectOrder+"</a>&nbsp;");
		pw.append("</div>");
	}

这里运行以后,可看到以上的效果图所示的页面。

定义图书实体类

因为我们需要展示多本图书供用户进行购买,而每一本图书都需要包含,书名,作者,单价,出版社,购买时间等等数据,因此为采用定义实体类的方式用于分别存储每一本书的这些数据信息。

接着我们在src文件夹中定义包com.book.entity,用于存储创建的所有实体类,点右键新建class类,类名为Book,在Book中定义五个全局变量用于存储以上五个信息,并对其进行数据封装,代码如下:

package com.book.entity;
/**
 * 图书的实体类
 * @author teacher
 *	2021/10/14
 */
public class Book {
	//java类的封装
	private String bookName;//书名
	private String author;//作者
	private String price;//单价
	private String address;//出版社
	private String buyTime;//购买时间
	public String getBookName() {
		return bookName;
	}
	public void setBookName(String bookName) {
		this.bookName = bookName;
	}
	public String getAuthor() {
		return author;
	}
	public void setAuthor(String author) {
		this.author = author;
	}
	public String getPrice() {
		return price;
	}
	public void setPrice(String price) {
		this.price = price;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public String getBuyTime() {
		return buyTime;
	}
	public void setBuyTime(String buyTime) {
		this.buyTime = buyTime;
	}
	
	//生成所有变量的get和set方法
	//构造方法的作用:
	//1.用于创建这个类的对象
	//2.用于快速给变量进行赋值
	//生成无参构造方法
	public Book() {
		// TODO Auto-generated constructor stub
	}
	//生成有参构造方法
	public Book(String bookName, String author, String price, String address, String buyTime) {
		super();
		this.bookName = bookName;
		this.author = author;
		this.price = price;
		this.address = address;
		this.buyTime = buyTime;
	}
	@Override
	public String toString() {
		return "Book [bookName=" + bookName + ", author=" + author + ", price=" + price + ", address=" + address
				+ ", buyTime=" + buyTime + "]";
	}
	
	//生成toString方法,为了在做功能的时候,
	//查看检查这个对象中是否有数据
	
	
}

定义临时图书库工具类

这里我们使用List集合临时将多本图书信息存储起来,用于显示在页面上供用户进行购买,这里我们在src文件夹中新建包com.book.util,在包中新建类BookDBUtil,在类中定义方法,创建多本图书信息,并将多本图书存储至List集合,代码如下:

package com.book.util;
/**
 * 图书信息的工具类
 * @author teahcer
 *	2021/10/14
 *用于临时存储一些图书信息
 */

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.book.entity.Book;

public class BookDataUtil {

	//定义方法,用于存储多本书的信息
	public List<Book> getBooks(){
		Book book1=new Book("Java编程思想", "马云", "120.0元", "人民邮电出版社", "");
		Book book2=new Book("MySQL数据库教程", "任正非", "89.0元", "清华大学出版社", "");
		Book book3=new Book("Java疯狂讲义", "马化腾", "108.0元", "电子工业出版社", "");
		Book book4=new Book("Python爬虫技术", "李彦宏", "66.0元", "新华出版社", "");
		Book book5=new Book("C语言从入门到放弃", "李云龙", "56.0元", "江西出版社", "");
		//创建List用于存储以上五本书
		List<Book> oBooks=new ArrayList<Book>();
		oBooks.add(book1);
		oBooks.add(book2);
		oBooks.add(book3);
		oBooks.add(book4);
		oBooks.add(book5);
		return oBooks;
	}
	
	//获得当前实时时间
	public static String getNowTime() {
		//获得的现在实时时间是毫秒计算的
		Date date=new Date();
		//简单日期格式类  2021年10月20 日  13:55:30
		SimpleDateFormat sdf=
				new SimpleDateFormat("yyyy年MM月dd日  HH:mm:ss");
		//按照设定的格式进行格式化
		String time=sdf.format(date);
		return time;
	}
}

创建图书信息列表页面供用户购买图书

即多本图书已准备好,这里需要创建Servlet完成图书信息列表页面,类名为ShowBookInfoServlet,这里我们需要先从工具类中获得所有图书信息,并将该图书已表格的形式发送给浏览器上显示出来,其代码如下:

package com.book.servlet;

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

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 com.book.entity.Book;
import com.book.util.BookDataUtil;

/**
 * Servlet implementation class ShowBookInfoServlet
 */
@WebServlet("/ShowBookInfoServlet")
public class ShowBookInfoServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ShowBookInfoServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获得所有图书信息
		BookDataUtil util=new BookDataUtil();
		List<Book> oBooks=util.getBooks();
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw=response.getWriter();
		pw.append("<div align='center'>");
		pw.append("<table border='1' style='width:800px;text-align:center;'>");
		//写标题
		pw.append("<tr>");
		pw.append("<td>书名</td>");
		pw.append("<td>作者</td>");
		pw.append("<td>单价</td>");
		pw.append("<td>出版社</td>");
		pw.append("<td>操作</td>");
		pw.append("</tr>");
		for (int i=0;i<oBooks.size();i++) {
			pw.append("<tr>");
			pw.append("<td>"+oBooks.get(i).getBookName()+"</td>");
			pw.append("<td>"+oBooks.get(i).getAuthor()+"</td>");
			pw.append("<td>"+oBooks.get(i).getPrice()+"</td>");
			pw.append("<td>"+oBooks.get(i).getAddress()+"</td>");
			pw.append("<td><a href='BuyBookServlet?index="+i+"'><input type='button' "
					+ "style='background-color:green;' "
					+ "value='购买'></a></td>");
			pw.append("</tr>");
		}
		pw.append("</table>");
		pw.append("</div>");
	}

	/**
	 * @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);
	}

}

并在HomeServlet的首页的购买图书的超链接上添加图书信息列表页面的虚拟地址。

其运行后,点击购买图书即课跳转至图书信息列表页面,效果如下:

完成存储用户购买的图书记录信息

当用户点击任意一本图书进行购买的时候,这里我们采取发送给图书的下标给服务器的方式,能尽快的获取用户要购买的图书信息,这里新建一个Servlet类,类名为BuyBookServlet,用于接收用户将要购买的图书的下标,并查找出该图书,并通过方法获得当前购买图书的下单的实时时间,存储至该购买的图书中,然后将该图书存储至List集合,因为用户可能会购买多本图书,最后将所哟购买的图书记录信息存储至ServletContext对象中。

package com.book.servlet;

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

import javax.servlet.ServletContext;
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 com.book.entity.Book;
import com.book.util.BookDataUtil;

/**
 * Servlet implementation class BuyBookServlet
 */
@WebServlet("/BuyBookServlet")
public class BuyBookServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BuyBookServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//获得用于点击购买按钮发送过来的请求
		//获得浏览器发送过来的图书的下标
		String index=request.getParameter("index");
		//将接收的字符串类型转换成int类型
		int i=Integer.parseInt(index);
		//根据用户发送过来的下标,去查找用户将要购买的书籍
		List<Book> oBooks=new BookDataUtil().getBooks();
		Book book=oBooks.get(i);
		//当用户购买图书的时候,需要获得当前实时时间
		book.setBuyTime(BookDataUtil.getNowTime());
		//获得ServletContext对象
		ServletContext sc=getServletContext();
		//判断ServletContext是否存在List集合
		Object object=sc.getAttribute("orders");
		List<Book> oList=null;
		if (object==null) {
			//说明以前从来没有购买过书
			oList=new ArrayList<Book>();
			oList.add(book);
		}else {
			//以前有购买书,只需要拿到List集合继续添加购买记录即可
			//不需要重新创建List集合
			oList=(List<Book>) object;
			oList.add(book);
		}
		//保存完购买记录,之后存储至ServletContext对象
		sc.setAttribute("orders", oList);
		//购买成功之后,跳转至提示页面
		//使用请求转发跳转,因为请求转发可以携带数据跳转页面
		request.setAttribute("book", book);
		request.getRequestDispatcher("AlertServlet")
					.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);
	}

}

 创建提示信息页面

在图书记录信息存储后,需要提示用户购买的图书下单完成,是否需要继续购买的提示,这里新建一个Servlet类,类名为:AlertServlet

package com.book.servlet;

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;

import com.book.entity.Book;

/**
 * Servlet implementation class AlertServlet
 */
@WebServlet("/AlertServlet")
public class AlertServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AlertServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Book book=(Book) request.getAttribute("book");
		String info="您的《"+book.getBookName()+"》购买成功,"
				+ "如果继续购买请<a href='ShowBookInfoServlet'>点击这里</a>,"
				+ "或者5秒之后自动跳回首页";
		response.setHeader("refresh", "5;url=HomeServlet");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw=response.getWriter();
		pw.print(info);
	}

	/**
	 * @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);
	}

}

效果如下:

完成查看图书记录信息列表页面

用户在购买完图书信息之后,需要查看当前购买的所有图书的记录信息,这里我们新建Servlet类,类名为:SelectOrderServlet,从ServletContext类中获得所有的图书记录信息,展示在表格上,并需要判断是否有购买图书记录信息,其代码如下:

package com.book.servlet;

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

import javax.servlet.ServletContext;
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 com.book.entity.Book;

/**
 * Servlet implementation class SelectOrderServlet
 */
@WebServlet("/SelectOrderServlet")
public class SelectOrderServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SelectOrderServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//因为用户购买的图书信息被存储在ServletContext对象中
		//要展示用户的购买记录,需要先获得ServletContext对象
		ServletContext sc=getServletContext();
		//从该对象中获得存储图书记录的List集合
		Object object=sc.getAttribute("orders");
		response.setContentType("text/html");
		response.setCharacterEncoding("UTF-8");
		PrintWriter pw=response.getWriter();
		List<Book> oBooks=null;
		if (object!=null) {
			oBooks=(List<Book>) object;
			pw.append("<div align='center'>");
			pw.append("<table border='1' style='width:800px;text-align:center;'>");
			//写标题
			pw.append("<tr>");
			pw.append("<td>书名</td>");
			pw.append("<td>作者</td>");
			pw.append("<td>单价</td>");
			pw.append("<td>出版社</td>");
			pw.append("<td>购买时间</td>");
			pw.append("</tr>");
			for (int i=0;i<oBooks.size();i++) {
				pw.append("<tr>");
				pw.append("<td>"+oBooks.get(i).getBookName()+"</td>");
				pw.append("<td>"+oBooks.get(i).getAuthor()+"</td>");
				pw.append("<td>"+oBooks.get(i).getPrice()+"</td>");
				pw.append("<td>"+oBooks.get(i).getAddress()+"</td>");
				pw.append("<td>"+oBooks.get(i).getBuyTime()+"</td>");
				pw.append("</tr>");
			}
			pw.append("</table>");
			pw.append("</div>");
		}else {
			pw.print("当前还没有购买图书的记录,请先购买再查看!!!");
		}
		
	}
	

	/**
	 * @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);
	}

}

并把给Servlet的虚拟地址添加至主页面的第二个超链接上,

其运行的效果如下:

本次文章就到这里,初学者可根据代码完成以上功能,可自行扩展修改图书信息以及删除购买记录的功能等等。 

  • 作者:笔触狂放
  • 原文链接:https://blog.csdn.net/u010321564/article/details/120896362
    更新时间:2023-04-11 09:17:11