@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. Vue--组件嵌套

    1.全局注册: 组件放到components文件夹内,建议组件名是什么行为的name名就是什么 main.js 引入组件:import Users from '组件位置' 注册全局组件:Vue.com ...

  2. A1114. Family Property

    This time, you are supposed to help us collect the data for family-owned property. Given each person ...

  3. Django 配置数据库

    Django提到配置那大多数都是在settings.py配置文件 在配置文件里的 DATABASES 内进行设置 # 数据库配置 DATABASES = { #连接mysql 'default': { ...

  4. SQL中 like 通配符 特殊字符处理

    以下是一些匹配的举例,需要说明的是,只有like操作才有这些特殊字符,=操作是没有的.a_b... a[_]b%a%b... a[%]b%a[b... a[[]b%a]b... a]b%a[]b... ...

  5. bcftools合并vcf文件

    见命令: bcftools merge A.vcf.gz B.vcf.gz C.vcf.gz -Oz -o ABC.vcf.gz 参考链接:http://vcftools.sourceforge.ne ...

  6. python3.5和python3.6关于json模块的区别

    python3.5中 无法反序列化bytes数据必须decode成str才可以 >>> import json >>> a = b'{"username& ...

  7. Java概念、语法和变量基础整理

    Java概述 J2SE:  Java 2 Platform Standard Edition( 2005年之后更名为Java SE ).包含构成Java语言核心的类 J2EE: Java 2 Plat ...

  8. go tcp

    TCP编程 1.客户端和服务器 2.服务端的处理流程 监听端口 接收客户端的链接 创建goroutine,处理该链接 3.客户端的处理流程 建立与服务端的链接 进行数据收发 关闭链接 服务端代码 pa ...

  9. go goroutine

    进程和线程 进程是程序在操作系统中的一次执行过程,系统进行资源分配和调度的 一个独立单位. 线程是进程的一个执行实体,是CPU调度和分派的基本单位,它是比进程更 小的能独立运行的基本单位. 一个进程可 ...

  10. 剑指Offer_编程题_4

    题目描述 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树.假设输入的前序遍历和中序遍历的结果中都不含重复的数字.例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7, ...