文档章节

来自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
码字总数 2208
作品 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
[转]通俗易懂Tomcat中Servlet的生命周期

我在上一篇文章里详细的介绍了 HTTP协议工作的流程,其中最重要的就是如何理解HTTP请求头和HTTP响应头,现在在这里再来详细的说明Tomcat 容器(即Servlet 容器)到底是如何 管理Servlet的,S...

穿越星辰
2010/05/13
0
2

没有更多内容

加载失败,请刷新页面

加载更多

下一页

基于TP5的微信的公众号获取登录用户信息

之前讲过微信的公众号自动登录的菜单配置,这次记录一下在TP5项目中获取自动登录的用户信息并存到数据库的操作 基本的流程为:微信设置自动登录的菜单—>访问的URL指定的函数里获取用户信息—...

月夜中徘徊
今天
0
0
youTrack

package jetbrains.teamsys.license.runtime; 计算lis package jetbrains.ring.license.reader; 验证lis 安装后先不要生成lis,要把相关文件进行替换 ring-license-checker-1.0.41.jar char......

max佩恩
今天
0
0
12.17 Nginx负载均衡

Nginx负载均衡 下面的dig看到可以返回2个IP,就是解析出来的IP,这样我们可以做负载均衡。 dig www.qq.com 1.vim /usr/local/nginx/conf/vhost/fuzai.conf 2.添加如下配置 upstream qq //定义...

芬野de博客
今天
0
0
SSE(Server Send Event 服务端发送事件)

package com.example.demo.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframe......

Canaan_
今天
0
0
jvm调优

1.jvm运行模式 client模式:启动快,占用内存少,jit编译器生成代码的速度也更快. server模式:主要优势在于代码优化功能,这个功能对于服务器应用而言尤其重要. tiered server模式:结合了client与...

Funcy1122
今天
1
0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部