使用if语句将结果发送回jsp

时间:2014-11-12 14:59:06

标签: java jsp spring-mvc if-statement

我想要一种用户通过一系列单选按钮输入详细信息的方法。然后,java类通过查看响应并基于响应向用户返回分数来做一些工作(即,不同的响应可以给出不同的反馈)。我编写了jsps的代码,现在需要一些方法可以链接到包含if语句的java类,通过if语句然后返回结果。

选择单选按钮的第一个jsp

<form:form action="/HelloSpring/questionTwo" method="post">

    <p> What is the correct wrapper class for the primitive int? </p>
    <input type="radio" name="radios1" value="Int" path="types" >Int<br>
    <input type="radio" name="radios1" value="Enum" path="types">Enum<br>
    <input type="radio" name="radios1" value="integer" path="types" >integer<br>
    <input type="radio" name="radios1" value="Integer" path="types" >Integer<br>

             <input type="submit" value="Next" >

</form:form >

控制器应该读取结果,然后执行if语句

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


                String radio = (String)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;
                }
                else{
                    total = total + 0;
                }


                System.out.println(radio);

                return "results";

    }

应该发布他们得到的结果的jsp。 session.getAttribute位不起作用$ {total}

<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: ${total} /4</p>

1 个答案:

答案 0 :(得分:0)

将表单提交给控制器,调用if语句并将结果放入控制器返回的ModelAndView中。

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

      ModelAndView mav = new ModelAndView();
      // set name of next view ...
      mav.setViewName("results");

      // handle if...

      // add results to next view ...
      mav.addObject("anyNameYouWant", yourObject);
      return mav;

}