欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2022-07-10 08:07:35
...

工具:

nginx-1.15.3

apache-tomcat-9.0.11

 

代码准备:

前端

新建前端文件,结构如下

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

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项目,结构如下

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

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项目为后台请求,转发到后台

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

访问测试:

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

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

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

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

 

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

 

扩展:

Windows环境:

nginx启动:start nginx.exe

检查配置:nginx.exe -t

重启:nginx.exe -s reload

Linux环境:

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