zoukankan      html  css  js  c++  java
  • SpringMVC:后台将List转为Json,传值到页面

    一、JSP页面

    <body>
    
        <form name="test" action="getAllStudent" method="post">
            <input type="text" name="username">
            <input type="submit" value="提交" onclick="submit()"/>
            
        </form>
        
        <table>
            <tr>
                <td>
                    ${message }
                </td>
            </tr>
        </table>
    
    </body>

     JS提交表单

    function submit(){
         document.getElementById("test").submit();  
     }

    二、后台(List转为Json,传值到页面)

    @RequestMapping("/getAllStudent") 
        public String getAllStudent(HttpServletRequest request, Model model) throws IOException{
            //获取JSP页面的值
            String ss = request.getParameter("username");
            //获取数据库数据,返回List
            List<Student> students  = studentService.getAllStudent();
            //定义Json数组,遍历List,存到Json数组
            JSONArray jsonArray = new JSONArray();
            for(Student s : students){
                System.out.println(s.getId());
                System.out.println(s.getName());
                
                JSONObject jo = new JSONObject();
                jo.put("id", s.getId());
                jo.put("name", s.getName());
                jsonArray.add(jo);
                
            }
            System.out.println(jsonArray.toString());
            //要传到页面的值交给Model,在JSP页面通过${message }即可获得
            model.addAttribute("message", jsonArray.toString());
            //forward转到页面,若是redirect重定向:页面${message }获取不到值
            return "forward:index.jsp";//返回index.jsp页面
            
        }

     JSON使用需要的JAR包。参考我另一篇博客:

    http://www.cnblogs.com/Donnnnnn/p/7645545.html

    三、页面处理JSON数据

    敬请期待。。。

  • 相关阅读:
    jQuery事件篇---高级事件
    Cookie处理
    JDBC技术
    JSP行为
    JSP九大内置对象
    JSP指令学习
    Oracle数据库学习之存储过程--提高程序执行的效率
    数据库操作之游标
    PL/SQL编程接触
    数据库数据的查询----连接查询
  • 原文地址:https://www.cnblogs.com/Donnnnnn/p/8074675.html
Copyright © 2011-2022 走看看