struts2 会话维护 [英] struts2 Session maintaining

查看:55
本文介绍了struts2 会话维护的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 struts 2 MVC 框架开发 Web 应用程序.我目前正在研究它的登录模块.我是这些技术的新手.我在维护会话时遇到问题.我希望如果有人直接点击个人资料页面的 url(成功登录时打开的页面),那么他或她会被重定向回登录页面.此外,如果有人使用错误的凭据登录,那么他将再次被重定向回登录页面.此外,如果他输入了一些登录详细信息,则必须首先检查凭据,如果凭据正确,则必须设置会话变量.在呈现配置文件页面之前,如果设置了会话变量,则会检查它们.如果仅设置了会话变量,则控制将传递到配置文件页面.

I am developing a web application using struts 2 MVC framework. I am currently working on login module of it. I am new to these technologies. I am facing problems in maintaining sessions. I want that if some one directly hits the url of the profile page(page that is opened on successful login), then he or she is redirected back to the login page. Also if someone login with wrong credentials then again he is redirected back to login page. Also if he enters some login details, then first the credentials must be checked and if credentials r correct, then he session variables must be set. And before profile page is rendered, session variables are checked if they r set. If only the session variables are set, the control passes to the profile page.

以下是我的登录表单代码 loginPage.jsp:此页面向用户显示登录页面:

Below is my Login form code loginPage.jsp: This page displays the loginpage to the user:

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>LOGIN PAGE</title>
</head>
<body>
  <s:form action="login" method="post">
    <s:textfield name="login.username" label="Username"/>
    <s:password name="login.password" label="Password"/>
    <s:submit value="SUBMIT" align="center"/>
    <s:reset value="RESET" align="center"/>
  </s:form>
</body>
</html>

现在是我的 loginAction 类:这是我的操作类,对应于在登录表单上单击登录按钮时产生的登录操作.

now is my loginAction class: This is my action class corresponding to login action that is produced when the login button is clicked on the login form.

package com.view;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
import com.controller.LoginManager;
import com.model.Login;
import com.model.UserDetails;
public class LoginAction implements SessionAware{
    private Login login;
    private LoginManager loginManager;
    private UserDetails userDetails;
    Map<String,Object> map;
    public LoginAction()
    {
        loginManager=new LoginManager();
    }
    public String loginLink()
    {
        return "loginClicked";
    }
    public String checkLogin()
    {
       try
       {
        //String loggedInUsername=null;
        System.out.println("---------"+login.getUsername());

        /*if(map.containsKey("username"))
        {
            loggedInUsername=(String)map.get("username");
        }*/
        userDetails=loginManager.check(login);
        /*if(loggedInUsername!=null && loggedInUsername==userDetails.getUsername())
        {
            return "loginSuccess";
        }*/
        if(userDetails!=null && userDetails.getUsername()!=null)
        {
            map.put("login",true);
            map.put("username",userDetails.getUsername());
            map.put("name",userDetails.getName());
            map.put("sex",userDetails.getSex());
            map.put("email",userDetails.getEmail());
            map.put("phoneno",userDetails.getPhone_no());
            System.out.println("Inside session map creation that is Successful login");
            return "loginSuccess"; 
        }
        else
        {
            System.out.println("Inside check login with invalid credentials");
            return "loginClicked";
        }
       }catch(Exception ex)
       {
           System.out.println("Inside exception of checkLogin.");
           return "loginClicked";
       }
    }
    public void setLogin(Login login)
    {
        this.login=login;
    }
    public Login getLogin()
    {
        return login;
    }
    @Override
    public void setSession(Map<String, Object> map) {
        this.map=map;
    }
}

loginManager 类:该类处理数据库部分.在此类中检查登录凭据.

loginManager class: This class handles the database part. Login credentials are checked in this class.

package com.controller;
import org.hibernate.Query;
import org.hibernate.classic.Session;
//import java.util.List;
import com.model.Login;
import com.model.UserDetails;
import com.util.HibernateUtil;
public class LoginManager extends HibernateUtil{

        UserDetails userDetails;
        public UserDetails check(Login login)
        {
          Session session = HibernateUtil.getSessionFactory().getCurrentSession();
          session.beginTransaction();
          try
          {
            System.out.println("Inside try block to retrieve from db");
            String hql="FROM UserDetails where username='"+login.getUsername()+"' and password='"+login.getPassword()+"' and role='U'";
            Query query = session.createQuery(hql);
            System.out.println("Query Created");
            userDetails=(UserDetails)query.uniqueResult();
            //System.out.println("Returned Username"+userDetails.getUsername());
            //System.out.println("Returned Password"+userDetails.getPassword());
            session.getTransaction().commit();
          }catch(Exception ex){
              System.out.println("Exception generated is "+ex.getMessage());
              session.getTransaction().rollback();
              userDetails=null;
              ex.printStackTrace();
          }
          return userDetails;
        }
}

下面是我的 struts.xml 文件:

Below is my struts.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
   "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
   "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <constant name="struts.devMode" value="true" />
    <package name="package2" extends="struts-default">

        <interceptors>
         <interceptor name="myinterceptor" class="interceptors.LoginInterceptor" />
         <interceptor-stack name="myinterceptorSt">
            <interceptor-ref name="myinterceptor" />
            <interceptor-ref name="defaultStack" />
        </interceptor-stack>
        </interceptors>



        <action name="registerLink" class="com.view.RegisterAction" method="registerLink">
            <result name="registerLinkClicked">/registerPage1.jsp</result>
        </action>

        <action name="register" class="com.view.RegisterAction" method="addUser">
            <result name="registered">/registrationSuccess.jsp</result>
        </action>

        <action name="login" class="com.view.LoginAction" method="checkLogin">
            <interceptor-ref name="myinterceptorSt" /> 
            <result name="loginSuccess" type="redirect">/profile.jsp</result>
            <result name="loginFail">/loginFail.jsp</result>
            <result name="loginClicked">/loginPage.jsp</result>
        </action>

        <action name="sessionCheck" class="com.view.SessionCheckAction">
            <result name="sessionCheckSuccess"></result>
        </action>

        <action name="loginLink" class="com.view.LoginAction" method="loginLink">
            <result name="loginClicked">/loginPage.jsp</result>
        </action>

    </package>
</struts>

任何人都可以帮助我编写拦截器代码以实现我上面指定的功能.

Can anyone please help me with the interceptor code that should be written in order to implement the functionality specified by me above.

推荐答案

我阅读了评论,正如 Dave Newton 提到的,这是拦截器代码:

I read comments and as Dave Newton mentioned, this is interceptor code:

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

    String username = (String) session.get("username");//getting username from session

    // If the user is already logged-in, then let the request through.
    if (username != null) {
        return invocation.invoke();
    }

    Object action = invocation.getAction();  // get which action class is called

    // for the first action LoginAction interceptor will allow request to be forwarded.
    if (action instanceof LoginAction) {
        return invocation.invoke();
    }
    else {
        return "notAuthorized";
    }
 }
}  

现在,在 <interceptors></interceptors>

<global-results>
    <result name="notAuthorized">/loginPage.jsp</result>
</global-results>  

此答案基于您的代码.我提到了这个最好的帖子
以下是一些可能对您有所帮助的链接

This answer is based upon your code. I referred this best post
Here are few links which may help you

  1. 会话拦截器
  2. 包配置
  3. 拦截器
  4. 拦截器堆栈示例
    谢谢.

这篇关于struts2 会话维护的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆