Nginx+tomcat 实现前后端分离(解决跨域)

工具:

nginx-1.15.3

apache-tomcat-9.0.11

 

代码准备:

前端

新建前端文件,结构如下

index.html代码如下


<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
  $("#b01").click(function(){
  htmlobj=$.ajax({url:"http://localhost/restdemo/RestDemo",async:false});
  $("#myDiv").html(htmlobj.responseText);
  });
});
</script>
</head>
<body>
<div id="myDiv"><h2>通过 AJAX 改变文本</h2></div>
<button id="b01" type="button">改变内容</button>
<a href="demo.html">demo</a>
</body>
</html>

 

后端

新建后端web项目,结构如下

RestDemo.java代码如下

package com.zq.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class RestDemo
 */
public class RestDemo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public RestDemo() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

nginx配置

静态网页请求发送到nginx静态目录html中,restdemo项目为后台请求,转发到后台。(注:这里是同一台机使用localhost,也可以是别的ip或域名)

访问测试:

浏览器输入地址:http://localhost/frontdemo/

点击“改变内容”按钮,可以看到文本通过ajax调通了

 

本文资源下载:Nginx1.15.3+Tomcat9.0.11前后端分离及测试源码

 

扩展:

Windows环境:

nginx启动:start nginx.exe

nginx停止:nginx -s stop

检查配置:nginx.exe -t

重启:nginx.exe -s reload

Linux环境:

https://www.cnblogs.com/codingcloud/p/5095066.html

 

 

 

  • 3
    点赞
  • 31
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值