@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, ServletException { //使用请求参数做了一个菜单
String action = req.getParameter("action");
if (action == null){
action = "list";//默认ticket列表
}
switch (action){
case "create":
this.showTicketForm(req,resp);//展示表单
break;
case "view":
this.viewTicket(req,resp);//具体一张
break;
case "download":
this.downloadAttachment(req,resp);//下载附件
break;
default:
this.listTickets(req,resp);//展示ticket
break;
}
} @Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
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(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
request.setAttribute("ticketDatabase",this.ticketDatabase);
request.getRequestDispatcher("/WEB-INF/jsp/view/listTickets.jsp").forward(request,response);
} private void viewTicket(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
//从ticket列表进入某张ticket所需要id
String idString = request.getParameter("ticketId");
Ticket ticket = this.getTicket(idString, response);
if(ticket == null)
return;
request.setAttribute("ticketId",idString);
request.setAttribute("ticket",ticket); request.getRequestDispatcher("/WEB-INF/jsp/view/viewTicket.jsp")
.forward(request,response);
} private Ticket getTicket(String id, HttpServletResponse response) throws IOException {
//id.len == '' 一般合法性检查 有没有
if (id == null || id.length()==0){
response.sendRedirect("tickets");
return null;
}
try {
//parse异常
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(HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException {
// 内部转发,而不是重定向,用户浏览器不会收到重定向状态码,浏览器URL也不改变
// 内部请求处理转发至应用程序不同部分,forward后,Servlet代码没有控制权再操作响应对象。
req.getRequestDispatcher("/WEB-INF/jsp/view/ticketForm.jsp").forward(req,resp);
} 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=" +
new String(attachment.getName().getBytes("UTF-8"),"ISO8859-1")); 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;
}

【展示ticket表单】

 <%--<%@ page contentType="text/htmlcharset=UTF-8" %>--%>
<%@ page session="false" %>
<html>
<head>
<title>Create a Ticket</title>
</head>
<body>
<%--//编码类型multipart/form-data--%>
<form method="POST" action="tickets" enctype="multipart/form-data">
<%--//隐藏域提交 action value = create--%>
<input type="hidden" name="action" value="create"/>
Your Name<br/>
<input type="text" name="customerName"/><br/><br/>
Subject<br/>
<input type="text" name="subject"/><br/><br/>
Body<br/>
<textarea name="body" rows="5" cols="30"></textarea><br/><br/>
<b>Attachments</b><br/>
<input type="file" name="file1"/><br/><br/>
<input type="submit" value="提交"/>
</form>
</body>
</html>

【查看Ticket】

 <%@ page import="net.mypla.model.Ticket" %>
<%@ page session="false" %>
<%
String ticketId = (String) request.getAttribute("ticketId");
Ticket ticket = (Ticket) request.getAttribute("ticket");
%>
<html>
<head>
<title>客户支持系统</title>
</head>
<body>
<h2>Ticket #<%= ticketId%>: <%=ticket.getSubject()%></h2>
<i>Customer Name - <%= ticket.getCustomerName()%></i><br /><br />
<%= ticket.getBody()%><br /><br />
<%
if(ticket.getNumberOfAttachments()>0){
%>Attachments:<%
int i = 0;
for(Attachment a:ticket.getAttachments()){
if(i++>0)
out.print(",");
%><a href="<c:url value="/tickets">
<c:param name="action" value="download"/>
<c:param name="ticketId" value="<%= ticketId%>"/>
<c:param name="attachment" value="<%= a.getName()%>"/>
</c:url>"><%= a.getName()%></a><%
}
}
%><br/>
<a href="<c:url value="/tickets" />">Return to list tickets</a>
</body>
</html>

【查看tickets列表】

 <%@ page session="false" import="java.util.Map" %>
<%@ page import="net.mypla.model.Ticket" %>
<%
@SuppressWarnings("unchecked")
Map<Integer,Ticket> ticketDatabase = (Map<Integer, Ticket>) request.getAttribute("ticketDatabase");
%>
<html>
<head>
<title>消费者支持系统</title>
</head>
<body>
<h2>Tickets</h2> <a href="<c:url value="/tickets"><c:param name="action" value="create"/></c:url>">Create Ticket</a><br/><br/>
<%
if(ticketDatabase.size() == 0){
%><i>There are no tickets in the system.</i><%
}
else{
for(int id : ticketDatabase.keySet()){
String idString = Integer.toString(id);
Ticket ticket = ticketDatabase.get(id);
%>Ticket #<%= idString%>:<a href="<c:url value="/tickets">
<c:param name="action" value="view"/>
<c:param name="ticketId" value="<%= idString%>"/></c:url>"><%= ticket.getSubject()%></a>
( customer:<%= ticket.getCustomerName() %>)<br /><%
}
}
%>
</body>
</html>

【部署描述符】

<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<url-pattern>*.jspf</url-pattern>
<page-encoding>UTF-8</page-encoding>
<scripting-invalid>false</scripting-invalid>
<include-prelude>/WEB-INF/jsp/base.jspf</include-prelude>
<!--jsp转换器删除响应输出中空白,只留指令、声明、脚本、jsp标签-->
<trim-directive-whitespaces>true</trim-directive-whitespaces>
<default-content-type>text/html</default-content-type>
</jsp-property-group>
</jsp-config>

jsp 起航 和Servlet通过attribute通信的更多相关文章

  1. Java Applet 与Servlet之间的通信

    1 Applet对Servlet的访问及参数传递的实现 2.1.1创建URL对象 在JAVA程序中,可以利用如下的形式创建URL对象 URL servletURL = new URL( "h ...

  2. The JSP specification requires that an attribute name is

    把另一个博客内容迁移到这里 七月 10, 2016 10:23:12 上午 org.apache.catalina.core.ApplicationDispatcher invoke 严重: Serv ...

  3. Mac OS中Java Servlet与Http通信

    Java中一个Servlet其实就是一个类,用来扩展服务器的性能,服务器上驻留着可以通过“请求-响应”编程模型来访问的应用程序.Servlet可以对任何类型的请求产生响应,但通常只用来扩展Web服务器 ...

  4. Servlet和JSP之有关Servlet和JSP的梳理(二)

    JSP JSP页面本质上是一个Servlet,JSP页面在JSP容器中运行,一个Servlet容器通常也是JSP容器. 当一个JSP页面第一次被请求时,Servlet/JSP容器主要做一下两件事情: ...

  5. 初识Jsp,JavaBean,Servlet以及一个简单mvc模式的登录界面

    1:JSP JSP的基本语法:指令标识page,include,taglib;page指令标识常用的属性包含Language用来定义要使用的脚本语言:contentType定义JSP字符的编码和页面响 ...

  6. The JSP specification requires that an attribute name is preceded by whitespace

    一个jsp页面在本地运行一点问题没有,发布到服务器就报错了: The JSP specification requires that an attribute name is preceded by ...

  7. 自建目录中jsp页面访问servlet路径出错404

    ---恢复内容开始--- 自建目录中jsp页面访问servlet路径出错404 使用eclipse建立的项目,总是会遇到路径问题,比如jsp页面访问servlet,jsp在默认的路径.jsp在自建目录 ...

  8. JSP lifecycle - with servlet

    编译阶段: servlet容器编译servlet源文件,生成servlet类 初始化阶段: 加载与JSP对应的servlet类,创建其实例,并调用它的初始化方法 执行阶段: 调用与JSP对应的serv ...

  9. JSP入门3 Servlet

    需要继承类HttpServlet 服务器在获得请求的时候会先根据jsp页面生成一个java文件,然后使用jdk的编译器将此文件编译,最后运行得到的class文件处理用户的请求返回响应.如果再有请求访问 ...

随机推荐

  1. SCOI2008着色方案(记忆化搜索)

    有n个木块排成一行,从左到右依次编号为1~n.你有k种颜色的油漆,其中第i 种颜色的油漆足够涂ci 个木块.所有油漆刚好足够涂满所有木块,即 c1+c2+...+ck=n.相邻两个木块涂相同色显得很难 ...

  2. uWSGI+Nginx安装、配置

    1.关闭SELINUX: [root@PYTHON27 /]# vim /etc/selinux/config 将SELINUX=enforcing修改为SELINUX=disabled 2.关闭防火 ...

  3. 透彻掌握Promise的使用

    Promise的重要性我认为我没有必要多讲,概括起来说就是必须得掌握,而且还要掌握透彻.这篇文章的开头,主要跟大家分析一下,为什么会有Promise出现. 在实际的使用当中,有非常多的应用场景我们不能 ...

  4. MySQL 之 库操作,表操作

    系统数据库 information_schema :虚拟库,不占用磁盘空间,存储的是数据库启动后的一些参数,如用户表信息.列信息.权限信息.字符信息等 mysql:核心数据库,里面包含用户.权限.关键 ...

  5. 使用bcftools提取指定样本的vcf文件(extract specified samples in vcf format)

    1.下载安装bcftools. 2.准备样本ID文件,这里命名为samplelistname.txt,一个样本一行,如下所示: sample1 sample2 sample3 3.输入命令: bcft ...

  6. pip的更新问题

    OSX系统中在利用pip安装有些模块的时候出现”you are using pip version 9.0.1, however version 10.0.0 is available. You sh ...

  7. codesmith 连接mysql

    下载地址是http://dev.mysql.com/downloads/mirror.php?id=403020 请先注册登录后才能下载mysql-connector-net-6.3.7.msi这个文 ...

  8. zuul的学习

    1.zuul的介绍 https://blog.csdn.net/tianyaleixiaowu/article/details/78083269

  9. websocket实现简单的通信

    websocket server端 #coding=utf8 #!/usr/bin/python import struct,socket import hashlib import threadin ...

  10. Java泛型、List接口整理

    泛型 package com.oracle.demo01; import java.util.HashMap; import java.util.Iterator; import java.util. ...