SSM框架以json格式传给前端页面

Posted 蓉啊

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSM框架以json格式传给前端页面相关的知识,希望对你有一定的参考价值。

配置文件和由Mybatis逆向工程生成了相关的代码见  登录实现

关键的是在Controller层的方法上加入@ResponseBody注解实现json格式

在控制台输出的json格式数据

index.jsp

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP \'test.jsp\' starting page</title>
    
     <%
        pageContext.setAttribute("APP_PATH",request.getContextPath());
     %>
    <script type="text/javascript" src="${APP_PATH}/static/js/jquery-3.2.1.min.js"></script>
    <link rel="stylesheet" type="text/css" href="${APP_PATH}/static/bootstrap-3.3.7-dist/css/bootstrap.min.css">
    <script type="text/javascript" src="${APP_PATH}/static/bootstrap-3.3.7-dist/js/bootstrap.min.js"></script>

  </head>
  
  <body>
    <button id="button">获取数据</button>
   
  </body>
  <script>
  var name=$("#name").val();
  var password=$("#password").val();
  
          $("#button").click(function(){
              $.ajax({
                  url:"${APP_PATH}/depts",
                  success:function(result){
                      console.log(result);
                      console.log(result.length);
                      } 
                  });
          });
      
          
  
  </script>
</html>

DepartmentController.java

package com.ssm.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ssm.bean.Department;
import com.ssm.service.DepartmentService;


@Controller
public class DepartmentController {
        
        @Autowired
        DepartmentService departmentService;
        
        @RequestMapping("/depts")
        @ResponseBody
        public List<Department> getAllDept(){
            
            List<Department> list = departmentService.getDepts();
            return list;
            
        }
        
}

DepartmentService.java

package com.ssm.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import com.ssm.bean.Department;
import com.ssm.dao.DepartmentMapper;

@Service
public class DepartmentService {
    
    @Autowired
    DepartmentMapper departmentMapper;
    
    public List<Department> getDepts() {
        
        return departmentMapper.selectByExample(null);
    }

}

 

以上是关于SSM框架以json格式传给前端页面的主要内容,如果未能解决你的问题,请参考以下文章

ssm项目实现删除操作后如何使查询出来的数据页面自动刷新?

SSM框架下jsp页面怎么获取数据库的数据

Ssm框架下怎么把数据库数据动态显示到前端页面?

使用SpringMVC返回java对象数据时会自动转为json格式传给前端

代码中怎么看出使用了vue框架

前端向后端传一个json数组对象