Java 如何使用单例模式计数器为图像上载设置自动数字名称生成器
所以我的问题是,我必须创建一个用于数字命名的单例模式计数器。例如“1”、“2”、“3”等。其思想是每次我启动应用程序和服务器(tomcat)时,它都会得到最后一个数字,当我上传另一个图像时,它应该从那里继续。让我们假设最后一个是“43”,所以下次我启动应用程序时,它应该知道它,并将“44”用于下一个图像上传 我的Java不是很好,所以请给我一些耐心:) 这是我的FileUploadServlet。它通过从submit中获取文件来处理来自fileUploadForm.jsp的请求Java 如何使用单例模式计数器为图像上载设置自动数字名称生成器,java,tomcat,servlets,file-upload,singleton,Java,Tomcat,Servlets,File Upload,Singleton,所以我的问题是,我必须创建一个用于数字命名的单例模式计数器。例如“1”、“2”、“3”等。其思想是每次我启动应用程序和服务器(tomcat)时,它都会得到最后一个数字,当我上传另一个图像时,它应该从那里继续。让我们假设最后一个是“43”,所以下次我启动应用程序时,它应该知道它,并将“44”用于下一个图像上传 我的Java不是很好,所以请给我一些耐心:) 这是我的FileUploadServlet。它通过从submit中获取文件来处理来自fileUploadForm.jsp的请求 package
package upload;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import utils.FormatChecker;
import utils.UnzipFile;
//Servlet for handling the Upload request from the Index.jsp
@MultipartConfig
public class FileUploadServlet extends HttpServlet {
// Instace of the FileUpload object
private FileUploader uploader = new FileUploader();
// Instance of the FormatChecker object
private FormatChecker checker = new FormatChecker();
// Instance of the UnzipFile object
private UnzipFile unzip = new UnzipFile();
private static final long serialVersionUID = 1L;
private static final String SAVE_FOLDER = "C:\\Users\\cuche\\Desktop\\tomcat\\apache-tomcat-7.0.47\\webapps\\files";
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("error.jsp");
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String contentType;
boolean isFormatValid;
Part filePart = request.getPart("file");
contentType = filePart.getContentType();
ServletContext context = getServletContext();
String appPath = context.getRealPath("/");
String fileNameOld = getFileName(filePart);
String fileNameNew = appPath + fileNameOld;
isFormatValid = checker.check(contentType);
请忽略带有FileUnziper的部分
if (isFormatValid == true) {
if (contentType == ("application/x-zip-compressed")) {
unzip.FileUnziper(fileNameNew, SAVE_FOLDER);
} else {
//gets the content and saves in form of a stream
InputStream fileContent = filePart.getInputStream();
//using the uploadImage method of uploader class
uploader.uploadImage(fileNameNew, fileContent);
}
try {
response.sendRedirect("result.jsp");
} catch (IOException ex) {
response.getWriter().append(ex.getLocalizedMessage());
}
} else {
response.getWriter().append("Format is wrong");
}
}
// method for removing header for proper file upload
private String getFileName(Part part) {
for (String cd : part.getHeader("content-disposition").split(";")) {
if (cd.trim().startsWith("filename")) {
String filename = cd.substring(cd.indexOf('=') + 1).trim()
.replace("\"", "");
return filename.substring(filename.lastIndexOf('/') + 1)
.substring(filename.lastIndexOf('\\') + 1); // MSIE fix.
}
}
return null;
}
}
这是我的FileUploader类
package upload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* @author Iwan Cuche
* @date:
*/
public class FileUploader {
/**
* This method reads a File
*
* @param fileName
* @param stream
*/
public void uploadImage(String fileName, InputStream stream)
throws IOException {
try {
File file = new File(fileName);
OutputStream os = new FileOutputStream(file);
int data;
while ((data = stream.read()) != -1) {
os.write(data);
}
os.flush();
os.close();
System.out.println("Uploaded file successfully saved in "
+ file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
throw e;
}
}
}
这是我的单身班
package utils;
public class ServerCounter {
private static ServerCounter INSTANCE = new ServerCounter();
private ServerCounter() {};
public static ServerCounter getInstance() {
return INSTANCE;
}
}
我希望有人能帮助我,因为我不知道该怎么做。在ServerCounter中,添加
private final AtomicLong counter = new AtomicLong();
public String nextval() { return String.valueOf(counter.incrementAndGet()); }
每次调用INSTANCE.nextval()
都会得到一个新的数字字符串
显然,每次重新启动应用程序时,计数器都会重新启动。在ServerCounter中,添加
private final AtomicLong counter = new AtomicLong();
public String nextval() { return String.valueOf(counter.incrementAndGet()); }
每次调用INSTANCE.nextval()
都会得到一个新的数字字符串
显然,每次重新启动应用程序时,计数器都会重新启动。好的,如果要在tomcat关闭后获得计数器,首先必须保留计数器。我们需要tomcat的侦听器:
package utils;
public class ContextListener implements ServletContextListener{
void contextInitialized(ServletContextEvent sce){ // we could call loadFromFile here as well
}
//will be executed at tomcat shutdown
void contextDestroyed(ServletContextEvent sce){
ServerCounter .getInstance().writeToFile();
}
}
现在是单身汉(就像Marko的回答:):
现在可以使用ServerCounter.getInstance.nextval()增加计数器并获取值
最后一件事是,您需要将侦听器放入您的Web应用程序:
<web-app>
...
<listener>
<listener-class>utils.ContextListener </listener-class>
</listener>
</web-app>
...
utils.ContextListener
编辑:ServerCounter错误地实现了ServletContextListener
EDIT2:添加了读/写文件好的,如果您想在tomcat关闭后获得计数器,首先必须持久化计数器。我们需要tomcat的侦听器:
package utils;
public class ContextListener implements ServletContextListener{
void contextInitialized(ServletContextEvent sce){ // we could call loadFromFile here as well
}
//will be executed at tomcat shutdown
void contextDestroyed(ServletContextEvent sce){
ServerCounter .getInstance().writeToFile();
}
}
现在是单身汉(就像Marko的回答:):
现在可以使用ServerCounter.getInstance.nextval()增加计数器并获取值
最后一件事是,您需要将侦听器放入您的Web应用程序:
<web-app>
...
<listener>
<listener-class>utils.ContextListener </listener-class>
</listener>
</web-app>
...
utils.ContextListener
编辑:ServerCounter错误地实现了ServletContextListener
EDIT2:添加了读/写文件我想您的主要问题是将上次使用的ID保存在应用程序之外的某个地方,或者保存在数据库中,或者保存在某个文本文件中。这将是一个瓶颈。你不能改用db序列吗?你说的“每次启动应用程序”是什么意思?你是说每次我重新启动tomcat还是每次我向服务器发送请求?问题是,这是我的第一个“更大”的项目。所以我需要一步一步走。现在我得到了这个上传,图像保存在我电脑的一个文件夹中。接下来是这个计数器,“每次我启动应用程序”是指tomcat的启动。@Leo现在我不使用它,下一步是计数器,然后是DB用法(JavaDB)。我想你的主要问题是将上次使用的ID保存在应用程序之外的某个地方,或者在数据库中,或者在某个文本文件中。这将是一个瓶颈。你不能改用db序列吗?你说的“每次启动应用程序”是什么意思?你是说每次我重新启动tomcat还是每次我向服务器发送请求?问题是,这是我的第一个“更大”的项目。所以我需要一步一步走。现在我得到了这个上传,图像保存在我电脑的一个文件夹中。接下来是这个计数器,“每次我启动应用程序”是指tomcat的启动。@Leo现在我不使用它,下一步是计数器,然后是DB用法(JavaDB)+1谢谢,至少我知道了如何实际处理它。+1谢谢,至少我知道了如何实际处理它。+1非常感谢,非常感谢。你甚至给了我一些代码片段。祝你有愉快的一天:)我会从现在开始努力解决它。再次感谢您关于“从文件加载值”的事情,您建议具体做什么?只需创建一个新文件并由FileReader读取即可。你需要如何做这件事的例子吗?很高兴看到一个例子是的:)我添加了文件读/写的例子。它将使用c\Test\counter.txt文件存储计数器。+1非常感谢,非常感谢。你甚至给了我一些代码片段。祝你有愉快的一天:)我会从现在开始努力解决它。再次感谢您关于“从文件加载值”的事情,您建议具体做什么?只需创建一个新文件并由FileReader读取即可。你需要如何做这件事的例子吗?很高兴看到一个例子是的:)我添加了文件读/写的例子。它将使用c\Test\counter.txt文件存储计数器。