struts2应用程序中的会话

发布于 2024-10-29 03:21:00 字数 985 浏览 1 评论 0原文

我创建了一个网络应用程序,我需要在其中维护会话 如果存在用户会话,那么也只有这样,它才会允许用户看到该 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");
    }

%>

我在某处读到,操作类会话的范围仅限于一页 - 我该如何解决这个问题?

任何例子都会对我很有帮助。

I have created a web application in which I need to maintain the session
if a user session is there, and then and only then will it allow the user to see the jsp.

I have worked with jsp servlets before, but I'm new to struts2.

Here I am setting username in my action class:

Revised Code

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;
}

Now, when I am redirected to next page after an action, it shows the session value once. After that, on every page, I am finding null values in session.

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

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

%>

I read somewhere that the scope of an action class session is limited to one page - how could I solve this problem?

Any example will be very helpful to me.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

夜雨飘雪 2024-11-05 03:21:00

您当前的代码存在一些问题。

  • 您应该使用拦截器强制用户登录,而不是尝试在 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>

There are a few problems with the code you currently have.

  • You should use an Interceptor to enforce that the user is logged in, rather than trying to enforce it in the JSP. JSP should only be for presentation, not for flow control.
  • You should avoid scriptlets (blocks of code) in JSP. That was deprecated a really long time ago and is widely considered to be a very poor practice in an MVC application.
  • You can access session values in your JSP directly. You do not need to implement the SessionAware interface in your action unless you need access to the session inside of the action itself.
  • You should redirect the user to a login action, not directly to a JSP page, otherwise you are bypassing the Struts2 framework and losing out on the benefits of using the framework.

Login Example

Below is some example code for creating a basic login system using the Struts2 framework.

Login Required

This part is optional, but in general, not all pages in a web application will require the user to be logged in. Therefore, let's create an interface called LoginRequired. Any action that implements this marker interface will redirect to the login page if the user is not already logged in.

Note: You can use an annotation instead, if you prefer, but for this example I will use the interface.

public interface LoginRequired {}

The Interceptor

The interceptor will handle forcing the user to login for any requested action which implements the LoginRequired interface.

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();
    }
}

You will also need a LoginAction which displays and processes the login page and a LogoutAction which invalidates or clears the session.

The Configuration

You will need to add the interceptor to your stack and also create a global result mapping for "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>
幸福%小乖 2024-11-05 03:21:00

要维护会话,请在操作类中使用 SessionAware 接口并实现 int
public void setSession(Map m) 它将把属性作为map中的键值对
可以从任何地方访问,只需购买并检索密钥即可。

例如 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/

To maintain a session use SessionAware interface in your action class and implement int
public void setSession(Map m) it will take the attribute as a key value pair in map
which can be be access from any where just buy retrieving the key.

for example Action class

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;
    }

}

SOURCE: http://www.java4s.com/struts-tutorials/example-on-struts-2-sessionaware-interface/

国际总奸 2024-11-05 03:21:00

我发现没有理由使用这种 Map 来授权用户。如果您的要求只是针对会话验证用户,那么我建议使用 Filter 而不是某些类中的某些映射,这种映射的问题是一旦会话失效,就删除会话对象,当然,您可以使用 HttpSessionListener 来使其工作,但我想最好通过 Filter 进行验证,而不是通过 Map 进行验证。

除此之外,您还可以查看许多安全框架(例如 Apache Shiro),以使您的任务更简单、更高效强壮的。

I find no reason to use this kind of Map to authorize user. If your requirement is only validate the user against session then I would recommend to use Filter than some map in some class, the problem with this kind of map is to remove the session objects once session is invalidated, of course you can use HttpSessionListener to make it work but I guess it's best to validate via Filter than Map.

Apart from it you can take a look at many security framework (like Apache Shiro) to make your task simpler and more robust.

不打扰别人 2024-11-05 03:21:00

您的 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 代码获取页面上的用户名。我已经在我的机器上测试了这种方法并且它有效。

编辑2:
顺便说一句,这样的登录检查可以通过 Struts2 框架提供的“Interceptor”轻松而优雅地完成。

Has your Action class already implemented the SessionAware interface?

EDIT:

Try this(It's a struts2 style solution):

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;
    }
}

Then use your jsp code to get the userName on page. I've tested this approach on my machine and it works.

EDIT2:
BTW, such login check can be done easily and elegant with "Interceptor" provided by Struts2 Framework.

韶华倾负 2024-11-05 03:21:00

不需要 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();
   }
} 

SessionAware implemention not required.

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();
   }
} 
暮凉 2024-11-05 03:21:00

下面的journaldev文章在上面史蒂文回复的同一行中提供了更多详细信息 http://www.journaldev.com/2210/struts-2-interceptor-tutorial-with-custom-authentication-interceptor-example

Following journaldev article has more detail in the same line of Steven response above http://www.journaldev.com/2210/struts-2-interceptor-tutorial-with-custom-authentication-interceptor-example

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文