文档章节

来自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
博文 30
码字总数 2410
作品 0
扬州
私信 提问
shtml和jsp是什么 关系呀?

我学习一个java web项目,里面的页面好像都是shtml,为什么要这么写? 这是web.xml里的一段 controller org.springframework.web.servlet.DispatcherServlet 1 controller *.shtml...

Vek_lip
2016/10/26
280
2
javaweb

我真是草他妈的弄了整整2天!就这么一个JSP页面无论如何都是空白页面 没有任何效果,if(request.getAttribute("aa")!=null) if(request.getAttribute("aa")==null)都写过了 要不是我的问题马...

地瓜地瓜我是土豆876
2017/07/06
132
4
客户端通过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
精研Servlet,HttpServlet的实现追究

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

Zhao-Qian
2012/12/08
0
57

没有更多内容

加载失败,请刷新页面

加载更多

zookeeper配置与使用

一.登录官网下载 不要带后缀的,那是公侧版本,下稳定版,比如3.4.9 二.安装与使用 解压后bin里是启动程序 配置文件:在conf下 复制zoo_sample.cfg改名为为zoo.cfg,打开zoo修改文件...

小兵胖胖
22分钟前
1
0
spring源码阅读笔记(一)

ClassPathXmlApplicationContext 与 FileSystemXmlApplicationContext 用了这么久的框架,是时候搞一下源码了,一般最初接触spring 从以下步骤开始 创建一个bean类 并创建 ooxx.xml之类的spr...

NotFound403
45分钟前
2
0
MySQL主从配置

12月14日任务 17.1 MySQL主从介绍 17.2 准备工作 17.3 配置主 17.4 配置从 17.5 测试主从同步 MySQL主从介绍 MySQL主从又叫做Replication、AB复制。简单将就是A/B两个服务器做主从后,在A上写...

robertt15
48分钟前
8
0
我的Linux系统九阴真经

在今天,互联网的迅猛发展,科技技术也日新月异,各种编程技术也如雨后春笋一样,冒出尖来了。各种创业公司也百花齐放百家争鸣,特别是针对服务行业,新型互联网服务行业,共享经济等概念的公...

问题终结者
今天
22
0
Java 使用 gson 对 json 根据 key 键进行排序

引入Google的gson jar <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.0</version>......

yh32
今天
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部