SSH study notes (c)

Third, project development

The following is added in front of a small project in a small feature, dynamically generated execl file and download, to use apache's POI components, this package has been spring loaded by default

1, the method of adding the UserService.java

public InputStream getInputStream();

Achieved in its implementation class

package com.test.service.impl; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import com.test.bean.User; import com.test.dao.UserDAO; import com.test.service.UserService; public class UserServiceImpl implements UserService { private UserDAO userDao; public void delete(User user) { // TODO Auto-generated method stub this.userDao.removeUser(user); } public List<User> findAll() { // TODO Auto-generated method stub return this.userDao.findAllUsers(); } public User findById(Integer id) { // TODO Auto-generated method stub return this.userDao.findUserById(id); } public void save(User user) { // TODO Auto-generated method stub this.userDao.saveUser(user); } public void update(User user) { // TODO Auto-generated method stub this.userDao.updateUser(user); } public UserDAO getUserDao() { return userDao; } public void setUserDao(UserDAO userDao) { this.userDao = userDao; } public InputStream getInputStream() { HSSFWorkbook wb = new HSSFWorkbook(); //生成ececl HSSFSheet sheet = wb.createSheet("sheet1"); //创建sheet1 HSSFRow row = sheet.createRow(0); //创建一行 HSSFCell cell = row.createCell((short) 0); //一个单元格 cell.setEncoding(HSSFCell.ENCODING_UTF_16); //设置字符集 cell.setCellValue("序号"); cell = row.createCell((short) 1); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue("姓"); cell = row.createCell((short) 2); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue("名"); cell = row.createCell((short) 3); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue("年龄"); List<User> list = this.findAll(); for (int i = 0; i < list.size(); ++i) { User user = list.get(i); row = sheet.createRow(i + 1); cell = row.createCell((short) 0); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(i + 1); cell = row.createCell((short) 1); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(user.getFirstname()); cell = row.createCell((short) 2); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(user.getLastname()); cell = row.createCell((short) 3); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(user.getAge()); } File file = new File("test.xls"); try { OutputStream os = new FileOutputStream(file); wb.write(os); os.close(); } catch (Exception e) { e.printStackTrace(); } InputStream is = null; try { is = new FileInputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } return is; } }

Temporary files produced test.xls bin directory in apache

2, the new GenerateExcelAction.java in com.test.user.action

package com.test.action.user; import java.io.InputStream; import com.opensymphony.xwork2.ActionSupport; import com.test.service.UserService; public class GenerateExcelAction extends ActionSupport { private UserService service; public UserService getService() { return service; } public void setService(UserService service) { this.service = service; } public InputStream getDownloadFile() { return this.service.getInputStream(); } @Override public String execute() throws Exception { return SUCCESS; } }

Add action statements in the structs.xml

<Action name = "generateExcel" class = "generateExcelAction"> <result name = "success" type = "stream"> <-! Note type stream -> <param name = "contentType"> application / vnd.ms -excel </ param> <-! file types -> <param name = "contentDisposition"> filename = "AllUsers.xls" </ param> <-! browser renders the file name -> <param name = "inputName"> downloadFile </ param> <-! file download method is getDownloadFile -> </ result> </ action>

Add action statements in the applicationContext.xml

<Bean id = "generateExcelAction" class = "com.test.action.user.GenerateExcelAction" scope = "singleton"> <-! No class state, may be configured to singleton -> <property name = "service" ref = "userService"> </ property> </ bean>

Add a link in the list.jsp

<s:a href="index.jsp">Homepage</s:a><br><br> <s:a href="generateExcel.action">生成excel</s:a>

Well, this function has been completed.


3, but there is a problem: the program generates an intermediate file, if there is a connection in writing this document, just there is another connection to download the file, this will lead to conflict. There are two solutions: 1), for each connection generates a random name of intermediate file, when the connection ends promptly delete the middle file. 2), the flow directly to the output memory, to directly generate Inputstream delivery client, so as not to generate the temporary file, the method described in point 4.

For the first method, there are two ways: they write code to generate random strings or using third-party libraries. To write their own code words as follows:

New Package com.test.util in the project, the new CharacterUtils.java in the package

package com.test.util; // project in general have util package, wrapped a supporting role in this method is generally static, so a direct call on the line import java.util.Random; public class CharacterUtils {public static String getRandomString (int length) length length // producing random random string, a method of {string str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; random random = new random (); StringBuffer sb = new StringBuffer (); for (int i = 0; i <length ; ++ i) {int number = random.nextInt (62); sb.append (str.charAt (number));} return sb.toString ();} // public static String getRandomString2 (int length) // production random length length random string, method II // {// random random = new random (); // StringBuffer sb = new StringBuffer (); // // for (int i = 0; i <length; + + i) // {// int number = random.nextInt (3); // long result = 0; // // switch (number) // {// case 0: // result = Math.round (Math .random () * 25 + 65); // sb.append (String.valueOf((char)result)); // break; // case 1: // result = Math.round(Math.random() * 25 + 97); // sb.append(String.valueOf((char)result)); // break; // case 2: // sb.append(String.valueOf(new Random().nextInt(10))); // break; // } // } // // return sb.toString(); // } // public static void main(String[] args) // { // System.out.println(getRandomString2(10)); // } }

The UserServiceImpl.java generated in test.xml place changed

String fileName = CharacterUtils.getRandomString(10); fileName = new StringBuffer(fileName).append(".xls").toString(); File file = new File(fileName);

To achieve the effect of generating a random string, the package can also be provided apache, the following embodiments:
The UserServiceImpl.java in place to generate test.xml

String fileName = RandomStringUtils.randomAlphanumeric(10); //apache 提供的方法 fileName = new StringBuffer(fileName).append(".xls").toString(); File file = new File(fileName);

The following delete the temporary files, our approach is 20 minutes thread delete this file after file generation is good, and every time the server is started when checking in init () method if there were a temporary file in the apache bin directory, if any then deleted.
Added in UserServiceImpl.java

new Thread (new Runnable () {public void run () {try {Thread.sleep (20000 * 60); // Sleep 20 minutes} catch (InterruptedException e) {e.printStackTrace ();} file.delete (); // delete temporary files}}) start ().;

New Package com.test.servlet, new in the package DeleteFileServlet.java, the servlet xls to delete the temporary files in the bin directory in apache tomcat startup time, the user can not access the servlet, the servlet only need to implement init ( ) method, without the need doGet (), doPost (), does not require servlet-mapping.

package com.test.servlet; import java.io.File; import java.io.FileFilter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; public class DeleteFilesServlet extends HttpServlet { public void destroy() { } public void init() throws ServletException { // 方法一比较简单 // File file = new File("."); //获取当前目录文件 // // File[] subFiles = file.listFiles(); // // for(File f : subFiles) // { // if(f.getName().endsWith("xls")) // { // f.delete(); // } // } // 方法二,使用FileFilter File file = new File("."); File[] subFiles = file.listFiles(new FileFilter() { public boolean accept(File pathname) { if(pathname.getName().endsWith("xls")) { return true; } return false; } } ); for(File f : subFiles) { f.delete(); } } }

Join in web.xml

<servlet> <servlet-name>DeleteFilesServlet</servlet-name> <servlet-class>com.test.servlet.DeleteFilesServlet</servlet-class> <load-on-startup>8</load-on-startup> </servlet>

 

4. Well, now look at the second way, does not generate temporary files directly to the output stream. In this case Step 3 all need to do, directly in UserServiceImpl.java

ByteArrayOutputStream os = new ByteArrayOutputStream(); //不生成临时文件 try { wb.write(os); } catch (IOException e) { e.printStackTrace(); } byte[] content = os.toByteArray(); InputStream is = new ByteArrayInputStream(content); return is;

 

So far, the system has been completed.

appendix:

Whole notes referring to the [Long Xi original] Struts2.Hibernate3.2.Spring2.0 integration (mid-air), which is a good video tutorials for a quick overview of SSH

Project Source http://www.kuaipan.cn/file/id_3287587011724175.html


 


 


 



 

Reproduced in: https: //www.cnblogs.com/moiyer/archive/2011/08/24/2316165.html

Guess you like

Origin blog.csdn.net/weixin_34162228/article/details/94693166
Recommended