jsp 起航 和Servlet通过attribute通信

  1 @WebServlet(name = "ticketServlet",urlPatterns = {"/tickets"},loadOnStartup = 1)
  2 @MultipartConfig(fileSizeThreshold = 5242880,
  3 maxFileSize = 20971520L,//20MB
  4 maxRequestSize = 41943040L//40MB
  5 )
  6 public class TicketServlet extends HttpServlet{
  7     //线程可见性
  8     private volatile int TICKET_ID_SEQUENCE = 1;
  9     private Map<Integer,Ticket> ticketDatabase = new LinkedHashMap<>();
 10 
 11     @Override
 12     protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
 13 
 14         //使用请求参数做了一个菜单
 15         String action = req.getParameter("action");
 16         if (action == null){
 17             action = "list";//默认ticket列表
 18         }
 19         switch (action){
 20             case "create":
 21                 this.showTicketForm(req,resp);//展示表单
 22                 break;
 23             case "view":
 24                 this.viewTicket(req,resp);//具体一张
 25                 break;
 26             case  "download":
 27                 this.downloadAttachment(req,resp);//下载附件
 28                 break;
 29             default:
 30                 this.listTickets(req,resp);//展示ticket
 31                 break;
 32         }
 33     }
 34 
 35     @Override
 36     protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
 37         req.setCharacterEncoding("UTF-8");
 38         String action = req.getParameter("action");
 39         if(action == null){
 40             action = "list";
 41         }
 42         switch (action){
 43             case "create":
 44                 this.createTicket(req,resp);//表单提交实际创建方法
 45                 break;
 46             case "list":
 47             default:
 48                 resp.sendRedirect("tickets");//重定向 get
 49                 break;
 50 
 51         }
 52 
 53     }
 54 
 55 
 56     private void listTickets(HttpServletRequest request,HttpServletResponse response) throws IOException, ServletException {
 57         request.setAttribute("ticketDatabase",this.ticketDatabase);
 58         request.getRequestDispatcher("/WEB-INF/jsp/view/listTickets.jsp").forward(request,response);
 59     }
 60 
 61     private void viewTicket(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
 62         //从ticket列表进入某张ticket所需要id
 63         String idString = request.getParameter("ticketId");
 64         Ticket ticket = this.getTicket(idString, response);
 65         if(ticket == null)
 66             return;
 67         request.setAttribute("ticketId",idString);
 68         request.setAttribute("ticket",ticket);
 69 
 70         request.getRequestDispatcher("/WEB-INF/jsp/view/viewTicket.jsp")
 71                 .forward(request,response);
 72     }
 73 
 74     private Ticket getTicket(String id, HttpServletResponse response) throws IOException {
 75         //id.len == ''  一般合法性检查  有没有
 76         if (id == null || id.length()==0){
 77             response.sendRedirect("tickets");
 78             return null;
 79         }
 80         try {
 81             //parse异常
 82             Ticket ticket = this.ticketDatabase.get(Integer.parseInt(id));
 83             //都考虑失败 没有的情况
 84             if (ticket == null) {
 85                 response.sendRedirect("tickets");
 86                 return null;
 87             }
 88             return ticket;
 89         }catch (Exception e){
 90             response.sendRedirect("tickets");
 91             return null;
 92         }
 93     }
 94 
 95     private void showTicketForm(HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException {
 96 //        内部转发,而不是重定向,用户浏览器不会收到重定向状态码,浏览器URL也不改变
 97 //        内部请求处理转发至应用程序不同部分,forward后,Servlet代码没有控制权再操作响应对象。
 98         req.getRequestDispatcher("/WEB-INF/jsp/view/ticketForm.jsp").forward(req,resp);
 99     }
100 
101 
102     private void downloadAttachment(HttpServletRequest request, HttpServletResponse response) throws IOException {
103        //下载某一个attachment
104         String idString = request.getParameter("ticketId");
105         Ticket ticket = this.getTicket(idString, response);
106         if(ticket == null)
107             return;
108 
109         String name = request.getParameter("attachment");
110         if(name == null)
111         {
112             response.sendRedirect("tickets?action=view&ticketId=" + idString);
113             return;
114         }
115 
116         Attachment attachment = ticket.getAttachment(name);
117         if(attachment == null)
118         {
119             response.sendRedirect("tickets?action=view&ticketId=" + idString);
120             return;
121         }
122         //header 内容位置   文件名
123         response.setHeader("Content-Disposition",
124                 "attachment; filename=" +
125                         new String(attachment.getName().getBytes("UTF-8"),"ISO8859-1"));
126 
127         response.setContentType("application/octet-stream");
128         //
129         ServletOutputStream stream = response.getOutputStream();
130         stream.write(attachment.getContents());
131     }
132 
133 
134     private void createTicket(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
135         Ticket ticket = new Ticket();
136         ticket.setCustomerName(req.getParameter("customerName"));
137         ticket.setSubject(req.getParameter("subject"));
138         ticket.setBody(req.getParameter("body"));
139 
140         Part filePart = req.getPart("file1");
141         if (filePart!=null){
142             Attachment attachment = this.processAttachment(filePart);
143             if (attachment!=null)
144                 ticket.addAttachment(attachment);
145         }
146         int id;
147         synchronized (this){
148             id = this.TICKET_ID_SEQUENCE++;
149             this.ticketDatabase.put(id,ticket);
150         }
151         resp.sendRedirect("tickets?action=view&ticketId="+id);
152     }
153 
154     private Attachment processAttachment(Part filePart) throws IOException {
155         InputStream inputStream = filePart.getInputStream();//用户输入流
156         ByteArrayOutputStream outputStream = new ByteArrayOutputStream();//写入attachment做准备
157 
158         int read;
159         final byte[] bytes  = new byte[1024];//buffer
160         while((read=inputStream.read(bytes))!=-1){//有多少
161             outputStream.write(bytes,0,read);//写多少
162         }
163 
164         Attachment attachment = new Attachment();
165         attachment.setName(filePart.getSubmittedFileName());
166         attachment.setContents(outputStream.toByteArray());
167 
168         return attachment;
169     }

【展示ticket表单】

 1 <%--<%@ page contentType="text/htmlcharset=UTF-8" %>--%>
 2 <%@ page session="false" %>
 3 <html>
 4 <head>
 5     <title>Create a Ticket</title>
 6 </head>
 7 <body>
 8     <%--//编码类型multipart/form-data--%>
 9 <form method="POST" action="tickets" enctype="multipart/form-data">
10     <%--//隐藏域提交 action value = create--%>
11     <input type="hidden" name="action" value="create"/>
12     Your Name<br/>
13     <input type="text" name="customerName"/><br/><br/>
14     Subject<br/>
15     <input type="text" name="subject"/><br/><br/>
16     Body<br/>
17     <textarea name="body" rows="5" cols="30"></textarea><br/><br/>
18     <b>Attachments</b><br/>
19     <input type="file" name="file1"/><br/><br/>
20     <input type="submit" value="提交"/>
21 </form>
22 </body>
23 </html>

【查看Ticket】

 1 <%@ page import="net.mypla.model.Ticket" %>
 2 <%@ page session="false" %>
 3 <%
 4     String ticketId = (String) request.getAttribute("ticketId");
 5     Ticket ticket = (Ticket) request.getAttribute("ticket");
 6 %>
 7 <html>
 8 <head>
 9     <title>客户支持系统</title>
10 </head>
11 <body>
12     <h2>Ticket #<%= ticketId%>: <%=ticket.getSubject()%></h2>
13     <i>Customer Name - <%= ticket.getCustomerName()%></i><br /><br />
14     <%= ticket.getBody()%><br /><br />
15     <%
16         if(ticket.getNumberOfAttachments()>0){
17             %>Attachments:<%
18             int i = 0;
19             for(Attachment a:ticket.getAttachments()){
20                 if(i++>0)
21                     out.print(",");
22                 %><a href="<c:url value="/tickets">
23                     <c:param name="action" value="download"/>
24                     <c:param name="ticketId" value="<%= ticketId%>"/>
25                     <c:param name="attachment" value="<%= a.getName()%>"/>
26                 </c:url>"><%= a.getName()%></a><%
27             }
28         }
29     %><br/>
30     <a href="<c:url value="/tickets" />">Return to list tickets</a>
31 </body>
32 </html>

【查看tickets列表】

 1 <%@ page session="false" import="java.util.Map" %>
 2 <%@ page import="net.mypla.model.Ticket" %>
 3 <%
 4     @SuppressWarnings("unchecked")
 5     Map<Integer,Ticket> ticketDatabase = (Map<Integer, Ticket>) request.getAttribute("ticketDatabase");
 6 %>
 7 <html>
 8 <head>
 9     <title>消费者支持系统</title>
10 </head>
11 <body>
12     <h2>Tickets</h2>
13     
14     <a href="<c:url value="/tickets"><c:param name="action" value="create"/></c:url>">Create Ticket</a><br/><br/>
15     <%
16         if(ticketDatabase.size() == 0){
17             %><i>There are no tickets in the system.</i><%
18         }
19         else{
20             for(int id : ticketDatabase.keySet()){
21                 String idString = Integer.toString(id);
22                 Ticket ticket = ticketDatabase.get(id);
23                 %>Ticket #<%= idString%>:<a href="<c:url value="/tickets">
24                     <c:param name="action" value="view"/>
25                     <c:param name="ticketId" value="<%= idString%>"/></c:url>"><%= ticket.getSubject()%></a>
26         ( customer:<%= ticket.getCustomerName() %>)<br /><%
27         }
28 }
29 %>
30 </body>
31 </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>
posted @ 2018-03-21 16:21  chenhui7373  阅读(527)  评论(0编辑  收藏  举报