本次文章基于第三章的ServletConfig,ServletContext,HttpServletRequest,HttpServletResponse对象完成一个图书订阅系统的购买图书和查看图书购买记录功能。
搭建项目主页面创建一个动态网站项目,在src中新建包com.book.servlet.
在包中,新建HomeServlet作为主页。效果图如下:
为了让一访问项目根路径地址就默认进入HomeServlet,这里需要将 HomeServlet的虚拟地址写入web.xml文件中作为默认的首页地址。
Day07Jsp HomeServlet
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; @WebServlet(urlPatterns = "/HomeServlet", initParams = { @WebInitParam(name = "buy",value = "购买图书"), @WebInitParam(name = "selectOrder",value = "查看订单") }) public class HomeServlet extends HttpServlet { private static final long serialVersionUID = 1L; public HomeServlet() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } 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方法中编写两个超链接发送给浏览器上显示:
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(""); pw.append(""+buy+" "); pw.append(""+selectOrder+" "); pw.append(""); }
这里运行以后,可看到以上的效果图所示的页面。
定义图书实体类因为我们需要展示多本图书供用户进行购买,而每一本图书都需要包含,书名,作者,单价,出版社,购买时间等等数据,因此为采用定义实体类的方式用于分别存储每一本书的这些数据信息。
接着我们在src文件夹中定义包com.book.entity,用于存储创建的所有实体类,点右键新建class类,类名为Book,在Book中定义五个全局变量用于存储以上五个信息,并对其进行数据封装,代码如下:
package com.book.entity; 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; 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创建图书信息列表页面供用户购买图书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 oBooks=new ArrayList (); 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; @WebServlet("/ShowBookInfoServlet") public class ShowBookInfoServlet extends HttpServlet { private static final long serialVersionUID = 1L; public ShowBookInfoServlet() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获得所有图书信息 BookDataUtil util=new BookDataUtil(); ListoBooks=util.getBooks(); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter pw=response.getWriter(); pw.append(""); pw.append(""); //写标题 pw.append(" "); pw.append("书名"); pw.append("作者"); pw.append("单价"); pw.append("出版社"); pw.append(" *** 作"); pw.append(" "); for (int i=0;i"); pw.append(""+oBooks.get(i).getBookName()+""); pw.append(""+oBooks.get(i).getAuthor()+""); pw.append(""+oBooks.get(i).getPrice()+""); pw.append(""+oBooks.get(i).getAddress()+""); pw.append(""); pw.append(""); } pw.append(""); pw.append(""); } 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; @WebServlet("/BuyBookServlet") public class BuyBookServlet extends HttpServlet { private static final long serialVersionUID = 1L; public BuyBookServlet() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获得用于点击购买按钮发送过来的请求 //获得浏览器发送过来的图书的下标 String index=request.getParameter("index"); //将接收的字符串类型转换成int类型 int i=Integer.parseInt(index); //根据用户发送过来的下标,去查找用户将要购买的书籍 List创建提示信息页面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 oList=null; if (object==null) { //说明以前从来没有购买过书 oList=new ArrayList (); oList.add(book); }else { //以前有购买书,只需要拿到List集合继续添加购买记录即可 //不需要重新创建List集合 oList=(List ) object; oList.add(book); } //保存完购买记录,之后存储至ServletContext对象 sc.setAttribute("orders", oList); //购买成功之后,跳转至提示页面 //使用请求转发跳转,因为请求转发可以携带数据跳转页面 request.setAttribute("book", book); request.getRequestDispatcher("alertServlet") .forward(request, 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; @WebServlet("/alertServlet") public class alertServlet extends HttpServlet { private static final long serialVersionUID = 1L; public alertServlet() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Book book=(Book) request.getAttribute("book"); String info="您的《"+book.getBookName()+"》购买成功," + "如果继续购买请点击这里," + "或者5秒之后自动跳回首页"; response.setHeader("refresh", "5;url=HomeServlet"); response.setContentType("text/html"); response.setCharacterEncoding("UTF-8"); PrintWriter pw=response.getWriter(); pw.print(info); } 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; @WebServlet("/SelectOrderServlet") public class SelectOrderServlet extends HttpServlet { private static final long serialVersionUID = 1L; public SelectOrderServlet() { super(); // TODO Auto-generated constructor stub } 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(); ListoBooks=null; if (object!=null) { oBooks=(List ) object; pw.append(""); pw.append(""); //写标题 pw.append(" "); pw.append("书名"); pw.append("作者"); pw.append("单价"); pw.append("出版社"); pw.append("购买时间"); pw.append(" "); for (int i=0;i"); pw.append(""+oBooks.get(i).getBookName()+""); pw.append(""+oBooks.get(i).getAuthor()+""); pw.append(""+oBooks.get(i).getPrice()+""); pw.append(""+oBooks.get(i).getAddress()+""); pw.append(""+oBooks.get(i).getBuyTime()+""); pw.append(""); } pw.append(""); pw.append(""); }else { pw.print("当前还没有购买图书的记录,请先购买再查看!!!"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
并把给Servlet的虚拟地址添加至主页面的第二个超链接上,
其运行的效果如下:
本次文章就到这里,初学者可根据代码完成以上功能,可自行扩展修改图书信息以及删除购买记录的功能等等。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)