简体   繁体   English

如果有人未登录struts2,如何防止任何页面加载

[英]how to prevent any page getting loaded if person not logged in struts2

I have been googling from week now. 我从一周开始一直在谷歌搜索。 Still have not got any solution which resolves my problem. 仍然没有任何解决我问题的解决方案。 My strtus2 web application is simple. 我的strtus2 Web应用程序很简单。 There is a login page once the login is successful then it has to redirect to the success page. 登录成功后会有一个登录页面,然后必须重定向到成功页面。 But my problem is if i right click on the success.jsp and run that page, still that page is loading without any session but my requirement is success.jsp should never get loaded rather it should redirect to the login.jsp page. 但是我的问题是,如果我右键单击success.jsp并运行该页面,该页面仍在加载而没有任何会话,但是我的要求是success.jsp永远不要加载,而应该重定向到login.jsp页面。

login.jsp: login.jsp的:

<%@ 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 uri="/struts-tags" prefix="s"%> 
<s:form action="login"> 
<s:textfield name="username" label="User Name"/> 
<s:password name="password" label="Password"/> 
<s:submit value="Login"/> 
</body>
</html>

my pojo class for Login. 我的用于登录的pojo类。

package com.cm.ccb.login;

public class Login {
private int userid;
private String username;
private double password;
private String email;
private double phone;
public int getUserid() {
return userid;
}
public void setUserid(int userid) {
this.userid = userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public double getPassword() {
return password;
}
public void setPassword(double password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public double getPhone() {
return phone;}
public void setPhone(double phone) {
this.phone = phone;
}
}

My loginAction class. 我的loginAction类。

package com.cm.ccb.login;

import java.util.Map;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport  implements SessionAware { 
private static final long serialVersionUID = 1L; 
private String username; 
private String password;
Map<String, Object> session;

SessionMap<String,String> sessionmap;  
LoginDao dao=new LoginDao(); 
@Override
public void validate(){ 
if(username.length()==(0)) 
this.addFieldError("username", "Name is required"); 
if(password.length()==(0)) 
this.addFieldError("password", "Password is required"); 
} 
@Override
public String execute(){

if(dao.find(getUsername(),getPassword())) {
return "success";

}
else

return "error"; 
} 

public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() { 
return password; 
} 
public void setPassword(String password) { 
this.password = password; 
}
public void setSession(Map<String, Object> session) {
this.session = session;

} }

} }

My loginDao class 我的登录课程

package com.cm.ccb.login;
import java.util.Iterator;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.cm.ccb.mapping.HibernateUtil;

public class LoginDao { 

@SuppressWarnings("unchecked") 
public boolean find(String username, String password) { 
Session session = HibernateUtil.getSessionFactory().openSession(); 

String SQL_QUERY = " from Login l where l.username='"+username+"' and l.password='"+password+"'"; 
System.out.println(SQL_QUERY); 
Query query = session.createQuery(SQL_QUERY); 
Iterator<Login> it = query.iterate(); 
List<Login> list = query.list(); 
if (list.size() > 0) {


return true; 
} 

return false; 
}
} 

my success.jsp 我的success.jsp

<%@ 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 uri="/struts-tags" prefix="s"%> 
success

</body>
</html>

There are many ways to achieve this, but I am explaining one way to store session value. 有很多方法可以实现这一点,但是我正在解释一种存储会话值的方法。

Step 1 In your Login Action when users login put username in session if username and password are correct. 步骤1如果用户名和密码正确,则在用户登录时的“ 登录操作”中 ,将用户名放入会话中。

 Map<String,Object> session = ActionContext.getContext().getSession();

 session.put("username", username);

Step 2 Implement Interceptor Which checks this session value. 步骤2实施拦截器,检查该会话值。 Create package Interceptors and create a class AuthorizationInterceptor.java in it. 创建包Interceptors并在其中创建一个类AuthorizationInterceptor.java

package Interceptors;

import org.apache.struts2.dispatcher.SessionMap;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class AuthorizationInterceptor implements Interceptor {

private static final long serialVersionUID = 1841289944579731267L;

@Override
public void destroy() {
    // TODO Auto-generated method stub

}

@Override
public void init() {
    // TODO Auto-generated method stub

}

@Override
public String intercept(ActionInvocation inv) throws Exception {
    ActionContext context = inv.getInvocationContext();

    //for login and register actions ignore checking
    if(context.getName().equalsIgnoreCase("login") || context.getName().equalsIgnoreCase("register"))
    {
        return inv.invoke();
    }
    SessionMap<String,Object> map = (SessionMap<String,Object>) inv.getInvocationContext().getSession();
    if(map==null)
    {
        return "login"; 
    }
    Object user = map.get("username");      
    if(user==null ||user.equals("") || map.isEmpty() || map == null ){                  
        return "login";     
    }

    return inv.invoke();
}

}

Step 3: Configure this interceptor in struts.xml 步骤3:struts.xml配置此拦截器

<package name="mydefault" namespace="/" extends="struts-default">

    <interceptors>
        <interceptor name="Authorizeuser" class="Interceptors.AuthorizationInterceptor"></interceptor>

        <interceptor-stack name="myStack">
            <interceptor-ref name="defaultStack" />
            <interceptor-ref name="Authorizeuser" />
        </interceptor-stack>
    </interceptors>

    <default-interceptor-ref name="myStack" />
    <global-results>
          <result name="login">login.jsp</result>
     </global-results>

    ...your Actions here....
</package>

Up to this it will prevent action urls if user is not logged in 到目前为止,如果用户未登录,它将阻止操作URL

Step 4 Prevent jsps -> Put following code in the jsp you want to prevent eg success.jsp 步骤4防止jsps->将以下代码放入要防止的jsp中,例如success.jsp

 <%@ 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 uri="/struts-tags" prefix="s"%> 
 < %
    HttpSession sess = request.getSession(true);
    if (sess.getAttribute("username")==null)
    {
    % >
        <jsp:forward page="/login.jsp?msg=You will have to login first in order to access other pages"></jsp:forward>
    < %
    }
% >
<html>
    <body>
        success
    </body>
</html>

Note: Instead of using session, you can also use cookies,context variables etc. 注意:除了使用会话,您还可以使用cookie,上下文变量等。

You can solve your problem by using cookies..On your login page at the time of login, add a new cookie. 您可以使用cookie解决问题。.登录时,在登录页面上添加新的cookie。 Now on your success.jsp page check that cookie for null value..if it is, redirect again to login.jsp 现在,在您的success.jsp页面上,检查该cookie是否为空值。如果是,请再次重定向至login.jsp

Let's say you added a cookie named userid on your login page as 假设您在登录页面上添加了一个名为userid的cookie作为

 Cookie ck=new Cookie("usrid",userid);
 response.addCookie(ck);

Now on your success.jsp page you can check it for null value as : 现在,在您的success.jsp页面上,您可以通过以下方式检查它的空值:

 String userid = "";
 try 
 {
      Cookie[] ck = request.getCookies();
      for (int i = 0; i < ck.length; i++) 
      {
          if (ck[i].getName().equals("usrid")) 
          {
              userid = ck[i].getValue();
              break;
          }
      }
 } 
 catch (Exception ex) 
 {
     if (userid.equalsIgnoreCase("")) //if your cookie is null it will be redirected to login.jsp
     {
          response.sendRedirect("login.jsp");
     }
 }

This way, whenever you try to open success.jsp ,it will be redirected to login.jsp if you have not logged in 这样,每当您尝试打开success.jsp ,如果您尚未登录,它将被重定向到login.jsp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM