Springboot实现ajax

来源:互联网 发布:日常工作安排软件 编辑:程序博客网 时间:2024/06/05 14:33

本文将结束如何让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<String,String> ajax(@RequestParam("cityName") String city){          Map<String, String> map=new HashMap<String, String>();          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"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><script src="https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js"></script><script>function sendAjax(){var cityname = $("#cityName").val();    $.ajax(    {        url:"ajax",        data:{"cityName":cityname},        type:"get",        dataType:"json",        success:function(data)        {            alert(data.name);        },        error: function() {            alert("error");          }    }); }</script><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Springboot + Jsp</title></head><body>    ${hello}    <p>启动方式</p>    <ol>        <li>spring-boot:run</li>        <li>打包成war,通过 java -jar demo-0.0.1-SNAPSHOT.war启动</li>    </ol>    <p>jar包运行的时候会404错误,因为默认jsp不会被拷贝到程序包中,而war包里面有包含了jsp,所以没问题。</p>    <p>另外springboot官方并不推荐使用jsp</p>    <input name="cityName" id="cityName"type=text/>    <button onclick="sendAjax()">提交</button></body></html>
4. 启动运行

http://localhost:8080/api/



点击提交;前端提示



后台显示接收成功




原创粉丝点击