java 避免未登录_防止未登录的用户直接重写URL访问系统(java)

最近在开发系统的时候,碰到个问题,就是未登录的用户可以通过重写url登录他本不能登录的系统。

经过研究,终于把此问题解决了。呵~

思路是:每当有用户成功登录系统时,把其信息保存到session中。在相应被访问的页面,其对应的bean中的构造函数来获得session 中用户对象,若用户对象为空,则表明此用户是未登录的,使其跳转到登录页面。

session 取得代码

public class SessionHelper

{

private static final String OA_WEB_SESSION="OAWebSession";

private static HttpSession getSession()

{

FacesContext context = FacesContext.getCurrentInstance();

HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();

return request.getSession();

}

public static OAWebSession getOAWebSession()

{

Object session = getSession().getAttribute(OA_WEB_SESSION);

if (session == null)

{

session = new OAWebSession();

getSession().setAttribute(OA_WEB_SESSION, session);

}

return (OAWebSession) session;

}

public static void removeOAWebSession()

{

getSession().removeAttribute(OA_WEB_SESSION);

}

}

在用户成功登录后把其信息储存到session中

User user = new User();

user.login(userID, password);

SessionHelper.getOAWebSession().setUser(user);

被访问的页面对应的bean

public class Top{

public Top(){

user = SessionHelper.getOAWebSession().getUser();

if (user == null) {

NavigateHelper.redirect("Logon.jsp");

}

}

}

redirect 方法如下:

public class NavigateHelper

{

public static void redirect(String url)

{

FacesContext context = FacesContext.getCurrentInstance();

HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse();

try

{

response.sendRedirect(url);

}

catch (IOException ex)

{

ExceptionHelper.jumpToErrorPageWithResponseComplete(ex, SessionHelper.getOAWebSession());

}

}

}

注明: 由于jsf 是先走构造函数,才走get方法,所以get方法要加个对象或值取得为空的判断。

注明: 此块功能只对未登录的用户有效,登录了但没权挟的在研究中。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值