来自javaweb高级编程的详细的例子--servlet
来自javaweb高级编程的详细的例子--servlet
木之下 发表于3个月前
来自javaweb高级编程的详细的例子--servlet
  • 发表于 3个月前
  • 阅读 5
  • 收藏 0
  • 点赞 0
  • 评论 0

腾讯云 新注册用户 域名抢购1元起>>>   

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
博文 19
码字总数 2022
×
木之下
如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!
* 金额(元)
¥1 ¥5 ¥10 ¥20 其他金额
打赏人
留言
* 支付类型
微信扫码支付
打赏金额:
已支付成功
打赏金额: