如何在 Java 中创建 session

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在 Java 中创建 session相关的知识,希望对你有一定的参考价值。

1、 HttpSession session = ServletActionContext.getRequest().getSession(); //创建
2、 ActionContext.getContext().getSession().put("msg", "Hello World from Session!"); //存
session.setAttribute("softtypeid", softtypeid); //存
获取 if(session.getAttribute("softtypeid")!=null)
if(!softtypeid.equals(session.getAttribute("softtypeid")))
pager_offset=1; //如果不是同一种分类,返回是第一页

3、
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();

HttpSession session = request.getSession(); //创建
参考技术A session的作用域是你(浏览器)和服务器之间存在的连接,也就是说浏览器不关闭session就一直存在并且不会自动清空.所以你在任何地方set,在没有改变的情况下,在任何地方也可以get出来

如何在Controller中创建不可变的BusinessLayer而不更改其属性?

我有BusinessLayer,它包含旧桌面应用程序中的集合和可重用代码。

现在我想在MVC应用程序中再次使用此层。我尝试在Controller中使用图层,例如Index()

public ActionResult Index()
{
    if (Session["DataEntryLogic"] == null)
        Session["DataEntryLogic"] = new DataEntryLogic();

    var EntryLogic = Session["DataEntryLogic"] as DataEntryLogic;

    EntryLogic.Tables.Add(new Table());
    EntryLogic.Tables[0].TableID = "AccTransHed";
    EntryLogic.Tables[0].TableType = TableType.Master;
}

现在我想保留我在第一个View加载中添加的表。并使其在下一个回发中不可变。我用了Session。我不知道是否应该使用ViewBag或ViewData。

简而言之:我应该遵循哪种模式来制作不可变的BusinessLayer?

因为每次发生回发事件都不需要一次又一次地获取表信息或密钥或逻辑本身。

更新时间为2019/04/14

我应该将整个BusinessLogic属性和集合替换为此模式吗?

在Windows应用程序中:

pulic class EntryLogic{
   public List<Table> Tables{get;set;}
}

到MVC应用程序:

public class EntryLogic{
  public List<Table> Tables{
    get{
           if(Session["Tables"] == null)
              Session["Tables"] = new List<Table>();
           return Session["Tables"] as List<Table>;
      }
    set { Session["Tables"] = value;}
  }
}

或者只是在会话变量中初始化桌面应用程序的EntryLogic实例?

var EntryLogic = Session["EntryLogic"] as EntryLogic;
答案

对我来说,听起来你可以使用缓存来减少对数据库的调用,而不用担心保留状态。

另一答案

首先,我不认为你想在索引上使用图层但是在app start上。此外,如果您要使用Session,这意味着每个用户将拥有一组不同的表。

归结为:

  • 每个用户的集合是否相同?如果是,那么你想在app start中初始化它们
  • 具有静态变量也是一样的。通过使用静态变量,它将在所有操作和用户之间共享。
  • 如果每个用户都有一组不同的表和键,并且它们是不同的,则可以使用“会话”来存储您想要的任何变量。

也:

  • ViewBag和ViewData是相同的。你可以使用其中之一。

这是你带集合的静态类

enter image description here

这是您初始化和填充集合的位置

enter image description here

这就是你如何将你的收藏品用于控制器。

enter image description here

以上是关于如何在 Java 中创建 session的主要内容,如果未能解决你的问题,请参考以下文章