Session的方法getSession() 与 getSession(boolean para)区别

本文解析了HTTP请求中getSession方法的功能及使用场景。详细介绍了getSession(boolean create)如何根据参数决定是否创建新的HttpSession,以及其在不同情况下的行为表现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

getSession(boolean para)返回当前http会话,如果不存在,则创建一个新的会话
getSession() 调用getSession(true)的简化版

 

【官方解释】
getSession
public HttpSession getSession(boolean create)
Returns the current HttpSession associated with this request or, if if there is no current session and create is true, returns a new session.
If create is false and the request has no valid HttpSession, this method returns null.
To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown.
Parameters: true - to create a new session for this request if necessary; false to return null if there's no current session
Returns: the HttpSession associated with this request or null if create is false and the request has no valid session
译:
getSession(boolean create)意思是返回当前reqeust中的HttpSession ,如果当前reqeust为false,并且当前没有HttpSession,那么久返回为null,如果create为true,没有Session时就会创建一个新的Session;
简而言之:
HttpServletRequest.getSession(ture) 等同于 HttpServletRequest.getSession()
HttpServletRequest.getSession(false) 等同于 如果当前Session没有就为null;

转载于:https://www.cnblogs.com/liaojie970/p/4800035.html

package com.example.test1.service; import com.example.test1.component.WordToHtmlConverter; import com.jcraft.jsch.; import org.apache.poi.xwpf.usermodel.; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import java.io.; import java.nio.file.; import java.util.UUID; @Service public class FileProcessingService { // 远程服务器配置 private static final String REMOTE_HOST = “”; private static final int REMOTE_PORT = ; private static final String REMOTE_USER = “”; private static final String REMOTE_PASSWORD = “#”; private static final String REMOTE_BASE_DIR = “////”; private static final String BASE_URL = “/images/”; private static final String LOCAL_TEMP_DIR = System.getProperty(“java.io.tmpdir”) + “/service_files/”; public String processInput(Object input) throws Exception { if (input instanceof String) { return processText((String) input); } else if (input instanceof MultipartFile) { return processFile((MultipartFile) input); } throw new IllegalArgumentException(“Unsupported input type”); } private String processText(String text) { // 转义HTML特殊字符 String escapedText = escapeHtml(text); // 保留换行符 - 将换行符转换为 标签 String withBreaks = escapedText.replace(“\n”, “ ”); // 直接返回HTML内容 return “ ” + withBreaks + “ ”; } private String processFile(MultipartFile file) throws Exception { String originalName = file.getOriginalFilename(); if (originalName == null) throw new IllegalArgumentException(“Invalid file name”); String extension = originalName.substring(originalName.lastIndexOf(“.”) + 1).toLowerCase(); switch (extension) { case “jpg”: case “jpeg”: case “png”: case “gif”: // 生成包含图片引用的HTML String imageUrl = uploadImage(file.getBytes(), extension); return “<img src="” + imageUrl + “" alt="Service Image">”; case “doc”: case “docx”: // 转换Word文档为HTML return convertToHtml(file.getInputStream()); default: throw new IllegalArgumentException(“Unsupported file type: " + extension); } } /** * 上传图片到远程服务器 * @param imageData 图片字节数组 * @param extension 文件扩展名 * @return 图片URL */ public String uploadImage(byte[] imageData, String extension) throws Exception { String fileName = “img_” + UUID.randomUUID() + “.” + extension; Path tempPath = saveTempFile(imageData, fileName); uploadViaSftp(tempPath, fileName); return BASE_URL + fileName; } private void uploadViaSftp(Path localPath, String remoteFileName) throws Exception { JSch jsch = new JSch(); Session session = jsch.getSession(REMOTE_USER, REMOTE_HOST, REMOTE_PORT); session.setPassword(REMOTE_PASSWORD); session.setConfig(“StrictHostKeyChecking”, “no”); session.connect(); ChannelSftp channel = (ChannelSftp) session.openChannel(“sftp”); channel.connect(); // 确保远程目录存在 try { channel.cd(REMOTE_BASE_DIR); } catch (SftpException e) { channel.mkdir(REMOTE_BASE_DIR); channel.cd(REMOTE_BASE_DIR); } // 上传文件 channel.put(localPath.toString(), remoteFileName); // 清理本地文件 Files.deleteIfExists(localPath); channel.disconnect(); session.disconnect(); } private Path saveTempFile(byte[] data, String fileName) throws IOException { Path dirPath = Paths.get(LOCAL_TEMP_DIR); if (!Files.exists(dirPath)) { Files.createDirectories(dirPath); } Path filePath = dirPath.resolve(fileName); Files.write(filePath, data); return filePath; } public String convertToHtml(InputStream docxStream) throws Exception { try (XWPFDocument document = new XWPFDocument(docxStream)) { StringBuilder htmlBuilder = new StringBuilder(); htmlBuilder.append(”“); // 处理段落 for (XWPFParagraph paragraph : document.getParagraphs()) { htmlBuilder.append(processParagraph(paragraph)); } // 处理表格 for (XWPFTable table : document.getTables()) { htmlBuilder.append(processTable(table)); } htmlBuilder.append(”“); return htmlBuilder.toString(); } } private String processParagraph(XWPFParagraph paragraph) throws Exception { StringBuilder paraBuilder = new StringBuilder(); boolean isFirstRun = true; for (XWPFRun run : paragraph.getRuns()) { String text = run.getText(0); // 处理图片 if (run.getEmbeddedPictures().size() > 0) { for (XWPFPicture picture : run.getEmbeddedPictures()) { XWPFPictureData picData = picture.getPictureData(); // 上传图片并获取URL String imageUrl = uploadImage( picData.getData(), picData.suggestFileExtension() ); paraBuilder.append(”<img src="“).append(imageUrl).append(”" alt="">“); } } if (text != null && !text.trim().isEmpty()) { // 处理换行符 String processedText = text.replace(”\n", “ ”); // 处理文本样式 if (run.isBold()) paraBuilder.append(“”); if (run.isItalic()) paraBuilder.append(“”); paraBuilder.append(escapeHtml(processedText)); if (run.isItalic()) paraBuilder.append(“”); if (run.isBold()) paraBuilder.append(“”); } // 检测换行符(Word中的硬回车) if (run.getCTR().getBrArray().length > 0) { paraBuilder.append(“ ”); } isFirstRun = false; } // 如果是空段落,保留换行效果 if (paraBuilder.length() == 0) { return “ ”; } return “ ” + paraBuilder.toString() + “ ”; } private String processTable(XWPFTable table) throws Exception { StringBuilder tableBuilder = new StringBuilder(“<table border="1">”); for (XWPFTableRow row : table.getRows()) { tableBuilder.append(“”); for (XWPFTableCell cell : row.getTableCells()) { tableBuilder.append(“”); for (XWPFParagraph para : cell.getParagraphs()) { tableBuilder.append(processParagraph(para)); } tableBuilder.append(“”); } tableBuilder.append(“”); } tableBuilder.append(“”); return tableBuilder.toString(); } private String escapeHtml(String text) { return text.replace(“&”, “&”) .replace(“<”, “<”) .replace(“>”, “>”) .replace(“"”, “"”) .replace(“'”, “'”); } }修改之前的解决方案,支持文体和图片同时传入,且图片支持多图片传入,转为HTML。保留word上传转为HTML功能。图片都存入服务器
最新发布
07-11
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值