jquery访问服务器

13 篇文章 0 订阅
4 篇文章 0 订阅

服务器

目录

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.bootvue</groupId>
  <artifactId>springvue</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>springvue Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.0.5.RELEASE</version>
	</parent>
	
	<dependencies>
		 <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>           
        </dependency>	
		

	</dependencies>
	<build>
		<finalName>springvue</finalName>
			<plugins>
			
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>			 
		</plugins>		
	</build>	
</project>

main

package com.bootvue;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;


import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


@RestController
@SpringBootApplication
@ServletComponentScan(basePackages = "com.bootvue.filter")
public class SpringVue {	
	@RequestMapping("/register")
    public @ResponseBody
    Map select(@RequestParam Map map,HttpServletRequest req) throws ServletException, IOException {   
		
        return map;     
    }
	
	@RequestMapping("/login")
    public @ResponseBody
    Map login(@RequestParam Map map,HttpServletRequest req) throws ServletException, IOException {     
        if ("zsls".equals(map.get("user"))) {
        	map.put("login", "success");
        	req.getSession().setAttribute("islogin", map.get("user"));
		} else { 
			map.put("login", "fail");
			req.getSession().setAttribute("islogin", null);
		}             
		
        return map;     
    }
	
	@RequestMapping("/tologin")
    public @ResponseBody
    Map toLogin(@RequestParam Map map,HttpServletRequest req) throws ServletException, IOException {     
       	map.put("login", "tologin");  		
        return map;     
    }
	
	
	public static void main(String[] args) {
		SpringApplication.run(SpringVue.class, args);
	}
	

	

}

filter

package com.bootvue.filter;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebFilter(filterName = "test", urlPatterns = "/*")
public class CrosFilter implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
			throws IOException, ServletException {

		HttpServletResponse response = (HttpServletResponse) servletResponse;
		HttpServletRequest request = (HttpServletRequest) servletRequest;
		
//		String[] allowDomains = {"http://127.0.0.1:800","http://www域名2"};
//        Set allowOrigins = new HashSet(Arrays.asList(allowDomains));
//        
        String originHeads = request.getHeader("Origin");       
        System.out.println(originHeads);
        if(originHeads==null) originHeads="*";
	
		boolean loginURL = request.getRequestURI().contains("tologin") || request.getRequestURI().contains("login");
		response.setHeader("Access-Control-Allow-Origin", originHeads);
		response.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,HEAD,PUT,PATCH");
		response.setHeader("Access-Control-Max-Age", "36000");
		response.setHeader("Access-Control-Allow-Headers",
				"Origin, X-Requested-With, Content-Type, Accept,Authorization,authorization");
		response.setHeader("Access-Control-Allow-Credentials", "true");
		String islogin = (String) request.getSession().getAttribute("islogin");
		System.out.println(request.getRequestURI());
		System.out.println("islogin="+islogin);
		if (!loginURL)
			if (!"zsls".equals(islogin)) {
				response.sendRedirect("tologin");
				return;
			}
		filterChain.doFilter(servletRequest, servletResponse);
	}

	public void destroy() {

	}
}

 

前端

islogin.js

$.ajax({
		url:"http://127.0.0.1:8080/register",	
		xhrFields:{
			            withCredentials:true
	    },
		crossDomain:true,
		success:function(res){		
			console.log(res)
			if(res.login=="tologin"){
				window.location.href="login.html"
			}
		}
	});

 

login.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<script src="jquery.min.js"></script>
		<script>
	$(function(){
		$("input[type='button']").click(function(){
			$.ajax({
				url:"http://127.0.0.1:8080/login",
				data:{user:$("#user").val()},
				xhrFields:{
				            withCredentials:true
				        },
				crossDomain:true,
				success:function(res){
					if(res.login=="fail")
					{
						 $("#fts").html(res.login)
					}else{
						alert("success");
						window.location.href="index.html"
					}
				}
			});
			
		})
	});	
	</script>	
		<title></title>
	</head>
	<body>
	user:<input id="user" /> <font id="fts" color=red></font><br>
	pass:<input id="pass" />
	<input   type="button" value="login" />
	</body>
</html>

test.html

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<script type="text/javascript" src="jquery.min.js"></script>
		<script type="text/javascript" src="islogin.js"></script>
	</head>
	<body>
		test...............
	</body>
</html>

访问效果(单独访问或协议访问)

打开test.html

直接跳到login.html

登录后访问

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值