对于想了解在JavaServlet中创建并下载CSV文件的读者,本文将提供新的信息,我们将详细介绍javaservlet怎么建立,并且为您提供关于Error:(12,8)java:无法访问javax.
对于想了解在Java Servlet中创建并下载CSV文件的读者,本文将提供新的信息,我们将详细介绍java servlet怎么建立,并且为您提供关于Error:(12, 8) java: 无法访问javax.servlet.ServletException 找不到javax.servlet.ServletException的类文件、java servlet 下载文件、Java Servlet(十一):一个servlet被10个浏览器客户端访问时会创建几个servlet实例?、Java Servlet:在Servlet中发送重定向和转发之间的区别的有价值信息。
本文目录一览:- 在Java Servlet中创建并下载CSV文件(java servlet怎么建立)
- Error:(12, 8) java: 无法访问javax.servlet.ServletException 找不到javax.servlet.ServletException的类文件
- java servlet 下载文件
- Java Servlet(十一):一个servlet被10个浏览器客户端访问时会创建几个servlet实例?
- Java Servlet:在Servlet中发送重定向和转发之间的区别
在Java Servlet中创建并下载CSV文件(java servlet怎么建立)
我正在研究Java ExtJS应用程序,需要在其中创建和下载CSV文件。
- 单击按钮后,我希望将CSV文件下载到客户端计算机上。
- 在按钮侦听器上,我正在使用AJAX调用servlet。在那里,我正在创建一个CSV文件。
我不希望将CSV文件保存在服务器中。我希望使用下载选项 动态 创建文件。我希望将文件的内容创建为字符串,然后将其作为 文件
提供,然后在浏览器中以下载模式打开该 文件 (这是我用其他语言实现的,但是不确定如何用Java实现) )。
这是我的代码,仅用于创建CSV文件,但是如果我只能将文件下载为CSV,我真的不想创建或保存CSV文件。
public String createCSV() { try { String filename = "c:\\test.csv"; FileWriter fw = new FileWriter(filename); fw.append("XXXX"); fw.append('',''); fw.append("YYYY"); fw.append('',''); fw.append("ZZZZ"); fw.append('',''); fw.append("AAAA"); fw.append('',''); fw.append("BBBB"); fw.append(''\n''); CSVResult.close(); return "Csv file Successfully created"; } catch(Exception e) { return e.toString(); }}
谁可以帮我这个事。
谢谢
答案1
小编典典我得到了解决方案,并将其发布在下面。
public void doGet(HttpServletRequest request, HttpServletResponse response){ response.setContentType("text/csv"); response.setHeader("Content-Disposition", "attachment; filename=\"userDirectory.csv\""); try { OutputStream outputStream = response.getOutputStream(); String outputResult = "xxxx, yyyy, zzzz, aaaa, bbbb, ccccc, dddd, eeee, ffff, gggg\n"; outputStream.write(outputResult.getBytes()); outputStream.flush(); outputStream.close(); } catch(Exception e) { System.out.println(e.toString()); }}
在这里,我们不需要在服务器中保存/存储文件。
谢谢
Error:(12, 8) java: 无法访问javax.servlet.ServletException 找不到javax.servlet.ServletException的类文件
Error:(12, 8) java: 无法访问javax.servlet.ServletException
找不到javax.servlet.ServletException的类文件
需要添加servlet依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
或者
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
java servlet 下载文件
resp.setContentType("text/html;charset=UTF-8"); String path = "http://yjsy.cupl.edu.cn/attachments/article/2689/2017%E5%B9%B4%E7%A1%95%E5%A3%AB%E7%A0%94%E7%A9%B6%E7%94%9F%E7%BB%9F%E8%80%83%E6%8B%9F%E6%8B%9B%E7%94%9F%E8%AE%A1%E5%88%92.pdf"; //设置返回头 resp.setHeader("Content-Disposition", "attachment;filename=" + filename); try { logger.debug("--- process start ---"); URL url = new URL(path); // 返回一个 URLConnection 对象,它表示到 URL 所引用的远程对象的连接。 URLConnection uc = url.openConnection(); //读取文件 InputStream in = uc.getInputStream(); OutputStream out = resp.getOutputStream(); //写文件 int b; while((b=in.read())!= -1) { out.write(b); } //流一定要记得关闭 in.close(); out.close(); } catch (MalformedURLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IOException e1) { // TODO Auto-generated catch block e1.printStackTrace(); }
Java Servlet(十一):一个servlet被10个浏览器客户端访问时会创建几个servlet实例?
一般Servlet只初始化一次(只有一个实例)。对于更多的客户端请求,Server创建新的请求和响应对象,仍然激活此Servlet的service()方法,将这两个对象作为参数传递给该方法。如此重复以上的循环,但无需再调用init()方法。
原因:
出于性能的考虑:特别的对于门户网站而言,每一个Servlet在每一秒内的并发访问量都可以是成千上万的。在一个面向模块化开发的现在,常常一个点击操作就被定义为一个Servlet的实现,而如果Servlet的每一次被访问,都创建一个新的实例的话,服务器的可用资源消耗量将是一个相当重要的问题。
退一步,一般Servlet的访问是很快的,每一个实例被快速的创建,又被快速的回收,GC的回收速度也跟不上,频繁的内存操作也将可能带来次生的问题。
所以,Servlet的“单一实例化”是一个很重要的策略。
此时为了更好理解servlet,这里附上servlet、httpservlet代码:
Servlet源代码:
package javax.servlet;
import java.io.IOException;
// Referenced classes of package javax.servlet:
// ServletException, ServletConfig, ServletRequest, ServletResponse
public interface Servlet
{
public abstract void init(ServletConfig servletconfig)
throws ServletException;
public abstract ServletConfig getServletConfig();
public abstract void service(ServletRequest servletrequest, ServletResponse servletresponse)
throws ServletException, IOException;
public abstract String getServletInfo();
public abstract void destroy();
}
HttpServlet源代码:
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.ResourceBundle;
import javax.servlet.*;
// Referenced classes of package javax.servlet.http:
// NoBodyResponse, HttpServletRequest, HttpServletResponse
public abstract class HttpServlet extends GenericServlet
implements Serializable
{
public HttpServlet()
{
}
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_get_not_supported");
if(protocol.endsWith("1.1"))
resp.sendError(405, msg);
else
resp.sendError(400, msg);
}
protected long getLastModified(HttpServletRequest req)
{
return -1L;
}
protected void doHead(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
NoBodyResponse response = new NoBodyResponse(resp);
doGet(req, response);
response.setContentLength();
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_post_not_supported");
if(protocol.endsWith("1.1"))
resp.sendError(405, msg);
else
resp.sendError(400, msg);
}
protected void doPut(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_put_not_supported");
if(protocol.endsWith("1.1"))
resp.sendError(405, msg);
else
resp.sendError(400, msg);
}
protected void doDelete(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String protocol = req.getProtocol();
String msg = lStrings.getString("http.method_delete_not_supported");
if(protocol.endsWith("1.1"))
resp.sendError(405, msg);
else
resp.sendError(400, msg);
}
private Method[] getAllDeclaredMethods(Class c)
{
if(c.equals(javax/servlet/http/HttpServlet))
return null;
Method parentMethods[] = getAllDeclaredMethods(c.getSuperclass());
Method thisMethods[] = c.getDeclaredMethods();
if(parentMethods != null && parentMethods.length > 0)
{
Method allMethods[] = new Method[parentMethods.length + thisMethods.length];
System.arraycopy(parentMethods, 0, allMethods, 0, parentMethods.length);
System.arraycopy(thisMethods, 0, allMethods, parentMethods.length, thisMethods.length);
thisMethods = allMethods;
}
return thisMethods;
}
protected void doOptions(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
Method methods[] = getAllDeclaredMethods(getClass());
boolean ALLOW_GET = false;
boolean ALLOW_HEAD = false;
boolean ALLOW_POST = false;
boolean ALLOW_PUT = false;
boolean ALLOW_DELETE = false;
boolean ALLOW_TRACE = true;
boolean ALLOW_OPTIONS = true;
for(int i = 0; i < methods.length; i++)
{
Method m = methods[i];
if(m.getName().equals("doGet"))
{
ALLOW_GET = true;
ALLOW_HEAD = true;
}
if(m.getName().equals("doPost"))
ALLOW_POST = true;
if(m.getName().equals("doPut"))
ALLOW_PUT = true;
if(m.getName().equals("doDelete"))
ALLOW_DELETE = true;
}
String allow = null;
if(ALLOW_GET && allow == null)
allow = "GET";
if(ALLOW_HEAD)
if(allow == null)
allow = "HEAD";
else
allow = (new StringBuilder()).append(allow).append(", HEAD").toString();
if(ALLOW_POST)
if(allow == null)
allow = "POST";
else
allow = (new StringBuilder()).append(allow).append(", POST").toString();
if(ALLOW_PUT)
if(allow == null)
allow = "PUT";
else
allow = (new StringBuilder()).append(allow).append(", PUT").toString();
if(ALLOW_DELETE)
if(allow == null)
allow = "DELETE";
else
allow = (new StringBuilder()).append(allow).append(", DELETE").toString();
if(ALLOW_TRACE)
if(allow == null)
allow = "TRACE";
else
allow = (new StringBuilder()).append(allow).append(", TRACE").toString();
if(ALLOW_OPTIONS)
if(allow == null)
allow = "OPTIONS";
else
allow = (new StringBuilder()).append(allow).append(", OPTIONS").toString();
resp.setHeader("Allow", allow);
}
protected void doTrace(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String CRLF = "\r\n";
String responseString = (new StringBuilder()).append("TRACE ").append(req.getRequestURI()).append(" ").append(req.getProtocol()).toString();
for(Enumeration reqHeaderEnum = req.getHeaderNames(); reqHeaderEnum.hasMoreElements();)
{
String headerName = (String)reqHeaderEnum.nextElement();
responseString = (new StringBuilder()).append(responseString).append(CRLF).append(headerName).append(": ").append(req.getHeader(headerName)).toString();
}
responseString = (new StringBuilder()).append(responseString).append(CRLF).toString();
int responseLength = responseString.length();
resp.setContentType("message/http");
resp.setContentLength(responseLength);
ServletOutputStream out = resp.getOutputStream();
out.print(responseString);
out.close();
}
protected void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
String method = req.getMethod();
if(method.equals("GET"))
{
long lastModified = getLastModified(req);
if(lastModified == -1L)
{
doGet(req, resp);
} else
{
long ifModifiedSince = req.getDateHeader("If-Modified-Since");
if(ifModifiedSince < (lastModified / 1000L) * 1000L)
{
maybeSetLastModified(resp, lastModified);
doGet(req, resp);
} else
{
resp.setStatus(304);
}
}
} else
if(method.equals("HEAD"))
{
long lastModified = getLastModified(req);
maybeSetLastModified(resp, lastModified);
doHead(req, resp);
} else
if(method.equals("POST"))
doPost(req, resp);
else
if(method.equals("PUT"))
doPut(req, resp);
else
if(method.equals("DELETE"))
doDelete(req, resp);
else
if(method.equals("OPTIONS"))
doOptions(req, resp);
else
if(method.equals("TRACE"))
{
doTrace(req, resp);
} else
{
String errMsg = lStrings.getString("http.method_not_implemented");
Object errArgs[] = new Object[1];
errArgs[0] = method;
errMsg = MessageFormat.format(errMsg, errArgs);
resp.sendError(501, errMsg);
}
}
private void maybeSetLastModified(HttpServletResponse resp, long lastModified)
{
if(resp.containsHeader("Last-Modified"))
return;
if(lastModified >= 0L)
resp.setDateHeader("Last-Modified", lastModified);
}
public void service(ServletRequest req, ServletResponse res)
throws ServletException, IOException
{
HttpServletRequest request;
HttpServletResponse response;
try
{
request = (HttpServletRequest)req;
response = (HttpServletResponse)res;
}
catch(ClassCastException e)
{
throw new ServletException("non-HTTP request or response");
}
service(request, response);
}
private static final String METHOD_DELETE = "DELETE";
private static final String METHOD_HEAD = "HEAD";
private static final String METHOD_GET = "GET";
private static final String METHOD_OPTIONS = "OPTIONS";
private static final String METHOD_POST = "POST";
private static final String METHOD_PUT = "PUT";
private static final String METHOD_TRACE = "TRACE";
private static final String HEADER_IFMODSINCE = "If-Modified-Since";
private static final String HEADER_LASTMOD = "Last-Modified";
private static final String LSTRING_FILE = "javax.servlet.http.LocalStrings";
private static ResourceBundle lStrings = ResourceBundle.getBundle("javax.servlet.http.LocalStrings");
}
参考:《.init()方法成功完成后,Servlet可以接受请求.默认有多少个Servlet实例被创建》、《Java Servlet(二):servlet配置及生命周期相关(jdk7+tomcat7+eclipse)》
Java Servlet:在Servlet中发送重定向和转发之间的区别
我正在使用servlet,有两种方法重定向和转发都将请求发送到同一页面,但是它们之间有什么区别。
答案1
小编典典redirect-它使用浏览器重定向。它发送代码为3xx的http响应(请参阅Wikipedia),然后浏览器向新页面发出另一个请求。
forward-Forward是Servlet容器的内部组件。浏览器从不了解页面已更改。因此,URL不会更改(例如重定向),并且在新页面中您也有相同的请求。
关于在Java Servlet中创建并下载CSV文件和java servlet怎么建立的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于Error:(12, 8) java: 无法访问javax.servlet.ServletException 找不到javax.servlet.ServletException的类文件、java servlet 下载文件、Java Servlet(十一):一个servlet被10个浏览器客户端访问时会创建几个servlet实例?、Java Servlet:在Servlet中发送重定向和转发之间的区别的相关知识,请在本站寻找。
本文标签: