簡體   English   中英

struts2應用程序中的會話

[英]Sessions in struts2 application

我創建了一個Web應用程序,如果有用戶會話,我需要維護會話 ,然后只有這樣才能讓用戶看到jsp。

我之前使用過jsp servlet,但我是struts2的新手。

這里我在我的動作類中設置用戶名

修訂后的守則

private HttpSession session;

public void setSession(HttpSession session) {
    // TODO Auto-generated method stub0
    this.session = session;
}

public HttpSession getSession() {
    return session;
}

public String getLoginStatus(){     
    session = request.getSession();
    session.setAttribute("userName", loginBean.getUsername());
    return SUCCESS;
}

現在,當我在操作后重定向到下一頁時,它會顯示一次會話值。 之后,在每個頁面上,我在會話中找到空值。

<%
    String userName = (String)session.getAttribute("userName");             
    System.out.println(userName);                        

    if(userName == null || userName.equals("") ){
        response.sendRedirect("login.jsp");
    }

%>

我在某處讀到動作類會話的范圍僅限於一頁 - 我該如何解決這個問題?

任何例子都對我很有幫助。

您目前擁有的代碼存在一些問題。

  • 您應該使用Interceptor強制用戶登錄,而不是嘗試在JSP中強制執行它。 JSP應僅用於表示,而不用於流控制。
  • 您應該避免在JSP中使用scriptlet(代碼塊)。 很久以前就被棄用了,並且在MVC應用程序中被廣泛認為是一種非常糟糕的做法。
  • 您可以直接訪問JSP中的會話值。 除非需要訪問操作本身內部的會話,否則不需要在操作中實現SessionAware接口。
  • 您應該將用戶重定向到登錄操作,而不是直接重定向到JSP頁面,否則您將繞過Struts2框架並失去使用框架的好處。

登錄示例

下面是使用Struts2框架創建基本登錄系統的一些示例代碼。

要求登錄

這部分是可選的,但一般而言,Web應用程序中的所有頁面都不需要用戶登錄。因此,讓我們創建一個名為LoginRequired的界面。 如果用戶尚未登錄,則實現此標記接口的任何操作都將重定向到登錄頁面。

注意:如果您願意,可以使用注釋,但是對於此示例,我將使用該界面。

public interface LoginRequired {}

攔截器

攔截器將處理強制用戶登錄任何實現LoginRequired接口的請求操作。

public class LoginInterceptor extends AbstractInterceptor {
    @Override
    public String intercept(final ActionInvocation invocation) throws Exception {
        Map<String, Object> session = ActionContext.getContext().getSession();

        // sb: feel free to change this to some other type of an object which
        // represents that the user is logged in. for this example, I am using
        // an integer which would probably represent a primary key that I would
        // look the user up by with Hibernate or some other mechanism.
        Integer userId = (Integer) session.get("userId");

        // sb: if the user is already signed-in, then let the request through.
        if (userId != null) {
            return invocation.invoke();
        }

        Object action = invocation.getAction();

        // sb: if the action doesn't require sign-in, then let it through.
        if (!(action instanceof LoginRequired)) {
            return invocation.invoke();
        }

        // sb: if this request does require login and the current action is
        // not the login action, then redirect the user
        if (!(action instanceof LoginAction)) {
            return "loginRedirect";
        }

        // sb: they either requested the login page or are submitting their
        // login now, let it through
        return invocation.invoke();
    }
}

您還需要一個LoginAction ,顯示和處理登錄頁面和LogoutAction其無效或清除會話。

配置

您需要將攔截器添加到堆棧中,並為“loginRedirect”創建全局結果映射。

<interceptors>
    <interceptor name="login" class="your.package.LoginInterceptor"/>

    <!-- sb: you need to configure all of your interceptors here. i'm only
         listing the one we created for this example. -->
    <interceptor-stack name="yourStack">
        ...
        <interceptor-ref name="login"/>
        ...
    </interceptor-stack>
</interceptors>

<global-results>
    <!-- sb: make this the path to your login action.
         this could also be a redirectAction type. -->
    <result name="loginRedirect" type="redirect">/login</url>
</global-results>

要維護會話,請在您的操作類中使用SessionAware接口並實現int public void setSession(Map m) ,它將把該屬性作為映射中的鍵值對,可以從任何只需購買檢索鍵的位置進行訪問。

例如Action類

import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

public class LogingEx extends ActionSupport implements SessionAware{
    private static final long serialVersionUID = 1L;

    private String stuname,stuage,country;
    private int stumarks;
    Map m;

    public String getStuname() {
        return stuname;
    }
    public void setStuname(String stuname) {
        this.stuname = stuname;
    }

    public String getStuage() {
        return stuage;
    }
    public void setStuage(String stuage) {
        this.stuage = stuage;
    }

    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }

    public int getStumarks() {
        return stumarks;
    }
    public void setStumarks(int stumarks) {
        this.stumarks = stumarks;
    }

    public void setSession(Map m)
    {
        this.m=m;
    }

    public String execute()
    {
        m.put("a",stuname);
        m.put("b", stuage);
        m.put("c",stumarks);
        m.put("d",country);

        return SUCCESS;
    }

}

消息來源: http//www.java4s.com/struts-tutorials/example-on-struts-2-sessionaware-interface/

我沒有理由使用這種Map來授權用戶。 如果你的要求只是針對會話驗證用戶,那么我建議使用Filter不是某些類中的某個map,這種映射的問題是在會話失效后刪除會話對象,當然你可以使用HttpSessionListener來制作它工作,但我想最好通過Filter不是Map進行驗證。

除此之外,您還可以查看許多安全框架(如Apache Shiro ),以使您的任務更簡單,更健壯。

您的Action類是否已實現SessionAware接口?

編輯:

試試這個(這是一個struts2風格的解決方案):

public class anAction implements SessionAware{
    private Map<String, Object> session;
    public Map<String, Object> getSession() {
         return session;
    }
    public void setSession(Map<String, Object> session) {
         this.session = session;
    }
    public String getLoginStatus(){
         session.put("userName", "test");  //Hard code here for testing.
         return SUCCESS;
    }
}

然后使用您的jsp代碼在頁面上獲取userName。 我已經在我的機器上測試了這種方法並且它有效。

EDIT2:BTW,這種登錄檢查可以通過Struts2 Framework提供的“Interceptor”輕松優雅地完成。

SessionAware實現不是必需的。

public class LoginAction extends Actionsupport
{
  private Map<String, Object> session;
  //Getter and Setter method
   public String execute() throws Exception {
      session=ActionContext.getContext().getSession();
      session.put("userName", "test");
     return super.execute();
   }
} 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM