Java 在 Struts 2 Web 应用程序中检查会话值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18609502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 09:29:47  来源:igfitidea点击:

Checking a session value in Struts 2 web application

javajspsessionauthenticationstruts2

提问by

I am creating a web application using Struts 2. I have a login page in it. As the user click the login button after entering the username and password, the credentials are checked and if the credentials are found correct, then a session is created and its attributes are set and control is redirected to WELCOME JSP.

我正在使用 Struts 2 创建一个 Web 应用程序。我在其中有一个登录页面。当用户在输入用户名和密码后单击登录按钮时,将检查凭据,如果凭据正确,则创建会话并设置其属性,并将控制重定向到 WELCOME JSP。

Now before the welcome.jspis opened, I want to check, if the session attributes are set. How to do it in Struts 2?

现在在welcome.jsp打开之前,我想检查是否设置了会话属性。如何在 Struts 2 中做到这一点?

Can anyone clear me the concept of interceptors. I read that we create interceptors to perform any function before or after an action is called. Can I create an interceptor that checks if the session is set, every time before WELCOME JSP is called.

任何人都可以让我清楚拦截器的概念。我读到我们创建了拦截器来在调用操作之前或之后执行任何功能。我可以创建一个拦截器来检查会话是否设置,每次在调用 WELCOME JSP 之前。

采纳答案by Pratik Shah

@rickgaurav for your 1st question. make a login action like this

@rickgaurav 对于您的第一个问题。进行这样的登录操作

<action name="login_action" class="loginAction class">
            <result name="success" type="chain">welcomeAction</result>
            <result name="input">/index.jsp</result>
            <result name="error">/index.jsp</result>
        </action>

wher index.jsp is your login page

index.jsp 是您的登录页面

and in login interceptor first make a session map in which your session attribute will be store

并在登录拦截器中首先制作一个会话映射,您的会话属性将存储在其中

Map<String, Object> sessionAttributes = invocation
            .getInvocationContext().getSession();

after that check using this condition

在使用此条件进行检查之后

if (sessionAttributes == null
                || sessionAttributes.get("userName") == null
                || sessionAttributes.get("userName").equals("")) {

            return "login";
        }else{
if (!((String) sessionAttributes.get("userName")).equals(null)){
return invocation.invoke();
}else{
return "login";
}

for your 2nd question assume you are calling a welcomeAction to go to the welcome.jsp page so you can add action like this

对于您的第二个问题,假设您正在调用welcomeAction 以转到welcome.jsp 页面,以便您可以添加这样的操作

<action name="welcomeAction" class="class">
        <interceptor-ref name="logininterceptor"></interceptor-ref>




            <result name="login" type="chain">loginaction</result>
        <result name="success" >/welcome.jsp</result>

    </action>

hope so this will work for you

希望这对你有用

回答by Umesh Awasthi

you can use <s:if>tag to test presence of your attribute in Session.I am assuming that you are setting value in your action class and here is how you can do that in jsp page

你可以使用<s:if>标签来测试你的属性在 Session 中的存在。我假设你在你的动作类中设置值,这里是你如何在 jsp 页面中做到这一点

<s:if test="%{#session.logged_in ==true}">

I am assuming that here i am setting a flag indicating if user is logged in or not on similar way you can test as per your requirements

我假设在这里我设置了一个标志,指示用户是否以类似的方式登录,您可以根据您的要求进行测试

For Interceptors, They are set of utility classes being provided by Struts2 out of the box to make your life easy.Interceptors are just java classes with certain functionality which is being provide by the framework, some of them are

对于拦截器,它们是 Struts2 开箱即用的一组实用程序类,使您的生活更轻松。拦截器只是具有框架提供的某些功能的 Java 类,其中一些是

  1. fileUpload
  2. i18n
  3. params
  4. token etc
  1. 上传文件
  2. 国际化
  3. 参数
  4. 令牌等

These Interceptors are called based on the interceptor stack being configured in your application and they will be called at 2 places

这些拦截器是根据在您的应用程序中配置的拦截器堆栈调用的,它们将在 2 个地方被调用

  1. when you send request to your action
  2. when request processing done and view rendered.
  1. 当您向您的操作发送请求时
  2. 当请求处理完成并呈现视图时。

in first case they will be called before your action execute or custom method defined by you is called, Interceptors are responsible to provide required data to your action class, some of the work done by interceptors before your action called are

在第一种情况下,它们将在您的操作执行或您定义的自定义方法被调用之前被调用,拦截器负责向您的操作类提供所需的数据,在您的操作调用之前拦截器完成的一些工作是

  1. File uploading
  2. Handling i18n
  3. Passing form values to respected fields in your action class
  4. validation of your data
  1. 文件上传
  2. 处理 i18n
  3. 将表单值传递给操作类中的受尊重字段
  4. 验证您的数据

there are certain set of interceptors being provided by struts2 , you can have look at struts-defaultxml.

struts2 提供了某些拦截器,您可以查看struts-defaultxml

You can create any number of interceptors and configure them to be executed as per your requirements,a ll you need to extends AbstractInterceptoran provide your custom logic inside intercept(ActionInvocation invocation)method I suggest you to follow below mentioned links to get more overview

您可以创建任意数量的拦截器并将它们配置为根据您的要求执行,您需要扩展AbstractInterceptor并在intercept(ActionInvocation invocation)方法中提供您的自定义逻辑我建议您按照下面提到的链接获取更多概述

building-your-own-interceptorStruts2 Interceptorswriting-interceptors

构建你自己的拦截器Struts2 拦截器编写拦截器

回答by Pratik Shah

Yes you can use interceptor. Make a Action class Which will store UserId / Username of user (after user is authenticated) in session like this.

是的,您可以使用拦截器。创建一个 Action 类,它将像这样在会话中存储用户的 UserId / Username(在用户通过身份验证后)。

session.put("userID", userlogin.getUserId());

after that make a Interceptor class which impl. interceptor

之后创建一个拦截器类。拦截器

public class LoginInterceptor implements **Interceptor** {  

public String intercept(ActionInvocation invocation) throws Exception {

get the session attribute using

使用获取会话属性

sessionAttributes.get("userId");

and check it is not null if it is null then return login to forward user to the login page or else return invocation.invoke(); to continue the action.

并检查它是否为空,如果为空则返回登录以将用户转发到登录页面,否则返回 invocation.invoke(); 继续行动。

and in struts.xml file configure interceptor inside package

并在 struts.xml 文件中配置包内的拦截器

<interceptors>
            <interceptor name="loginInterceptor" class=".....LoginInterceptor"></interceptor>
            <interceptor-stack name="loginStack">
                <interceptor-ref name="loginInterceptor"></interceptor-ref>
                <interceptor-ref name="defaultStack"></interceptor-ref>
            </interceptor-stack>
        </interceptors>

and for action you can write

对于行动,你可以写

<action name="anything" class="anyclass" method="default">
            <interceptor-ref name="loginStack"></interceptor-ref>

    <result name="login">/index.jsp</result>

            <result name="success" type="redirect">success.jsp</result>

    </action>

回答by Jay Trivedi

  1. In Struts.xml write this:

    <interceptors> <interceptor name="loginInterceptor" class="com.mtdc.interceptor.LoginInterceptor"></interceptor> <interceptor-stack name="loginStack"> <interceptor-ref name="loginInterceptor"></interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors>

  1. 在 Struts.xml 中这样写:

    <interceptors> <interceptor name="loginInterceptor" class="com.mtdc.interceptor.LoginInterceptor"></interceptor> <interceptor-stack name="loginStack"> <interceptor-ref name="loginInterceptor"></interceptor-ref> <interceptor-ref name="defaultStack"></interceptor-ref> </interceptor-stack> </interceptors>

2.Now After aAction which you want to check session put this: <interceptor-ref name="loginStack"></interceptor-ref>

2.Now After aAction which you want to check session put this: <interceptor-ref name="loginStack"></interceptor-ref>

3.Our LoginACtion in struts.xml: `

3.我们在struts.xml中的LoginACtion:`

<action name="login_action" class="com.action.LoginAction">

      <result name="success">/welcome.jsp</result>
      <result name="input">/login.jsp</result>
      <result name="error">/login.jsp</result> 

  </action>

`

`

4.Now define LOgin interceptor for that make com,interceptor.LoginInterceptor :

4.现在为那个make com,interceptor.LoginInterceptor定义登录拦截器:

`

    public String intercept(ActionInvocation invocation) throws Exception {

            Map<String, Object> sessionAttributes = invocation
                    .getInvocationContext().getSession();
            if (sessionAttributes == null
                    || sessionAttributes.get("userName") == null
                    || sessionAttributes.get("userName").equals("")) {

                return "login";
            } else {

                if (!((String) sessionAttributes.get("userName")).equals(null)
                        || !((String) sessionAttributes.get("userName")).equals("")) {

                    return invocation.invoke();
                } else {

                    return "login";
                }
            }
        }

`

[5]. Now make Login Action class where you assign session:

[5]。现在在您分配会话的地方创建登录操作类:

` 

    public String execute() {

        String result = LOGIN;
        UserLogin userlogin;
        try {
            userlogin = userlogindao.authenticateUser(signin_username, signin_password);
            if (userlogin != null && userlogin.getUsername() != null) {

            session.put("userID", userlogin.getUserId());
            session.put("userName", userlogin.getUsername());


            result = SUCCESS;
            } else {

            result = LOGIN;
            }
        } catch (Exception e) {
            result = LOGIN;


            e.printStackTrace();
        }
        return result;
        }

`

[6]. Now final step on your login page on click call action LoginAction.

[6]。现在在您的登录页面上点击调用操作 LoginAction 的最后一步。