下面列出了javax.servlet.http.HttpSession#getServletContext() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void toExit(HttpServletRequest request, HttpServletResponse response) throws IOException {
HttpSession session = request.getSession();
if (session.getAttribute("admin") == null) {
session.invalidate();
response.sendRedirect("index.jsp");
return;
}
Users user = (Users) session.getAttribute("user");
ServletContext application = session.getServletContext();
application.removeAttribute(((Users) session.getAttribute("user")).getUname());
Integer onlineNum = (Integer) application.getAttribute("onlineNum");
if (onlineNum > 0) {
application.setAttribute("onlineNum", onlineNum - 1);
}
Object signinid = session.getAttribute("signinid");
int uid = user.getUid();
Timestamp sdtime = Times.getSystemTime();
usersDao.updateOnline(0, uid);
signinDao.updateSignin((Integer) signinid, sdtime);
response.sendRedirect("index.jsp");
}
/**
* @param request
* @return
* @throws AxisFault
*/
private IWAAuthenticatorStub getIWAClient(HttpServletRequest request)
throws AxisFault, IdentityException {
HttpSession session = request.getSession();
ServletContext servletContext = session.getServletContext();
String backendServerURL = request.getParameter("backendURL");
if (backendServerURL == null) {
backendServerURL = CarbonUIUtil.getServerURL(servletContext, request.getSession());
}
ConfigurationContext configContext = (ConfigurationContext) servletContext
.getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
String serviceEPR = backendServerURL + "IWAAuthenticator";
IWAAuthenticatorStub stub = new IWAAuthenticatorStub(configContext, serviceEPR);
ServiceClient client = stub._getServiceClient();
client.engageModule("rampart");
Policy rampartConfig = IdentityBaseUtil.getDefaultRampartConfig();
Policy signOnly = IdentityBaseUtil.getSignOnlyPolicy();
Policy mergedPolicy = signOnly.merge(rampartConfig);
Options options = client.getOptions();
options.setProperty(RampartMessageData.KEY_RAMPART_POLICY, mergedPolicy);
options.setManageSession(true);
return stub;
}
/**
*
* @param request
* @return
* @throws AxisFault
*/
private AuthenticationAdminClient getAuthenticationAdminCient(HttpServletRequest request)
throws AxisFault {
HttpSession session = request.getSession();
ServletContext servletContext = session.getServletContext();
String backendServerURL = request.getParameter("backendURL");
if (backendServerURL == null) {
backendServerURL = CarbonUIUtil.getServerURL(servletContext, request.getSession());
}
session.setAttribute(CarbonConstants.SERVER_URL, backendServerURL);
ConfigurationContext configContext = (ConfigurationContext) servletContext
.getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
String cookie = (String) session.getAttribute(ServerConstants.ADMIN_SERVICE_AUTH_TOKEN);
return new AuthenticationAdminClient(configContext, backendServerURL, cookie, session, true);
}
/**
*
* @param backendServerURL
* @param session
* @return
* @throws AxisFault
*/
private LoggedUserInfoAdminStub getLoggedUserInfoAdminStub(String backendServerURL,
HttpSession session) throws AxisFault {
ServletContext servletContext = session.getServletContext();
ConfigurationContext configContext = (ConfigurationContext) servletContext
.getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
if (configContext == null) {
String msg = "Configuration context is null.";
log.error(msg);
throw new AxisFault(msg);
}
return new LoggedUserInfoAdminStub(configContext, backendServerURL + "LoggedUserInfoAdmin");
}
/**
*
* @param request
* @return
*/
private String getBackendUrl(HttpServletRequest request) {
HttpSession session = request.getSession();
ServletContext servletContext = session.getServletContext();
String backendServerURL = request.getParameter("backendURL");
if (backendServerURL == null) {
backendServerURL = CarbonUIUtil.getServerURL(servletContext, request.getSession());
}
if (backendServerURL != null) {
session.setAttribute(CarbonConstants.SERVER_URL, backendServerURL);
}
return backendServerURL;
}
@RequestMapping(value = "set_channel", method = RequestMethod.GET)
public @ResponseBody
ModelAndView setChannel(@RequestParam("use_channel")Integer channel, HttpSession session){
ServletContext context = session.getServletContext();
Map<String, Object> result = new HashMap();
result.put("msg", "success");
result.put("rst", 0);
result.put("data", channel);
context.setAttribute("use_channel", channel);
return new ModelAndView(new MappingJackson2JsonView(), result);
}
@Override
public void sessionCreated(HttpSessionEvent se) {
HttpSession session = se.getSession();
ServletContext context = session.getServletContext();
if (context.getAttribute("onlineCount") == null){
context.setAttribute("onlineCount", 1);
}else {
context.setAttribute("onlineCount", (Integer)context.getAttribute("onlineCount") + 1);
}
}
@Override
public void sessionDestroyed(HttpSessionEvent se) {
HttpSession session = se.getSession();
ServletContext context = session.getServletContext();
Integer subFlag = (Integer)session.getAttribute("sub_flag");
if(subFlag == null){
context.setAttribute("onlineCount", (Integer)context.getAttribute("onlineCount") - 1);
}
}
/**
* INTERNAL: Returns the plug-in class instance used by the ontopoly
* plugin. Used by classify/plugin.jsp.
*/
public static ClassifyPluginIF getPlugin(HttpServletRequest request) {
// create plugin by dynamically intantiating plugin class
HttpSession session = request.getSession(true);
ServletContext scontext = session.getServletContext();
String pclass = scontext.getInitParameter("classify_plugin");
if (pclass == null)
pclass = "net.ontopia.topicmaps.classify.DefaultPlugin";
ClassifyPluginIF cp = (ClassifyPluginIF)ObjectUtils.newInstance(pclass);
if (cp instanceof HttpServletRequestAwareIF)
((HttpServletRequestAwareIF)cp).setRequest(request);
return cp;
}
protected MultiSessionAttributeAdapter(HttpSession preferredSession, HttpSession localSession, HttpServletRequest request) {
this.preferredSession = preferredSession;
this.localSession = localSession;
ServletContext servletContext = request!=null ? request.getServletContext() :
localSession!=null ? localSession.getServletContext() :
preferredSession!=null ? preferredSession.getServletContext() :
null;
this.mgmt = servletContext != null ? new ManagementContextProvider(servletContext).getManagementContext() : null;
resetExpiration();
}
private HttpSession findPreferredSession(HttpSession localSession, HttpServletRequest optionalRequest) {
HttpSession preferredSession = findValidPreferredSession(localSession, optionalRequest);
//TODO just check this the first time preferred session is accessed on a given request (when it is looked up)
ManagementContext mgmt = null;
ServletContext servletContext = optionalRequest!=null ? optionalRequest.getServletContext() : localSession!=null ? localSession.getServletContext() : preferredSession!=null ? preferredSession.getServletContext() : null;
if(servletContext != null){
mgmt = new ManagementContextProvider(servletContext).getManagementContext();
}
boolean isValid = ((Session)preferredSession).isValid();
if (!isValid) {
throw new SessionExpiredException("Session invalidated", SessionErrors.SESSION_INVALIDATED, optionalRequest);
}
if(mgmt !=null){
Long maxSessionAge = mgmt.getConfig().getConfig(MAX_SESSION_AGE);
if (maxSessionAge!=null) {
if (isAgeExceeded(preferredSession, maxSessionAge)) {
invalidateAllSession(preferredSession, localSession);
throw new SessionExpiredException("Max session age exceeded", SessionErrors.SESSION_AGE_EXCEEDED, optionalRequest);
}
}
}
return preferredSession;
}
/**
* Invoke onSessionEnd() for any cfSessionData instance within the
* HttpSession.
*/
public static void onSessionEnd(HttpSession httpSession) {
ServletContext servletContext = httpSession.getServletContext();
boolean containsSessionId = false;
boolean containsUrlToken = false;
Enumeration<String> attrNames = httpSession.getAttributeNames();
while (attrNames.hasMoreElements()) {
String key = attrNames.nextElement();
if (key.equals("sessionid")) {
containsSessionId = true;
} else if (key.equals("urltoken")) {
containsUrlToken = true;
} else {
Object sessionAttr = httpSession.getAttribute(key);
if (sessionAttr instanceof cfSessionData) {
Object appAttr = servletContext.getAttribute(key);
if (appAttr instanceof cfApplicationData) {
((cfSessionData) sessionAttr).onSessionEnd((cfApplicationData) appAttr);
}
}
}
}
// check for unnamed cfJ2EESessionData
if (containsSessionId && containsUrlToken) {
cfSessionData session = new cfJ2EESessionData(httpSession);
session.onSessionEnd(new cfJ2EEApplicationData(servletContext));
}
}
/**
* Map of HttpSession Ids to FlexSessions. We need this when registered as a listener
* in web.xml in order to trigger the destruction of a FlexSession when its associated HttpSession
* is invalidated/destroyed. The Servlet spec prior to version 2.4 defined the session destruction event
* to be dispatched after attributes are unbound from the session so when we receive notification that
* an HttpSession is destroyed there's no way to get to the associated FlexSession attribute because it
* has already been unbound... Additionally, we need it to handle attribute removal events that happen
* during HttpSession destruction because the FlexSession can be unbound from the session before the
* other attributes we receive notification for.
*
* Because of this, it's simplest to just maintain this lookup table and use it for all HttpSession
* related event handling.
*
* The table is maintained on the servlet context instead of statically in order to prevent collisions
* across web-apps.
*/
private Map getHttpSessionToFlexSessionMap(HttpSession session)
{
try
{
ServletContext context = session.getServletContext();
Map map = (Map)context.getAttribute(SESSION_MAP);
if(map==null){
// map should never be null here as it is created during MessageBrokerServlet start-up
if (Log.isError())
Log.getLogger(FLEX_SESSION_LOG_CATEGORY).error("HttpSession to FlexSession map not created in message broker for "
+ session.getId());
MessageException me = new MessageException();
me.setMessage(10032, new Object[] {session.getId()});
throw me;
}
return map;
}
catch(Exception e)
{
if (Log.isDebug())
Log.getLogger(FLEX_SESSION_LOG_CATEGORY).debug("Unable to get HttpSession to FlexSession map for "
+ session.getId() + " " + e.toString());
return new ConcurrentHashMap();
}
}
@Override
public void unauthenticate(Object o) throws Exception {
HttpServletRequest request = (HttpServletRequest) o;
HttpSession session = request.getSession();
String username = (String) session.getAttribute(CarbonConstants.LOGGED_USER);
ServletContext servletContext = session.getServletContext();
ConfigurationContext configContext = (ConfigurationContext) servletContext
.getAttribute(CarbonConstants.CONFIGURATION_CONTEXT);
String backendServerURL = CarbonUIUtil.getServerURL(servletContext, session);
try {
String cookie = (String) session.getAttribute(ServerConstants.
ADMIN_SERVICE_AUTH_TOKEN);
OIDCAuthenticationClient authClient = new
OIDCAuthenticationClient(configContext, backendServerURL, cookie, session);
authClient.logout(session);
log.info(username + "@" + PrivilegedCarbonContext.getThreadLocalCarbonContext().
getTenantDomain() +" successfully logged out");
} catch (Exception ignored) {
String msg = "OIDC logout failed";
log.error(msg, ignored);
throw new Exception(msg, ignored);
}
String logoutUrl = Util.getIdentityProviderURI() + "logout";
request.setAttribute(OIDCConstants.HTTP_ATTR_IS_LOGOUT_REQ, true);
request.setAttribute(OIDCConstants.EXTERNAL_LOGOUT_PAGE, logoutUrl);
}
@Override
public Result login(LoginDTO dto, HttpSession session) throws Exception {
String psw =dto.getPassword();
String userName = dto.getUsername();
if(Tools.isEmpty(userName) || Tools.isEmpty(psw)){
throw new ApiException(ApiResultEnum.PARAMETER_NULL);
}
psw = SHA.encryptSHA(psw);
QueryWrapper<User> queryWrapper = new QueryWrapper();
queryWrapper.lambda().eq(User::getUsername,dto.getUsername()).eq(User::getPassword,psw);
User user = userService.getOne(queryWrapper);
if(user == null){
throw new ApiException(ApiResultEnum.ACCOUNT_NOT_FOUND);
}
if("lock".equalsIgnoreCase(user.getStatus())){
throw new ApiException(ApiResultEnum.ACCOUNT_LOCK);
}
//获取用户权限
Long userId = user.getUserId();
List<Role> roles =userRoleService.getUserRoles(userId);
long maxMenuId = menuService.getMaxId();
Role uRole = new Role(new BigInteger("0"),new BigInteger("0"),new BigInteger("0"),new BigInteger("0"),new BigInteger("0"));
checkUserRole(roles, uRole, maxMenuId);
System.out.println("==ROLE=="+JSON.toJSONString(uRole));
user.setRole(uRole);
//父级菜单
List<Menu> parentMenuList = menuService.getAllMenuList();
checkMenuRole(parentMenuList, uRole.getRights(),user.getUsername());
ServletContext servletContext = session.getServletContext();
Map<String,User> globalUser = (Map<String, User>) servletContext.getAttribute(Const.GLOBAL_SESSION);
if(globalUser == null){
globalUser = new HashMap<String, User>();
}else{
if(globalUser.containsKey(userName)){
globalUser.remove(userName);
}
}
user.setSessionId(session.getId());
user.setPassword("*****");
globalUser.put(userName, user);
session.setMaxInactiveInterval(0);
session.setAttribute(Const.SESSION_ALL_MENU, parentMenuList);
session.setAttribute(Const.SESSION_USER, user);
servletContext.setAttribute(Const.GLOBAL_SESSION, globalUser);
User updateUser = new User();
updateUser.setSessionId(session.getId());
updateUser.setUserId(userId);
userService.updateById(updateUser);
//保存登录日志
Login loginLog = new Login();
loginLog.setLastLoginTime(LocalDateTime.now());
loginLog.setUserId(userId);
this.save(loginLog);
return Result.ok();
}
public static ServletContext getServletContext() {
HttpSession session = getSession();
return session != null ? session.getServletContext() : null;
}
private void signUp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String name = (String) session.getAttribute("name");
String uname = (String) session.getAttribute("uname");
String pwd = (String) session.getAttribute("pwd");
String aite = request.getParameter("aite");
Timestamp utime = Times.getSystemTime();
int n = usersDao.addUser(uname, pwd, name, aite, utime);
if (n > 0) {
ServletContext application = session.getServletContext();
Integer zhuceNum = (Integer) application.getAttribute("zhuceNum");
if (zhuceNum == null) {
zhuceNum = 1;
} else {
zhuceNum += 1;
}
application.setAttribute("newTweetNum", zhuceNum);
Users user = usersDao.checkLogin(uname, pwd);
int m = usersinfoDao.addUserinfo(user.getUid());
if (m > 0) {
Usersinfo info = usersinfoDao.getInfos(user.getUid());
String folder = request.getSession().getServletContext().getRealPath("/img/" + user.getUname());
String img = request.getSession().getServletContext().getRealPath("/img");
File file = new File(folder);
file.mkdir();
InputStream is = new FileInputStream(img + "/" + info.getUlogo());
OutputStream os = new FileOutputStream(folder + "/" + info.getUlogo(), true);
byte[] b = new byte[1024];
int a = is.read(b); // 实际读到的文件的长度
while (a > 0) {
os.write(b, 0, a);
a = is.read(b);
}
os.close();
is.close();
session.setAttribute("info", info);
session.setAttribute("user", user);
response.sendRedirect("start.jsp");
}
}
}
public static String downloadDigitalProduct(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession();
ServletContext application = session.getServletContext();
Delegator delegator = (Delegator) request.getAttribute("delegator");
GenericValue userLogin = (GenericValue) session.getAttribute("userLogin");
String dataResourceId = request.getParameter("dataResourceId");
try {
// has the userLogin.partyId ordered a product with DIGITAL_DOWNLOAD content associated for the given dataResourceId?
GenericValue orderRoleAndProductContentInfo = EntityQuery.use(delegator).from("OrderRoleAndProductContentInfo")
.where("partyId", userLogin.get("partyId"),
"dataResourceId", dataResourceId,
"productContentTypeId", "DIGITAL_DOWNLOAD",
"statusId", "ITEM_COMPLETED")
.queryFirst();
if (orderRoleAndProductContentInfo == null) {
request.setAttribute("_ERROR_MESSAGE_", "No record of purchase for digital download found (dataResourceId=[" + dataResourceId + "]).");
return "error";
}
// TODO: check validity based on ProductContent fields: useCountLimit, useTime/useTimeUomId
if (orderRoleAndProductContentInfo.getString("mimeTypeId") != null) {
response.setContentType(orderRoleAndProductContentInfo.getString("mimeTypeId"));
}
OutputStream os = response.getOutputStream();
GenericValue dataResource = EntityQuery.use(delegator).from("DataResource").where("dataResourceId", dataResourceId).cache().queryOne();
Map<String, Object> resourceData = DataResourceWorker.getDataResourceStream(dataResource, "", application.getInitParameter("webSiteId"), UtilHttp.getLocale(request), application.getRealPath("/"), false);
os.write(IOUtils.toByteArray((InputStream) resourceData.get("stream")));
os.flush();
} catch (GeneralException | IOException e) {
String errMsg = "Error downloading digital product content: " + e.toString();
Debug.logError(e, errMsg, module);
request.setAttribute("_ERROR_MESSAGE_", errMsg);
return "error";
}
return "success";
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
HttpSession httpSession = httpSessionEvent.getSession();
ServletContext servletContext = httpSession.getServletContext();
File tempDir = (File) servletContext.getAttribute(ServletContext.TEMPDIR);
File attachmentDir = new File(tempDir, httpSession.getId());
if (attachmentDir.exists()) {
File[] files = attachmentDir.listFiles();
for (File file : files) {
file.delete();
logger.debug("Deleted file: " + file.getAbsolutePath());
}
}
}
@Override
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
HttpSession httpSession = httpSessionEvent.getSession();
ServletContext servletContext = httpSession.getServletContext();
File tempDir = (File) servletContext.getAttribute(ServletContext.TEMPDIR);
File attachmentDir = new File(tempDir, httpSession.getId());
if (attachmentDir.exists()) {
File[] files = attachmentDir.listFiles();
for (File file : files) {
file.delete();
logger.debug("Deleted file: " + file.getAbsolutePath());
}
}
}