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>
jsp 起航 和Servlet通过attribute通信的更多相关文章
- Java Applet 与Servlet之间的通信
1 Applet对Servlet的访问及参数传递的实现 2.1.1创建URL对象 在JAVA程序中,可以利用如下的形式创建URL对象 URL servletURL = new URL( "h ...
- The JSP specification requires that an attribute name is
把另一个博客内容迁移到这里 七月 10, 2016 10:23:12 上午 org.apache.catalina.core.ApplicationDispatcher invoke 严重: Serv ...
- Mac OS中Java Servlet与Http通信
Java中一个Servlet其实就是一个类,用来扩展服务器的性能,服务器上驻留着可以通过“请求-响应”编程模型来访问的应用程序.Servlet可以对任何类型的请求产生响应,但通常只用来扩展Web服务器 ...
- Servlet和JSP之有关Servlet和JSP的梳理(二)
JSP JSP页面本质上是一个Servlet,JSP页面在JSP容器中运行,一个Servlet容器通常也是JSP容器. 当一个JSP页面第一次被请求时,Servlet/JSP容器主要做一下两件事情: ...
- 初识Jsp,JavaBean,Servlet以及一个简单mvc模式的登录界面
1:JSP JSP的基本语法:指令标识page,include,taglib;page指令标识常用的属性包含Language用来定义要使用的脚本语言:contentType定义JSP字符的编码和页面响 ...
- The JSP specification requires that an attribute name is preceded by whitespace
一个jsp页面在本地运行一点问题没有,发布到服务器就报错了: The JSP specification requires that an attribute name is preceded by ...
- 自建目录中jsp页面访问servlet路径出错404
---恢复内容开始--- 自建目录中jsp页面访问servlet路径出错404 使用eclipse建立的项目,总是会遇到路径问题,比如jsp页面访问servlet,jsp在默认的路径.jsp在自建目录 ...
- JSP lifecycle - with servlet
编译阶段: servlet容器编译servlet源文件,生成servlet类 初始化阶段: 加载与JSP对应的servlet类,创建其实例,并调用它的初始化方法 执行阶段: 调用与JSP对应的serv ...
- JSP入门3 Servlet
需要继承类HttpServlet 服务器在获得请求的时候会先根据jsp页面生成一个java文件,然后使用jdk的编译器将此文件编译,最后运行得到的class文件处理用户的请求返回响应.如果再有请求访问 ...
随机推荐
- 阶乘函数(factorial)——结果在整型范围内的阶乘计算
定义: 在数学中,正整数的阶乘(英语:factorial)是所有小于及等于该数的正整数的积,计为n!,例如5的阶乘计为5!,其值为120: \[ 5!=5\times 4\times 3\times ...
- nginx常用配置
nginx.conf配置文件详解 其主要分为几个模块 全局快 从开始到events块之间的一部分内容,其作用域为全局作用域 events块 主要负责Nginx服务器与用户的网络连接 常用设置: 是否开 ...
- BZOJ 1996: [Hnoi2010]chorus 合唱队(区间dp)
题目: https://www.lydsy.com/JudgeOnline/problem.php?id=1996 题解: 这题刚拿到手的时候一脸懵逼qwq,经过思考与分析(看题解),发现是一道区间d ...
- 【UOJ 351】新年的叶子
http://uoj.ac/problem/351 其实原来看到这题是真的不想做的 毕竟真的特别怕期望题 后来莫名发现自己打了正解 也是很震惊的2333 Description 对于一棵树,每次随 ...
- 洛谷P5112 FZOUTSY
卡map还行.....手写hash表即可. 我一开始以为这个k会变......在sam上想各种奇技淫巧. k不变就是问一段区间有多少对长度为k的子串相同. 然后hash把子串转化为数字,就是区间有多少 ...
- Flask flask_script扩展库
flask_script 1.安装:进入到虚拟环境中,pip install flask_script 2.flask_script 作用:可以通过命令行的形式来操作Flask,例如通过命令跑一个开发 ...
- ANIS与UNICODE字符格式转换:MultiByteToWideChar() 和WideCharToMultiByte() 函数
资料来自: http://blog.csdn.net/holamirai/article/details/47948745 http://www.cnblogs.com/wanghao111/arch ...
- 常用工具类(System,Runtime,Date,Calendar,Math)
一.System: 一个java.lang包中的静态工具类. 三大字段: static PrintStream err “标准”错误输出流. static InputStream in “标准”输入流 ...
- Struts2上传文件出错
出现错误: Error setting expression 'myFile' with value '[Ljava.lang.String;@47fb02e8' 解决方法: 这是由于没有设置 < ...
- JSP页面用<a>标签访问 Action 出错
问题: JSP页面 <a href="/crud1/crud1/add.action" >添加</a> struts.xml 中: <package ...