首页 > 其他分享 >struts2 uploadify配合使用,以及处理session丢失问题

struts2 uploadify配合使用,以及处理session丢失问题

时间:2023-02-19 23:35:37浏览次数:44  
标签:LedSessionContext uploadify struts2 sessionId session null public out


直接上代码:

jsp页面中:

<div style="margin: 20px;">
<span>当前最新固件 :</span><label style="margin-left: 10px; color: red;" id="currentFirmware"></label>
</div>
<div style="margin: 20px;">
<p><input type="file" name="firmware" id="firmware" /></p><!-- 注意name的写法 -->
<p style="margin: 20px 0px 0px 15px;"> <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-upload'" οnclick="doUpload();">上 传 固 件</a> (上传固件到服务器,并不更新网关)</p>
<p style="margin: 20px 0px 0px 15px;"> <a href="#" class="easyui-linkbutton" data-options="iconCls:'icon-update'" οnclick="updateGateway();">更 新 固 件</a> (把服务器上最新的固件远程更新到网关)</p>
</div>

 

js:



var path = '<%=request.getContextPath()%>';
var sessionId = '<%=request.getSession().getId()%>';





$(function() {
$('#firmware').uploadify( {
'buttonText' : '选 择 固 件',
'fileObjName' : 'firmware', // 需和input的name,以及struts2中的三个文件上传属性一致
'swf' : path + '/js/uploadify/uploadify.swf',
'uploader' : path + '/doUpload.action', // 必须全路径 uploadPorcessServlet
'multi' : false,
'auto' : false,
'fileTypeDesc' : '固件',
'fileTypeExts' : '*.bin',
'formData' : {
'sessionId' : sessionId
},// sessionId用于解决session丢失的问题
'fileSizeLimit' : '10240KB',
'removeCompleted' : false,
'onUploadSuccess' : function(file, data, response) {
//alert('The file ' + file.name + ' was successfully uploaded with a response of ' + response + ':' + data);
if (data != null && data != '' && data != 'null') {
$.messager.alert('提示信息', data, 'info');
return;
} else {
$.messager.alert('提示信息', '上传成功', 'info');
//得到最新固件信息
getNewest();
}
}
});

//页面初始化时得到服务器上的最新固件
getNewest();
});


 

java类:

因为新的jdk已不支持通过sessionId得到session,所以要自己写个hashMap,保存session

package com.mhm.dto;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

public class LedSessionContext {
private static LedSessionContext instance;
private HashMap<String, HttpSession> sessionMap;

private LedSessionContext() {
sessionMap = new HashMap<String, HttpSession>();
}

public static LedSessionContext getInstance() {
if (instance == null) {
instance = new LedSessionContext();
}
return instance;
}

public synchronized void AddSession(HttpSession session) {
if (session != null) {
sessionMap.put(session.getId(), session);
}
}

public synchronized void DelSession(HttpSession session) {
if (session != null) {
sessionMap.remove(session.getId());
}
}

public synchronized HttpSession getSession(String sessionId) {
if (sessionId == null)
return null;
return (HttpSession) sessionMap.get(sessionId);
}

}

 

监听session的创建以及销毁

package com.mhm.listener;

import java.util.HashMap;

import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import com.mhm.dto.LedSessionContext;

public class SessionListener implements HttpSessionListener {

public static HashMap<String, HttpSession> sessionMap = new HashMap<String, HttpSession>();

private LedSessionContext lsc = LedSessionContext.getInstance();

@Override
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
lsc.AddSession(httpSessionEvent.getSession());
}

@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
HttpSession session = httpSessionEvent.getSession();
lsc.DelSession(session);
}

}

 

Action:

// =========== 供上传使用的字段,必须和jsp页面一致=============
private File firmware;
private String firmwareFileName;
private String firmwareFileContentType;
// =========== 供上传使用的字段=============

 

@Action(value = "doUpload", results = { @Result(name = Constants.SUCCESS, type = "json") })
public String doUpload() {
log.info("method begin: doUpload()");
PrintWriter out = null;
try {
HttpServletResponse response = getResponse();
response.setContentType("text/html;charset=UTF-8");
out = getResponse().getWriter();


String sessionId = (String)getRequest().getParameter("sessionId");
HttpSession session = LedSessionContext.getInstance().getSession(sessionId);
Userinfo user = (Userinfo)session.getAttribute(LedConstants.LOGINUSER);

if (user == null) {
rtnMsg = "用户未登录或登录已超时。上传失败";
out.print(rtnMsg);
out.flush();
out.close();
} else {
String path = getRequest().getSession().getServletContext().getRealPath("/upload");
System.out.println("path : " + path);

// 对文件类型过滤赞不考虑

if (firmware != null) {
StringBuilder newFileName = new StringBuilder();
int dotPos = firmwareFileName.indexOf(".");
String fName = firmwareFileName.substring(0, dotPos);

newFileName.append(fName)
.append("-")
.append(UUID.randomUUID())
.append(firmwareFileName.substring(dotPos));

File savefile = new File(new File(path), newFileName.toString());

if (!savefile.getParentFile().exists()) {
savefile.getParentFile().mkdirs();
}

FileUtils.copyFile(firmware, savefile);


// 上传信息存入数据库
Uploadfile entity = new Uploadfile();
entity.setFname(newFileName.toString());
entity.setOriginalName(firmwareFileName);
entity.setFilePath(path + "\\" + newFileName.toString());
entity.setType(Constants.INT_VALUE1);
entity.setFlag(Constants.INT_VALUE1);
entity.setCreateDate(getNowTimestamp());
entity.setCreateUser(user.getUserId());

uploadFileMng.save(entity);
out.print("");
out.flush();
out.close();
}
}
} catch (IOException ex) {
log.error("doUpload()", ex);
rtnMsg = ex.getLocalizedMessage();
out.print(rtnMsg);
out.flush();
out.close();
}
log.info("method begin: doUpload()");
return SUCCESS;
}

 

 

 

 


标签:LedSessionContext,uploadify,struts2,sessionId,session,null,public,out
From: https://blog.51cto.com/u_21817/6066952

相关文章

  • 使用ThreadLocal+OpenSessionInView优化Mybatis使用
    使用一个名为OpenSessionInView的servlet过滤器,简化在服务中使用mybatis的操作。   一、情况分析Mybatis的使用过程:1、获取配置文件2、获取session工厂......
  • sqlalchemy_装饰器获取session
    /Users/codelearn/fastapi-tutorial-fastapi_with_async_sqlalchemy/run.py#uvicornbackend.app.main:app--host127.0.0.1--port8000#uvicornsrc.main:app--hos......
  • Struts2 下载文件
    最近项目中用到,所以研究了下现在贴出代码注意看这个annotation写的action,不是在struts.xml中配的这样写方便维护/***下载action......
  • What is the difference between session and application state in ASP.NET?
    WhatisthedifferencebetweensessionandapplicationstateinASP.NET?InASP.NET,SessionstateandApplicationstatearetwodifferentwaystostoredatat......
  • 解决 1146 - Table ‘performance_schema.session_variables’ doesn’t exist
    C:\Users\Administrator>cdC:\ProgramFiles\MySQL\MySQLServer5.7\bin输入指令mysql_upgrade-uroot-p--force这是网上的教程,但是我自己在尝试的时候出现了以下......
  • DP8.0安装步骤session
    [root@rx6600]#./omnisetup.sh-CM-ISTheomnisetup.shscriptdidnotcompletethelasttimeitwasrun.CellManagerstillhastobeinstalledInstallation......
  • onnxruntime.InferenceSession
      https://vimsky.com/examples/detail/python-method-onnxruntime.InferenceSession.html  https://github.com/htshinichi/caffe-onnx/blob/master/onnxmodel/t......
  • Connect to RDS using shadow session
    1.Findoutcurrentactivesessions.Usingoneofthetwocommandsqwinsta/server:{rds_server}quser/server:{rds_server}RecordsessionID2.Connectmstsc/......
  • cookie、localStorage、sessionStorage的区别
    1.cookie:能存储内容较小,在4k左右,一般用作保存用户登录状态、记住密码,记住账号使用。不清除的话会一直存在,可以设置过期时间自动清除,设置的时候可以设置在不同的域下面。......
  • 【SpringBoot】Session共享
    本文参考SpringBoot一个依赖搞定session共享,没有比这更简单的方案了!在传统的单服务架构中,只有一个服务器,那就不会存在session共享的问题,但如果在分布式/集群项目......