jsp 起航 和Servlet通过attribute通信

时间:2023-03-09 21:43:43
jsp 起航 和Servlet通过attribute通信
 @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>