Springboot实现ajax

本文将结束如何让springboot完美结合ajax,springboot在这里先不介绍,想了解的同学可以去看我的博客,里面有Spirngboot+mybatis的demo

1. 配置好jsp路径;例如我是放在WEB-INF/jsp/下;配置路径如下

将代码写在application.properties里

spring.mvc.view.prefix:/WEB-INF/jsp/

spring.mvc.view.suffix:.jsp

2. controller代码

@RestController  
@RequestMapping("/api")  
public class CityRestController {  
  
    @Autowired  
    private CityService cityService;  
    @RequestMapping(value = "/ajax", method = RequestMethod.GET)  
    @ResponseBody  
    public Map ajax(@RequestParam("cityName") String city){  
        Map map=new HashMap();  
        map.put("name", "zz");  
        map.put("city", "fujian");  
        System.out.println(city);  
        return map;  
  
    }  
    @RequestMapping(value = "/", method = RequestMethod.GET)  
    public ModelAndView index(HttpServletResponse response,  
            HttpServletRequest request) throws MalformedURLException {  
        return new ModelAndView("index");  
  
    }  
}


3. index.jsp代码如下

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>






Springboot + Jsp


    ${hello}
    

启动方式

  1. spring-boot:run
  2. 打包成war,通过 java -jar demo-0.0.1-SNAPSHOT.war启动

jar包运行的时候会404错误,因为默认jsp不会被拷贝到程序包中,而war包里面有包含了jsp,所以没问题。

另外springboot官方并不推荐使用jsp

4. 启动运行

http://localhost:8080/api/

Springboot实现ajax_第1张图片


点击提交;前端提示

Springboot实现ajax_第2张图片


后台显示接收成功

Springboot实现ajax_第3张图片



你可能感兴趣的:(ajax,Springboot)