单例模式
//读取配置文件的工具类-单例模式public class ConfigManager { private static Properties properties; private static ConfigManager configManager; // 私有构造器-读取数据库配置文件 private ConfigManager() { properties = new Properties(); String configFile = "database.properties"; InputStream is = ConfigManager.class.getClassLoader() .getResourceAsStream(configFile); try { properties.load(is); is.close(); } catch (IOException e) { e.printStackTrace(); } } // 全局访问点 public static ConfigManager getInstance() { if (configManager == null) { configManager = new ConfigManager(); } return configManager; } public String getValue(String key) { return properties.getProperty(key); }}
懒汉模式
饿汉模式
Spring MVC-Controller的单例管理
文件上传
单文件上传
@RequestMapping(value = "/useradd.do") public String addUser( User user, @RequestParam(value = "a_idPicPath", required = false) MultipartFile file, HttpSession session, HttpServletRequest request) { String idPicPath = null; // 判断文件是否为空 if (!file.isEmpty()) { // 定义目标上传路径 String path = request.getSession().getServletContext() .getRealPath("statics" + File.separator + "uploadfiles"); String oldFileName = file.getOriginalFilename(); String suffix = FilenameUtils.getExtension(oldFileName); int filesize = 500000; if (file.getSize() > filesize) { request.setAttribute("uploadFileError", "* 上传大小不得超过500K"); return "useradd"; } else if (suffix.equalsIgnoreCase("jpg") || suffix.equalsIgnoreCase("jpeg") || suffix.equalsIgnoreCase("png") || suffix.equalsIgnoreCase("pneg")) { // 当前系统时间+随机数+"_Personal.jpg" String fileName = System.currentTimeMillis() + RandomUtils.nextInt(1000000) + "_Personal.jpg"; File targetFile = new File(path, fileName); if (!targetFile.exists()) { targetFile.mkdirs(); } try { file.transferTo(targetFile); } catch (Exception e) { e.printStackTrace(); request.setAttribute("uploadFileError", "* 上传失败"); return "useradd"; } idPicPath = path + File.separator + fileName; } else { request.setAttribute("uploadFileError", "* 上传图片格式不正确"); return "useradd"; } } user.setCreatedBy(((User) session.getAttribute(Constants.USER_SESSION)) .getId()); user.setCreationDate(new Date()); user.setIdPicPath(idPicPath); if (userService.add(user)) { return "redirect:/user/userlist.do"; } return "useradd"; }
多文件上传