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数据

敬请期待。。。

原文地址:https://www.cnblogs.com/Donnnnnn/p/8074675.html