文档章节

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

木之下
 木之下
发布于 2017/09/09 22:34
字数 792
阅读 7
收藏 0
点赞 0
评论 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
博文 23
码字总数 2208
作品 0
扬州
JavaWeb开发比较重要的面试题

JavaWeb开发比较重要的面试题 1. 编码转换:怎样将GB2312编码的字符串转换为ISO-8859-1编码的字符串? 答:示例代码如下: String s1=”你好”; String s2=new String(s1.getBytes(“GB2312”...

xj_9264 ⋅ 05/06 ⋅ 0

Java面试题之JavaWeb高级

一、Filter和Listener Filter:从J2EE1.3开始,Servlet2.3规范中加入对Filter的支持。Filter就称之为过滤器,它是Servlet技术中最激动人心的技术WEB开发人员通过Filter技术可以对web服务器管理...

年轻诠释我们的梦想_705b ⋅ 06/02 ⋅ 0

Apache Qpid JMS AMQP 0-x 6.3.1 发布

Apache Qpid JMS AMQP 0-x 6.3.1 已发布。Qpid JMS AMQP 0-x 是兼容 JMS 1.1 的客户端,等同于 AMQP 0-8,0-9,0-9-1 和 0-10。Qpid JMS 是一个使用 Qpid Proton 协议引擎的 Java Message Ser......

淡漠悠然 ⋅ 05/21 ⋅ 0

tomcat和jetty的区别

===========2017年11月3日08:33:07======================== 相同点 1.tomcat与jetty都是一种servlet引擎,他们都支持标准的servlet规范和javaEE规范 不同点 1.架构比较 jetty相比tomcat更为...

anlve ⋅ 05/27 ⋅ 0

Java Web(一) Servlet详解!!

一、什么是servlet?     处理请求和发送响应的过程是由一种叫做Servlet的程序来完成的,并且Servlet是为了解决实现动态页面而衍生的东西。理解这个的前提是了解一些http协议的东西,并且...

architect刘源源 ⋅ 05/08 ⋅ 0

干货!从Tomcat执行流程了解jsp是如何被解析的,错误提示是哪里生成的。

一.关于Tomcat组成 先上张图: Tomcat组成: 1.Server:代表整个 servlet 容器,如Tomcat,JBoss之类的。 2.Service:它由一个或者多个Connector组成,以及一个Engine,负责处理所有Connect...

宇的季节 ⋅ 05/07 ⋅ 0

Servlet的一些细节--学习笔记

Servlet细节 1)浏览器访问的url-pattern只是一个符合格式的任意字符串,以/开头 2)一个Servlet的url-pattern可以是1个或多个,有二种形式; a).xx b)/xx/ 注意:/不能一起直接使用 3)/和....

知止内明 ⋅ 04/17 ⋅ 0

JSP 学习总结---学习笔记

什么是JSP 1)为什么说,Servlet是一个动态Web开发技术呢? Servlet是基于服务端的一种动态交互技术, HttpServletRequest表示客户端到服务端的对象 HttpServletResponse表示服务端到客户端的...

知止内明 ⋅ 04/18 ⋅ 0

java过滤器(Filter和ChainFilter链)你了解吗?(有详细代码)

1、什么是过滤器? 在客户端到服务器的过程中,当发送请求时,如果有不符合的信息将会被filter进行拦截,如果符合则会进行放行,在服务器给客户端响应时也会进行判断 如果有不符合的信息将会...

IT_laobai ⋅ 今天 ⋅ 0

web项目中web.xml的作用

每个javaEE工程中都有web.xml文件,那么它的作用是什么呢?它是每个web.xml工程都必须的吗? 一个web中可以没有web.xml文件,也就是说,web.xml文件并不是web工程必须的。 web.xml文件是用来...

ChinaHYF ⋅ 04/27 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

关于“幂等”操作

一个幂等(idempotent)操作的特点是其任意多次执行所产生的影响均与一次执行的影响相同. 开发中, 我们经常考虑幂等操作的场景有“接口调用”、“MQ消费”、“自动任务”等 接口调用, 可能出现...

零二一七 ⋅ 29分钟前 ⋅ 0

Dubbo服务服务暴露之ProxyFactory Invoker

Dubbo服务暴露过程中有涉及到调用ProxyFactory 中方法获取Invoker对象的过程,现在我们来深究下源码,来看下这个过程是在做些什么,返回的Invoker 对象是什么,我们来看一下代码的切入点: ...

哲别0 ⋅ 44分钟前 ⋅ 0

GP两种连接方式性能测试

GP两种连接方式性能测试 Pivotal import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class GPQueryStrin......

仔仔1993 ⋅ 48分钟前 ⋅ 0

jsonrpc-4j代码解析

解析文件 AutoJsonRpcServiceImplExporter JsonServiceExporter AutoJsonRpcServiceImplExporter 路径:com.googlecode.jsonrpc4j.spring.AutoJsonRpcServiceImplExporter AutoJsonRpcServi......

郭恩洲_OSC博客 ⋅ 今天 ⋅ 0

百度搜索

from selenium import webdriver import time brower=webdriver.Firefox() brower.get('http://www.baidu.com') input=brower.find_element_by_id('kw') input.send_keys('中南大学') time.s......

南桥北木 ⋅ 今天 ⋅ 0

tomcat 日志记录器

1、日志记录器是记录消息的组件 日志记录器需要与某个servlet 容器相关联 2、Logger 接口 共定义了5种日志级别:FATAL、ERROR、WARNING、INFORMATION、DEBUGGER setVerbosity 设置级别 setC...

职业搬砖20年 ⋅ 今天 ⋅ 0

Thrift RPC实战(三) Thrift序列化机制

1.Thrift基础架构 Thrift是一个客户端和服务端的架构体系,数据通过socket传输; 具有自己内部定义的传输协议规范(TProtocol)和传输数据标准(TTransports); 通过IDL脚本对传输数据的数据结构...

lemonLove ⋅ 今天 ⋅ 0

网站建设就要像2018世界杯的俄罗斯队大杀四方[图]

今天心情不错,因为昨天晚上观看了世界杯比赛,尤其是对俄罗斯队的大杀四方感到十分霸气侧漏啊,因此我联想到了自己的博客网站,我的博客是去年年底上线的,一直想建设一个关于读书和读后感作...

原创小博客 ⋅ 今天 ⋅ 0

linux 信号机制

signal(SIGPIPE, SIG_IGN); TCP是全双工的信道, 可以看作两条单工信道, TCP连接两端的两个端点各负责一条. 当对端调用close时, 虽然本意是关闭整个两条信道, 但本端只是收到FIN包. 按照TCP协...

xxdd ⋅ 今天 ⋅ 0

my.cnf, my-small.cnf, my-medium.cnf, my-large.cnf

1. my-small.cnf # Example MySQL config file for small systems.## This is for a system with little memory (<= 64M) where MySQL is only used# from time to time and it's importa......

周云台 ⋅ 今天 ⋅ 0

没有更多内容

加载失败,请刷新页面

加载更多

下一页

返回顶部
顶部