spring中获得sesion的工具类

4 篇文章 0 订阅

开发中我们常常会用到session,但是传统的获取session的方法不是很灵活。。。

直接贴上源码:

package com.ibs.gbplatform.common.util;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

public class SessionUtils {

	public static Object getSessionAttribute(String key) {
		return ((ServletRequestAttributes) RequestContextHolder
				.getRequestAttributes()).getRequest().getSession()
				.getAttribute(key);
	}

	public static void setSessionAttribute(String key, Object object) {
		((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest().getSession().setAttribute(key, object);
	}
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
对于连接Linux的工具类,我们可以使用JSch库。下面是一个连接Linux服务器并执行命令的示例代码: ``` public class SSHUtil { private String host; private String username; private String password; private JSch jsch; private Session session; public SSHUtil(String host, String username, String password) { this.host = host; this.username = username; this.password = password; jsch = new JSch(); } public void connect() throws JSchException { session = jsch.getSession(username, host, 22); session.setPassword(password); session.setConfig("StrictHostKeyChecking", "no"); session.connect(); } public void disconnect() { if (session != null) { session.disconnect(); } } public String executeCommand(String command) throws JSchException, IOException { ChannelExec channelExec = (ChannelExec) session.openChannel("exec"); InputStream in = channelExec.getInputStream(); channelExec.setCommand(command); channelExec.connect(); StringBuilder result = new StringBuilder(); byte[] buffer = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(buffer, 0, 1024); if (i < 0) { break; } result.append(new String(buffer, 0, i)); } if (channelExec.isClosed()) { if (in.available() > 0) { continue; } result.append("exit-status: ").append(channelExec.getExitStatus()); break; } try { Thread.sleep(1000); } catch (InterruptedException ignore) { } } channelExec.disconnect(); return result.toString(); } } ``` 你可以通过创建SSHUtil对象,传入服务器地址、用户名和密码来连接Linux服务器,并执行需要的命令。例如,下面是在Linux上执行ls命令的示例代码: ``` public static void main(String[] args) throws JSchException, IOException { SSHUtil ssh = new SSHUtil("192.168.0.1", "root", "password"); ssh.connect(); String result = ssh.executeCommand("ls"); System.out.println(result); ssh.disconnect(); } ``` 希望这个例子对你有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

时间辜负了谁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值