【问题标题】:Checking for value in session BEFORE opening specific JSP在打开特定 JSP 之前检查会话中的值
【发布时间】:2023-03-03 23:33:01
【问题描述】:

我想在打开特定的 JSP 页面之前检查会话中的值是否为 null(authentification.jsp 映射到 authentification.html 并由 AuthentificationController.java 控制) 如果该值为 null 我希望用户被重定向到另一个页面,否则我希望他留在那个页面 我找不到解决方案,因为在控制器中我只有 formBackingObject 或 onSubmit 方法

【问题讨论】:

  • 如果我们假设您在 Session 对象中存储一个变量,那么在 AuthentificationController 类中您应该使用如下条件语句进行检查: String myvariable = session.getAttribute("myvariable"); if(myvariable == null){...}else{...} 如果我错过了您的问题的重点,那么我们需要查看更多代码才能完全理解您的查询。
  • 如果这是全局功能,请将其放入 HandlerInterceptor 或 servlet Filter。这样你只需要实现一次。
  • @M.Deinum 如何将 HandlerInterceptor 用于唯一的 URL??
  • 如果只有一个,在你的控制器中构建它。
  • 你能给我举个例子吗?

标签: java spring jsp model-view-controller controller


【解决方案1】:

我假设您使用的是 Spring 3.x,但另一方面看起来您使用的是旧的 Spring 2.0 (Simple)FormController

真的先学习如何使用 Spring 3.x Annotation Based Controller 和 Controller Methods。 (例如https://spring.io/guides/gs/serving-web-content/

回到你的问题:

要在 Spring 3.x Annotation Based Controller Method 中获取 HttpSession,只需将 HttpSession 类型的属性添加到控制器方法:

@Controller
public class SomeController {

    @RequestMapping("/test")
    public ModelAndView example(@RequestParam("name") String whatEver, ..., HttpSession session) {

        if (session.getAttribute("theVarialbe") != null) {
           return new ModelAndView(new RedirectView("somePage.html", true));
        } else {           
           Model model = new Model();
           return new ModelAndView("myJsp", model);        
        }
    }

}

【讨论】:

  • 嗨,我不明白如何使用该代码,我认为这不能解决问题。我想在打开特定 URL 之前检查会话的内容并选择稍后执行的操作。而且我不能使用注解,我必须使用 XML
  • 在一些 Request 被发送到服务器之前,你不能检查会话上下文,因为 Session 只存在于服务器中,并且它与 HttpServletRequest 相关联
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-09-11
  • 2011-02-27
  • 1970-01-01
  • 2012-11-18
  • 2012-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多