Cómo convertir la colección en datos json en el archivo Controller del proyecto SSM y representarlo en la página JSP

Puede ir a mi blog para ver más claramente: http://zhenyunboy.icu/?p=360 , o mi jardín de blogs: https://www.cnblogs.com/zhenyunboy/articles/13929203.html
A continuación se presentará Pasos específicos:
1. Cree un nuevo archivo de clase llamado ResponseUtil en el backend, copie el siguiente código en él

public class ResponseUtil {
    
    

	public static void write(HttpServletResponse response, Object o) throws Exception {
    
    
		response.setContentType("text/html;charset=utf-8");
		response.addHeader("Access-Control-Allow-Origin", "*");
		PrintWriter out = response.getWriter();
		out.println(o.toString());
		out.flush();
		out.close();
	}
}

2. Primero defina una respuesta HttpServletResponse como parámetro del método en la clase Controller requerida.
El siguiente es mi código solo como referencia:

public String way(HttpServletResponse response) throws Exception {
    
    }

3. Luego agregue el siguiente código en el archivo de controlador requerido:
JSONArray.fromObject (); Agregue sus datos de colección entre paréntesis, los datos de colección son la colección de objetos obtenida de la consulta de la base de datos.

//1.首先新建一个集合,集合是一个对象集合如List<User>,本人的
//集合对象是question,你是什么你就用什么。
List<question> questionList = new ArrayList<question>();
//2.注意这里是用集合接受你从数据库查询出来的数据一般是
//questionList=XXXXService.query(),我是用的xml存储数据
//所以有点区别,仅参考,如果用的mysql的话一般是写该句代码:
questionList=XXXXService.query();
//得到集合对象之后。再放入到JSONArray.fromObject()中
JSONObject result = new JSONObject();
JSONArray jsonArray = JSONArray.fromObject(questionList);
result.put("rows", jsonArray);
ResponseUtil.write(response, result);

4. El siguiente es el código de método específico de mi archivo de controlador:

	@RequestMapping(value = "/xuanZe")
	public String way(HttpServletResponse response) throws Exception {
    
    
		int difficult = 0;
		int testSelect = 0;
		int pop_size = 5;
		ZuJuan g = new ZuJuan();
		q = new QuestionFile(xuanze_qusetions_path);
		q = QuestionFile.getQFile();// 种群大小
		ArrayList<Individual> pop;
		StringBuffer resultContent = null;
		resultContent = new StringBuffer();
		pop = g.initial(pop_size, q, difficult);
		int j = 1;
		Individual best = pop.get(g.findBestIndividual(pop));
		int[] c = best.xuanze_chrom;
		String bString = resultContent.toString();
		List<question> questionList= new ArrayList<question>();
		questionList.clear();
		for (int k = 0; k < c.length; k++) {
    
    
			if (k != 27) {
    
    
				if (c[k] == 1) {
    
    
					// System.out.println(q.getXuanze_questions().get(k) + "\n\n");
					AllMeal.add(q.getXuanze_questions().get(k));
				}
			} else {
    
    
				break;
			}
		}
		//***********************************************
		//上面所有代码不过是为了获取question对象数据而已,
		//因为本人不是用的mysql数据库,所以仅参考,
		//你是怎么获取数据就怎么写,下面的代码基本不变套用就行
		//System.out.println(AllMeal);
		// 这里是获得项目路径下的WebRoot的路径
		JSONObject result = new JSONObject();
		JSONArray jsonArray = JSONArray.fromObject(questionList);
		result.put("rows", jsonArray);
		ResponseUtil.write(response, result);
		return null;
	}

5. Después de escribir el código anterior, se completa la devolución de datos de la interfaz de back-end, y es necesario obtenerlos en el front-end y representarlos en la página jsp.
Si ingresa la dirección de acceso en la barra de direcciones y ocurre la siguiente situación, significa que sus datos se devuelven correctamente.
Inserte la descripción de la imagen aquí
6. Luego, escriba el JSP de front-end, agregue el siguiente código en la etiqueta principal de la página XXX.jsp:

<script type="text/javascript">
  function go(){
    
    
	  $.ajax({
    
    
		   method:"get",//这里一般是get,因为你输入地址访问到了数据,如果是post就访问不到数据
		   url:"http://localhost:8080/movie_graph/zujuan/xuanZe.do",/*这里要写nginx访问的全路径,*/
		   //也就是你在地址栏输入地址访问到的数据,
		   //http://localhost:8080/你的项目名称/Controller里面类方法上面的名称/具体方法上面的名称
		   data:{
    
    },
		   dataType:'json',//注意这里一定要加这一句话,没有的话传过来的数据就是字符串
		   success: function(data){
    
    
			      var rows=data.rows;//这句代码必写,是已经获得到的具体json数据
			      //下面的代码都是给页面渲染数据且带有html标签显示。
			      //下面是循环便利你的json数据里面的单个对象,也就是说data.rows等价于question对象
			      //rows[i].identify 等价于question.identify
			      var msg="";
			      for(var i=0;i<rows.length;i++){
    
    
		             msg += "<tr>";
		             msg += "<td>" + rows[i].identify + "</td>";
		             msg += "<td>" + rows[i].difficulty + "</td>";
		             msg += "<td>" + rows[i].context+"&emsp;"+rows[i].difficulty+ "</td>";
		             msg += "<td>" + rows[i].a + "</td>";
		             msg += "<td>" + rows[i].c + "</td>";
		             msg += "<td>" + rows[i].d+ "</td>";
		             msg += "<td>" + rows[i].d + "</td>";              
		             msg += "</tr>";
			      }
			      $("#tab").html(msg);//这句是给html标签id为tab加上msg数据
		      }
		 });
	  } 
 </script>

7. Agregue el siguiente código a la etiqueta del cuerpo en la página JSP para representar los datos. Tenga en cuenta que debe hacer clic en el botón para mostrar el contenido, es decir, debe llamar al método go (). También puede llamar al método cuando se actualiza la página. La cosa es copiar el contenido de ajax ({}); a $ (function () {}).

<input style="background-color: cyan;" onclick="go()" type="button" value=" 开始答题 "  class="btn btn-default"/> 
<table>
    <thead>
          <th>ID</th>
          <th>难度</th>
          <th>内容</th>
          <th>A</th>
          <th>B</th>
           <th>C</th>
          <th>D</th>
     </thead>
     <tbody  id="tab">
     </tbody>
</table> 

8. Tenga en cuenta que el código anterior es de referencia. Si tiene alguna pregunta, por favor comente y deje un mensaje. También puedo modificar el artículo. Puede haber algunos errores menores.

Supongo que te gusta

Origin blog.csdn.net/qq_34134299/article/details/109499911
Recomendado
Clasificación