@WebServlet(name = "ticketServlet",urlPatterns = {"/tickets"},loadOnStartup = 1)
@MultipartConfig(fileSizeThreshold = 5242880,
maxFileSize = 20971520L,//20MB
maxRequestSize = 41943040L//40MB
)
public class TicketServlet extends HttpServlet{
//线程可见性
private volatile int TICKET_ID_SEQUENCE = 1;
private Map<Integer,Ticket> ticketDatabase = new LinkedHashMap<>(); @Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
//使用请求参数做了一个菜单
String action = req.getParameter("action");
if (action == null){
action = "list";//默认ticket列表
}
switch (action){
case "create":
this.showTicketForm(resp);//展示表单
break;
case "view":
this.viewTicket(req,resp);//具体一张
break;
case "download":
this.downloadAttachment(req,resp);//下载附件
break;
default:
this.listTickets(resp);//展示ticket
break;
}
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
if(action == null){
action = "list";
}
switch (action){
case "create":
this.createTicket(req,resp);//表单提交实际创建方法
break;
case "list":
default:
resp.sendRedirect("tickets");//重定向 get
break; } } private void listTickets(HttpServletResponse response) throws IOException {
PrintWriter writer = this.writeHeader(response); writer.append("<h2>Tickets</h2>\r\n");
//createTicket入口 先展示一个表单
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 viewTicket(HttpServletRequest request, HttpServletResponse response) throws IOException {
//从ticket列表进入某张ticket所需要id
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 Ticket getTicket(String id, HttpServletResponse response) throws IOException {
//id.len == '' 一般合法性检查 有没有
if (id == null || id.length()==0){
response.sendRedirect("tickets");
return null;
}
try {
Ticket ticket = this.ticketDatabase.get(Integer.parseInt(id));
if (ticket == null) {
response.sendRedirect("tickets");
return null;
}
return ticket;
}catch (Exception e){
response.sendRedirect("tickets");
return null;
}
} private void showTicketForm(HttpServletResponse resp) throws IOException {
PrintWriter writer = this.writeHeader(resp);
writer.append("<h2>Create a Ticket</h2>\r\n");
writer.append("<form method=\"POST\" action=\"tickets\" ")
.append("enctype=\"multipart/form-data\">\r\n");//编码类型multipart/form-data
writer.append("<input type=\"hidden\" name=\"action\" ")//隐藏域提交 action value = create
.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 downloadAttachment(HttpServletRequest request, HttpServletResponse response) throws IOException {
//下载某一个attachment
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;
}
//header 内容位置 文件名
response.setHeader("Content-Disposition",
"attachment; filename=" + attachment.getName()); response.setContentType("application/octet-stream");
//流
ServletOutputStream stream = response.getOutputStream();
stream.write(attachment.getContents());
} private void createTicket(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
Ticket ticket = new Ticket();
ticket.setCustomerName(req.getParameter("customerName"));
ticket.setSubject(req.getParameter("subject"));
ticket.setBody(req.getParameter("body")); Part filePart = req.getPart("file1");
if (filePart!=null){
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);
}
resp.sendRedirect("tickets?action=view&ticketId="+id);
} private Attachment processAttachment(Part filePart) throws IOException {
InputStream inputStream = filePart.getInputStream();//用户输入流
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//写入attachment做准备 int read;
final byte[] bytes = new byte[1024];//buffer
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;
} private PrintWriter writeHeader(HttpServletResponse response)
throws 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");
} }
【文件下载细节】
//header 内容位置 文件名
response.setHeader("Content-Disposition",
"attachment; filename=" +
new String(attachment.getName().getBytes("UTF-8"),"ISO8859-1"));//浏览器支持的编码是ISO8859-1
response.setContentType("application/octet-stream");
//流
ServletOutputStream stream = response.getOutputStream();
stream.write(attachment.getContents());