Value passing mode of json in SSM

1. The first way to use $. getJSON() (passing in List data)
(1) Controller code

Add @ RequestMapping(value = "method name", produces = "application/json; charset=UTF-8")

Add @ ResponseBody

Note that the method name should be consistent with the path reference name in js code

After getting the database data, define a json to receive the list name of the found data and return json

    /*
     * Get all announcements
     */
    @RequestMapping(value="getAllNotice",produces = "application/json; charset=UTF-8")//Returned json, not html
    @ResponseBody
    public String getAllNotice(){
        List<Notice> notices = newsService.getAllNotice();
        String json = JSON.toJSONString(notices);
        return json;
    }


(2) js code
Use $. getJSON() method to receive data in js code, such as

 $.getJSON("News/getAllNotice",function(r){

});

        //Display the bulletin board title on the left side of the news view.jsp page
        $.getJSON("News/getAllNotice",function(r){
            //Circular output display announcement
            for(var i = 0; i < r.length; i++){
                $("#news-list1 ul").append("<li><a index='"+i+"'>"+r[i].title+"</a></li>");
            }
            $("#news-list1 ul li a").click(function(){
                //Click the announcement title on the left to display the content
                var index = $(this).attr("index");//Get subscript
                $("#news h1").html(r[index].title); / / display the title
                $("#News. Content "). HTML (R [index]. Content); / / display details
            });
        });

2. The second way to use $. ajax({}) is to pass in List data
(1) Controller code

Add @ RequestMapping("getAllNews")

After receiving the data, fill it with JSONArray and put it into OutUtil.print(jsonArray, response); in js, receive the data

OutUtil is a encapsulated class. It is a class to clear and close json. print() is its encapsulated method, which is convenient for code writing. It doesn't need to write PrintWriter once for each method to solve Chinese disorder. I paste the specific writing method at the end of the page

    /*
     * Get all news
     */
    @RequestMapping("getAllNews")
    public String getAllNews(HttpServletResponse response){
        List<News> news = newsService.getAllNews();
        JSONArray jsonArray = JSONArray.fromObject(news);
        OutUtil.print(jsonArray, response);
        return null;
    }


(2) js code

        //Display the news bar title on the left side of the news view.jsp page
        $.ajax({
            type:"post",
            url:"News/getAllNews.do",
            dataType:"json",
            success:function(r){
                for(var i = 0; i < r.length; i++){//Loop title
                    $("#news-list2 ul").append("<li><a index='"+i+"'>"+r[i].title+"</a></li>");
                }
                $("#news-list2 ul li a").click(function(){
                    //Click the news title on the left to display the content
                    var index = $(this).attr("index");
                    $("#news h1").html(r[index].title);
                    $("#news .content").html(r[index].content);
                });
            }
        });


3. Pass in the json code of an object
(1) Controller code

    /*
     * Get the news details according to the news id
     */
    @RequestMapping("getNewById")
    public String getNewByIdS(String nid,HttpServletResponse response){
        News news = newsService.getNewsById(nid);
        JSONObject jsonObject =new JSONObject();
        jsonObject.put("rows", news);//Incoming news objects
        OutUtil.print(jsonObject, response);
        return null;
    }

(2) js code

            //Show news details
            $.ajax({
                type:"post",
                url:"News/getNewById.do?nid="+id,
                dataType:"json",
                success:function(res){
                    //Show information on page
                    $("#news h1").append(res.rows.title);
                    $("#news .content").append(res.rows.content);    
                }
            });   

4. Encapsulate the OutUtil class to reduce the code amount

package cn.jbit.util;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

public class OutUtil {
	public static void print(Object o,HttpServletResponse response){
		//Solve ajax Chinese code
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out;
		try {
			out = response.getWriter();
			out.print(o);
			out.flush();
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
}

 

Tags: JSON JSP Database Java

Posted on Thu, 09 Jan 2020 13:55:38 -0500 by homchz