文档章节

来自javaweb高级编程的详细的例子--servlet

木之下
 木之下
发布于 2017/09/09 22:34
字数 792
阅读 7
收藏 0

package com.weisen.demo.servlet;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.weisen.demo.model.Attachment;
import com.weisen.demo.model.Ticket;

/**
 * Servlet implementation class TicketServlet
 */
@MultipartConfig(
  fileSizeThreshold=5_242_880,//5MB
  maxFileSize=20_971_520L,//20MB
  maxRequestSize=41_943_040L//40MB
)
public class TicketServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
 

    private volatile int TICKET_ID_SEQUENCE = 1;
    private Map<Integer, Ticket> ticketDatabase=new LinkedHashMap<>();
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TicketServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

 /**
  * @see Servlet#init(ServletConfig)
  */
 public void init(ServletConfig config) throws ServletException {
  // TODO Auto-generated method stub
 }

 /**
  * @see Servlet#destroy()
  */
 public void destroy() {
  // TODO Auto-generated method stub
 }


    private void showTicketForm(HttpServletResponse response)throws ServletException, IOException{
        PrintWriter writer = this.writeHeader(response);

        writer.append("<h2>Create a Ticket</h2>\r\n");
        writer.append("<form method=\"POST\" action=\"tickets\" ")
              .append("enctype=\"multipart/form-data\">\r\n");
        writer.append("<input type=\"hidden\" name=\"action\" ")
              .append("value=\"create\"/>\r\n");
        writer.append("Your Name<br/>\r\n");
        writer.append("<input type=\"text\" name=\"customerName\"/><br/><br/>\r\n");
        writer.append("Subject<br/>\r\n");
        writer.append("<input type=\"text\" name=\"subject\"/><br/><br/>\r\n");
        writer.append("Body<br/>\r\n");
        writer.append("<textarea name=\"body\" rows=\"5\" cols=\"30\">")
              .append("</textarea><br/><br/>\r\n");
        writer.append("<b>Attachments</b><br/>\r\n");
        writer.append("<input type=\"file\" name=\"file1\"/><br/><br/>\r\n");
        writer.append("<input type=\"submit\" value=\"Submit\"/>\r\n");
        writer.append("</form>\r\n");

        this.writeFooter(writer);
    }

    private void viewTicket(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException{
        String idString = request.getParameter("ticketId");
        Ticket ticket = this.getTicket(idString, response);
        if(ticket == null)
            return;

        PrintWriter writer = this.writeHeader(response);

        writer.append("<h2>Ticket #").append(idString)
              .append(": ").append(ticket.getSubject()).append("</h2>\r\n");
        writer.append("<i>Customer Name - ").append(ticket.getCustomerName())
              .append("</i><br/><br/>\r\n");
        writer.append(ticket.getBody()).append("<br/><br/>\r\n");

        if(ticket.getNumberOfAttachments() > 0)
        {
            writer.append("Attachments: ");
            int i = 0;
            for(Attachment attachment : ticket.getAttachments())
            {
                if(i++ > 0)
                    writer.append(", ");
                writer.append("<a href=\"tickets?action=download&ticketId=")
                      .append(idString).append("&attachment=")
                      .append(attachment.getName()).append("\">")
                      .append(attachment.getName()).append("</a>");
            }
            writer.append("<br/><br/>\r\n");
        }

        writer.append("<a href=\"tickets\">Return to list tickets</a>\r\n");

        this.writeFooter(writer);
    }

 private void downloadAttachment(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  String idString = request.getParameter("ticketId");
  Ticket ticket = this.getTicket(idString, response);
  if (ticket == null)
   return;

  String name = request.getParameter("attachment");
  if (name == null) {
   response.sendRedirect("tickets?action=view&ticketId=" + idString);
   return;
  }

  Attachment attachment = ticket.getAttachment(name);
  if (attachment == null) {
   response.sendRedirect("tickets?action=view&ticketId=" + idString);
   return;
  }

  response.setHeader("Content-Disposition", "attachment; filename=" + attachment.getName());
  response.setContentType("application/octet-stream");

  ServletOutputStream stream = response.getOutputStream();
  stream.write(attachment.getContents());
 }
 
 private void listTickets(HttpServletResponse response)
            throws ServletException, IOException
    {
        PrintWriter writer = this.writeHeader(response);

        writer.append("<h2>Tickets</h2>\r\n");
        writer.append("<a href=\"tickets?action=create\">Create Ticket")
              .append("</a><br/><br/>\r\n");

        if(this.ticketDatabase.size() == 0)
            writer.append("<i>There are no tickets in the system.</i>\r\n");
        else
        {
            for(int id : this.ticketDatabase.keySet())
            {
                String idString = Integer.toString(id);
                Ticket ticket = this.ticketDatabase.get(id);
                writer.append("Ticket #").append(idString)
                      .append(": <a href=\"tickets?action=view&ticketId=")
                      .append(idString).append("\">").append(ticket.getSubject())
                      .append("</a> (customer: ").append(ticket.getCustomerName())
                      .append(")<br/>\r\n");
            }
        }

        this.writeFooter(writer);
    }

 private void createTicket(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  Ticket ticket = new Ticket();
  ticket.setCustomerName(request.getParameter("customerName"));
  ticket.setSubject(request.getParameter("subject"));
  ticket.setBody(request.getParameter("body"));

  Part filePart = request.getPart("file1");
  if (filePart != null && filePart.getSize() > 0) {
   Attachment attachment = this.processAttachment(filePart);
   if (attachment != null)
    ticket.addAttachment(attachment);
  }

  int id;
  synchronized (this) {
   id = this.TICKET_ID_SEQUENCE++;
   this.ticketDatabase.put(id, ticket);
  }

  response.sendRedirect("tickets?action=view&ticketId=" + id);
 }

 private Attachment processAttachment(Part filePart) throws IOException {
  InputStream inputStream = filePart.getInputStream();
  ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

  int read;
  final byte[] bytes = new byte[1024];

  while ((read = inputStream.read(bytes)) != -1) {
   outputStream.write(bytes, 0, read);
  }

  Attachment attachment = new Attachment();
  attachment.setName(filePart.getSubmittedFileName());
  attachment.setContents(outputStream.toByteArray());

  return attachment;
}


 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  //response.getWriter().append("Served at: ").append(request.getContextPath());
  String action=request.getParameter("action");
  if(action==null)
   action="view";
  switch(action) {
   case "create":this.showTicketForm(response);
    break;
   case "view":this.viewTicket(request, response);
    break;
   case "download":this.downloadAttachment(request, response);
    break; 
   default:this.listTickets(response);
    break;
  }
 }

 /**
  * @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);
 }
 private Ticket getTicket(String idString, HttpServletResponse response)
            throws ServletException, IOException
    {
        if(idString == null || idString.length() == 0)
        {
            response.sendRedirect("tickets");
            return null;
        }

        try
        {
            Ticket ticket = this.ticketDatabase.get(Integer.parseInt(idString));
            if(ticket == null)
            {
                response.sendRedirect("tickets");
                return null;
            }
            return ticket;
        }
        catch(Exception e)
        {
            response.sendRedirect("tickets");
            return null;
        }
    }

    private PrintWriter writeHeader(HttpServletResponse response)
            throws ServletException, IOException
    {
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");

        PrintWriter writer = response.getWriter();
        writer.append("<!DOCTYPE html>\r\n")
              .append("<html>\r\n")
              .append("    <head>\r\n")
              .append("        <title>Customer Support</title>\r\n")
              .append("    </head>\r\n")
              .append("    <body>\r\n");

        return writer;
    }

    private void writeFooter(PrintWriter writer)
    {
        writer.append("    </body>\r\n").append("</html>\r\n");
    }

}

© 著作权归作者所有

共有 人打赏支持
木之下
粉丝 0
博文 29
码字总数 2287
作品 0
扬州
javaweb开发之Filter

一、简介 在Servlet2.3规范中定义了过滤器,它对servlet容器调用servlet的过程进行拦截,从而在servlet进行响应处理的前后实现一些特殊的功能。 过滤器实现了一个责任链的模式。多个过滤器形...

小米米儿小
2013/12/06
0
0
六、JSP的由来以及与Servlet的关系

JavaWeb在有了Servlet这项技术以后,就可以编写动态网页了。在动态网页中,一般来说样式是不变的,变化的是数据。如果程序员在Servlet类中写了大量的静态代码,例如out.println("<html>");这...

Wakeeee_
07/09
0
0
精研Servlet,HttpServlet的实现追究

提前声明:个人说的不一定对,如有错误之处,请批评指出. Servlet的优点: servlet可以很好地替代公共网关接口(Common Gateway Interface,CGI)脚本。通常CGI脚本是用Perl或者C语言编写的,它们总...

Zhao-Qian
2012/12/08
0
57
客户端通过http协议 post xml型字符串数据到后台工作流程(请指点)

一.客户端流程 两种方法:1.通过httpurlconnection 2.通过apache开源的httpclient 代码示例为 urlconnection方法: StringBuilder responseBuilder = null;BufferedReader reader = null;Bu......

Enjoy前端开发
2013/08/23
0
0
超详细的Java面试题总结之JavaWeb基础知识总结

Servlet总结: 在Java Web程序中,Servlet主要负责接收用户请求HttpServletRequest,在doGet(),doPost()中做相应的处理,并将回应HttpServletResponse反馈给用户。Servlet可以设置初始化参数,...

Java互联网架构师
08/29
0
0

没有更多内容

加载失败,请刷新页面

加载更多

想用Unity3D引擎软件赚点钱的看过来

前言: 你可以不拥有很多钱 但你一定要有赚钱的能力 目前手上有项目, 需要熟练Unity3D引擎软件的伙伴 有意向的给我发私信

猿神出窍
30分钟前
0
0
Spring Boot全局异常处理

Spring Boot默认的异常处理机制 默认情况下,Spring Boot为两种情况提供了不同的响应方式。 一种是浏览器客户端请求一个不存在的页面或服务端处理发生异常时,一般情况下浏览器默认发送的请求...

狼王黄师傅
57分钟前
7
0
Thinkphp5 优雅配置两个数据库

工作需要需要配置两个数据库,框架5.0的,步骤如下: 1、在database.php同级创建一个database2.php文件 在里面配置第二个数据库信息, 2、在config中配置这个数据库信息: 3、创建第二个表的...

wqzbxh
今天
4
0
Socket网络编程进阶与实战

Socket网络编程进阶与实战 Socket对于每个工程师的重要性不言而喻。本课程将理论结合实践,带你从零开始,系统学习Socket编程技术,让Socket的学习不再那么零散与难以掌握,同时会提炼出Soc...

qq__2304636824
今天
4
0
Android studio常用快捷键

Ctrl +Alt +Space //显示可用参数 Ctrl + Alt +M //抽取方法 Ctrl +Alt + F //提取全局变量 Ctrl +Shift + "+或-" //折叠/展开代码块 Shift + F6 //批量更改变量 Ctrl + Tab //切换器 Ctrl +...

lanyu96
今天
5
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部