【问题标题】:How do you print a variable in a .jsp file that is from a Java class?如何打印来自 Java 类的 .jsp 文件中的变量?
【发布时间】:2015-01-07 21:41:26
【问题描述】:

我有一个 .jsp 文件,应该告诉用户他们的考试结果。

这是一个 WebController.java 类,它计算出一个人给出的答案,然后根据他们的答案是错还是正确添加 0 或 1。

@RequestMapping(value = "/results", method = RequestMethod.POST)
    public String results(Model model, HttpSession session, HttpServletRequest request,
            HttpServletResponse response){

            String radio = request.getParameter("radios1");

            request.setAttribute("total", total);
            model.addAttribute("total", total);

            if (radio.equals("int")){
                total = total + 0;
            }
            else if (radio.equals("Enum")){
                total = total + 0;
            }
            else if (radio.equals("integer")){
                total = total + 0;
            }
            else if (radio.equals("Integer")){
                total = total + 1;
            }

            return "results";
}

我想将“total”变量打印到 jsp 页面上,以便它显示在浏览器中。 所以这个想法是用户将能够立即看到他们在测试中得到了什么。

这也可以反过来以同样的方式工作吗?例如在上面的代码中,java类可以获取位于jsp类的表单内的参数“radios1”吗?

<p>Good day <%= session.getAttribute("uname") %> </p>
<p>For question 1 you chose <%= session.getAttribute("q1") %> </p>
<p>For question 2 you chose <%= session.getAttribute("q2") %> </p>
<p>For question 3 you chose <%= session.getAttribute("q3") %> </p>
<p>For question 4 you chose <%= session.getAttribute("q4") %> </p>

<section>

    <p>Total score: ${requestScope.total}</p>
    <p>Total score: ${total}</p>
</section>

【问题讨论】:

    标签: java jsp variables spring-mvc


    【解决方案1】:

    将请求、响应或会话中的总数设置为 属性,然后使用 JSTL 或 EL(表达式语言)在 JSP 中获取它

    例如

    小服务程序

    request.setAttribute("total",total);
    

    JSP:

    ${requestScope.total}
    

    JSP EL 中有几个隐式对象。请参阅“隐式对象”标题下的 Expression Language

    阅读更多...

    How to access a request attribute set by a servlet in JSP?

    【讨论】:

    • 我已经按照说的做了,但还没有运气。我的代码在上面的问题中被编辑了,你能看到任何明显的错误吗??
    【解决方案2】:

    将总数添加到模型中并在 html 上显示为

    model.addAttribute("total",total);

    并在 html 上显示为

    ${总计}

    【讨论】:

    • 我已经按照说的做了,但还没有运气。我的代码在上面的问题中被编辑了,你能看到任何明显的错误吗??
    • 什么是输出或者你得到一个异常
    • netbeans 目前很困难,并且在控制台中没有给我任何东西。我只能按照浏览器告诉我的内容去做。 (这显然不是工作或不工作)。
    【解决方案3】:

    当您使用 Spring MVC 时,您应该简单地输入 Model 您想要传递给视图的内容:

    model.addAttribute("total", total);
    

    【讨论】:

    • 大写字母a 的位置不对,抱歉。从智能手机上来说这并不容易:-(
    • 不用担心,我已经看到足够多的时间知道它应该是小写的!编辑了我的问题代码,浏览器仍然没有打球
    • 我在 java 类 static int total = 0; 顶部的变量名是否与此变量 model.addAttribute("total", total); 的名称相同?会不会弄糊涂了..?
    • @RedBaron 在这里使用静态变量看起来很奇怪......在会话中可能会更好。你是否控制了你在radio 中真正得到的东西?
    • 由于这里的建议,我在这里使用静态变量。 stackoverflow.com/questions/17126541/… 和收音机就是来自这个字符串。 String radio = request.getParameter("radios1");这是在 .jsp 文件中引用这些 Int
      抱歉评论中有很多代码。你明白我在做什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-13
    • 2014-03-15
    • 2016-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多