Springboot实现ajax

本文探讨了如何在Springboot项目中有效地结合使用Ajax。首先,介绍了配置JSP路径的方法,例如将页面放在WEB-INF/jsp/目录下,并在application.properties文件中进行设置。接着,通过一个例子展示了Ajax请求的URL配置,如http://localhost:8080/api/。在实际操作中,当用户点击提交后,前端能够收到成功提示,同时后台也能正确显示接收到了请求。

本文将结束如何让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/



点击提交;前端提示



后台显示接收成功




评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值