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

工具:

nginx-1.15.3

apache-tomcat-9.0.11

 

代码准备:

前端

新建前端文件,结构如下

index.html代码如下






Insert title here




通过 AJAX 改变文本

demo

 

后端

新建后端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

 

 

 

你可能感兴趣的:(javaee,架构)