admin管理员组

文章数量:1534389

文章目录

    • 问题重现
    • 解决方法
    • 成功解决

问题重现

Controller中使用@ResponseBody返回JSON数据。

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping(path = "/", method = RequestMethod.GET)
    @ResponseBody
    public List<Student> selectStudents() {
        return studentService.selectStudents();
    }
}

下图:本机运行项目,用360安全浏览器访问,没有问题。

下图:把项目部署到阿里云服务器上,用360安全浏览器访问,不会显示想要展示的JSON字符串,而是会把字符串存到后缀为.json的文件里,下载下来。

下图:把项目部署到阿里云服务器上,用chrome浏览器访问,没有问题。

解决方法

pom.xml 里加上:

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.58</version>
        </dependency>

修改Controller代码为:

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping(path = "/", method = RequestMethod.GET)
    //@ResponseBody
    public void selectStudents(HttpServletResponse response) {
        //return studentService.selectStudents();
        response.setContentType("text/html;charset=utf-8");
        try (
                PrintWriter writer = response.getWriter();
        ) {
            writer.write(JSON.toJSONString(studentService.selectStudents()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

成功解决

下图:此时本地可以访问。

下图:把项目部署到阿里云服务器上,用360安全浏览器访问,可以显示想要展示的JSON字符串。

下图:把项目部署到阿里云服务器上,用chrome浏览器访问,没有问题。

本文标签: 弹出下载页面浏览器数据responseBody