新加载页面$(window).focus()无效问题的解决

本文介绍了一个页面加载后未能自动触发focus事件的问题,并提供了解决方案。通过使用setTimeout结合triggerHandler方法,可以在页面加载后手动触发窗口的focus事件,解决了兼容性问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

新打开了一个页面,需要在页面的focus事件中触发函数,代码如下:

$(function(){
        var end=null;
        //页面失去焦点则停止提交
        $(window).blur(function(){
            clearInterval(end);
        });
        //页面得到焦点开始提交
        $(window).focus(function(){
            readBegin();
            end = setInterval(readEnd, 5000);
        });
        $(window).focus();
    });

发现在页面加载之后,window没有触发focus事件,多处翻阅资料,后改为如下代码即可:

$(function(){
        var end=null;
        //$(window).trigger("focus");
        //页面失去焦点则停止提交
        $(window).blur(function(){
            clearInterval(end);
        });
        //页面得到焦点开始提交
        $(window).focus(function(){
            readBegin();
            end = setInterval(readEnd, 5000);
        });
        window.setTimeout("$(window).triggerHandler('focus');", 100);//setTimeout可解决事件触发兼容问题,triggerHandler为执行focus事件却又不会让此元素获取焦点
    });

参考资料:setTimeout:http://my.oschina.net/justdo/blog/125643
triggerHandler:http://www.css88.com/jqapi-1.9/focus/

<template> <div id="cesiumContainer"></div> <div ref="miniMapContainer" class="mini-map" @click="handleMiniMapClick"> <div class="location-indicator" :style="indicatorStyle"></div> <!-- 四个角折角 --> <div class="corner corner-top-left"></div> <div class="corner corner-top-right"></div> <div class="corner corner-bottom-left"></div> <div class="corner corner-bottom-right"></div> <!-- <div class="camera-icon">📷</div> --> <div class="focus-effect"></div> <div class="pulse"></div> </div> <Search @location-selected="handleLocationSelected" /> <LocationBar v-if="loaded" :update-interval="100" :use-dms-format="useDmsFormat" /> </template> <style> /* @import "/temp/css/divGraphic.css"; */ </style> <script setup lang="ts"> import { computed, onUnmounted, onMounted, reactive } from "vue"; import LocationBar from "./location-bar.vue"; import Search from "./search.vue"; import initMap from "./init"; import { ref } from "vue"; import { throttle } from 'lodash'; import { loadRipplePoints, createMultipleRippleCircles } from './circle.js'; import { $prototype } from "../../main.ts"; const miniMapContainer = ref<HTMLElement>(); let viewIndicator: Rectangle; // 视图指示器样式 const currentPosition = reactive({ longitude: 113.361538, latitude: 27.339318, }); // 株洲市范围常量 const ZHUZHOU_EXTENT = { west: 112.5, // 株洲市西边界 east: 114.5, // 株洲市东边界 south: 26.0, // 株洲市南边界 north: 28.0 // 株洲市北边界 }; const rippleEntities = ref<any[]>([]); // 存储波纹圆实体 const heightThreshold = 80000; // 高度阈值(),高于此值隐藏波纹圆 const updateRippleVisibility = throttle(() => { if (!$prototype.$map || rippleEntities.value.length === 0) return; // 添加缺失的相机高度计算和显示判断 const cameraHeight = $prototype.$map.camera.positionCartographic.height; const shouldShow = cameraHeight > heightThreshold; rippleEntities.value.forEach(entity => { entity.show = shouldShow; }); }, 200); // 更指示器位置 const updateIndicatorPosition = () => { if (!$prototype.$map) return; const camera = $prototype.$map.camera; const rect = camera.computeViewRectangle(); if (!rect) return; // 计算在株洲市范围内的相对位置 const center = Cesium.Rectangle.center(rect); const lon = Cesium.Math.toDegrees(center.longitude); const lat = Cesium.Math.toDegrees(center.latitude); const lonPercent = ((lon - ZHUZHOU_EXTENT.west) / (ZHUZHOU_EXTENT.east - ZHUZHOU_EXTENT.west)) * 100; const latPercent = 100 - ((lat - ZHUZHOU_EXTENT.south) / (ZHUZHOU_EXTENT.north - ZHUZHOU_EXTENT.south)) * 100; // 更CSS指示器 indicatorStyle.value = { left: `${lonPercent}%`, top: `${latPercent}%`, display: "block" }; }; // 更鹰眼地图 - 只更指示器位置 const updateOverview = () => { if (!$prototype.$map || !overviewViewer.value) return; // 获取主地图的当前视图中心 const rectangle = $prototype.$map.camera.computeViewRectangle(); if (!rectangle) return; const center = Cesium.Rectangle.center(rectangle); currentPosition.longitude = Cesium.Math.toDegrees(center.longitude); currentPosition.latitude = Cesium.Math.toDegrees(center.latitude); // 更指示器位置 updateIndicatorPosition(); }; const overviewViewer = ref(null); // 初始化鹰眼地图 - 使用株洲市影像 const initMiniMap = () => { Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxMDhlNDdmYy03NzFhLTQ1ZTQtOWQ3NS1lZDAzNDc3YjE4NDYiLCJpZCI6MzAxNzQyLCJpYXQiOjE3NDcwNTMyMDN9.eaez8rQxVbPv2LKEU0sMDclPWyHKhh1tR27Vg-_rQSM"; if (!miniMapContainer.value) return; // 创建株洲市专用影像提供器 const zhuzhouProvider = new Cesium.UrlTemplateImageryProvider({ url: "http://124.232.190.30:9000/proxy/pk1725866655224/map/zzzsyx_18/{z}/{x}/{y}.png", minimumLevel: 1, maximumLevel: 17, crs: "EPSG:3857", }); // 鹰眼地图初始化 - 使用株洲市影像 overviewViewer.value = new Cesium.Viewer(miniMapContainer.value, { sceneMode: Cesium.SceneMode.SCENE2D, baseLayerPicker: false, homeButton: false, timeline: false, navigationHelpButton: false, animation: false, scene3DOnly: true, selectionIndicator: false, infoBox: false, imageryProvider: zhuzhouProvider, // 使用株洲市影像 terrainProvider: window.Cesium.createWorldTerrain(), }); // 设置固定视野为株洲市范围 overviewViewer.value.camera.setView({ destination: Cesium.Rectangle.fromDegrees( ZHUZHOU_EXTENT.west, ZHUZHOU_EXTENT.south, ZHUZHOU_EXTENT.east, ZHUZHOU_EXTENT.north ) }); // 隐藏控件 var toolbar = overviewViewer.value.container.getElementsByClassName("cesium-viewer-toolbar")[0]; if (toolbar) toolbar.style.display = "none"; overviewViewer.value.cesiumWidget.creditContainer.style.display = "none"; }; // 初始化视图指示器 function initRectangle() { // 创建视图指示器(株洲市范围框) viewIndicator = overviewViewer.value.entities.add({ rectangle: { coordinates: new Cesium.CallbackProperty(() => { return Cesium.Rectangle.fromDegrees( ZHUZHOU_EXTENT.west, ZHUZHOU_EXTENT.south, ZHUZHOU_EXTENT.east, ZHUZHOU_EXTENT.north ); }, false), material: Cesium.Color.RED.withAlpha(0.3), outline: true, outlineColor: Cesium.Color.RED, outlineWidth: 2, }, }); } // 指示器样式计算 const indicatorStyle = computed(() => { return {}; // 由updateIndicatorPosition直接设置 }); const loaded = ref(false); const useDmsFormat = ref(false); function addDemoGraphics() { const chinaBoundary = $prototype.$map.dataSources.add( Cesium.GeoJsonDataSource.load("/shp_zz.geojson", { stroke: Cesium.Color.WHITE, fill: false, clampToGround: true, describe: null, }) ); chinaBoundary.then((dataSource) => { const entities = dataSource.entities.values; for (let entity of entities) { if (entity.polyline) { entity.polyline.fill = false; } } }); } function flyToDes() { const center = Cesium.Cartesian3.fromDegrees(-98.0, 40.0); $prototype.$map.camera.flyTo({ destination: new Cesium.Cartesian3( -2432812.6687511606, 5559483.804371395, 2832009.419525571 ), orientation: { heading: 6.283185307179421, pitch: -1.0472145569408116, roll: 6.2831853071795205, }, complete: function () {}, }); } // 监听主地图相机变化 const setupCameraListener = () => { $prototype.$map.camera.changed.addEventListener(updateOverview); }; // 鹰眼地图点击处理 const handleMiniMapClick = (event: MouseEvent) => { if (!miniMapContainer.value || !overviewViewer.value) return; const rect = miniMapContainer.value.getBoundingClientRect(); const x = event.clientX - rect.left; const y = event.clientY - rect.top; // 计算在固定范围内的相对位置 const xPercent = (x / rect.width) * 100; const yPercent = (y / rect.height) * 100; // 转换为株洲市范围内的经纬度 const lon = ZHUZHOU_EXTENT.west + (xPercent / 100) * (ZHUZHOU_EXTENT.east - ZHUZHOU_EXTENT.west); const lat = ZHUZHOU_EXTENT.north - (yPercent / 100) * (ZHUZHOU_EXTENT.north - ZHUZHOU_EXTENT.south); // 主地图飞向点击位置 $prototype.$map.camera.flyTo({ destination: Cesium.Cartesian3.fromDegrees(lon, lat, 1000000), }); }; function addImage() { var rightImageProvider = new Cesium.UrlTemplateImageryProvider({ name: "影像图", type: "xyz", layer: "vec_d", url: "http://124.232.190.30:9000/proxy/pk1725866655224/map/zzzsyx_18/{z}/{x}/{y}.png", minimumLevel: 1, maximumLevel: 17, crs: "EPSG:3857", }); $prototype.$map.imageryLayers.addImageryProvider(rightImageProvider); rightImageProvider.splitDirection = Cesium.SplitDirection.right; } onMounted(() => { initMap(); addImage(); loaded.value = true; addDemoGraphics(); flyToDes(); initMiniMap(); setupCameraListener(); setTimeout(function () { initRectangle(); }, 2000); (async () => { try { const ripplePoints = await loadRipplePoints(); rippleEntities.value = createMultipleRippleCircles( $prototype.$map, ripplePoints ); $prototype.$map.camera.changed.addEventListener(updateRippleVisibility); updateRippleVisibility(); } catch (error) { console.error('加载波纹圆失败:', error); } })(); }); let currentMarker: any = null; const createMarker = (location: { lng: number; lat: number; name: string }) => { if (currentMarker) { $prototype.$map.entities.remove(currentMarker); } currentMarker = $prototype.$map.entities.add({ position: Cesium.Cartesian3.fromDegrees( location.lng, location.lat, 50 ), point: { pixelSize: 200, color: Cesium.Color.RED, outlineColor: Cesium.Color.WHITE, outlineWidth: 2, heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND, }, label: { text: location.name, font: "40px sans-serif", fillColor: Cesium.Color.WHITE, outlineColor: Cesium.Color.BLACK, outlineWidth: 1, verticalOrigin: Cesium.VerticalOrigin.BOTTOM, pixelOffset: new Cesium.Cartesian2(0, -20), heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND, distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, 10000), }, description: `<div style="padding: 10px;"> <h3 style="margin: 0 0 5px 0;">${location.name}</h3> <p>经度:${location.lng.toFixed(6)}</p> <p>纬度:${location.lat.toFixed(6)}</p> </div>`, }); return currentMarker; }; const handleLocationSelected = (location: { lng: number; lat: number; name: string; }) => { if (!$prototype.$map) return; const destination = Cesium.Cartesian3.fromDegrees( location.lng, location.lat, 200 ); $prototype.$map.camera.flyTo({ destination, orientation: { heading: Cesium.Math.toRadians(0), pitch: Cesium.Math.toRadians(-45), roll: 0, }, duration: 2, complete: () => { createMarker(location); }, }); }; onUnmounted(() => { if ($prototype.$map) { $prototype.$map.destroy(); $prototype.$map = null; } if ($prototype.$map) { $prototype.$map.camera.changed.removeEventListener(updateRippleVisibility); } console.log("组件销毁"); }); const emit = defineEmits(["onload", "onclick"]); const initMars3d = async (option: any) => { emit("onclick", true); emit("onload", $prototype.$map); }; </script> <style lang="less"> /**cesium 工具按钮栏*/ .cesium-viewer-toolbar { top: auto !important; bottom: 35px !important; left: 12px !important; right: auto !important; } .cesium-toolbar-button img { height: 100%; } .cesium-viewer-toolbar > .cesium-toolbar-button, .cesium-navigationHelpButton-wrapper, .cesium-viewer-geocoderContainer { margin-bottom: 5px; float: left; clear: both; text-align: center; } .cesium-button { background-color: rgba(23, 49, 71, 0.8); color: #e6e6e6; fill: #e6e6e6; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3); line-height: 32px; } .cesium-button:hover { background: #3ea6ff; } /**cesium 底图切换面板*/ .cesium-baseLayerPicker-dropDown { bottom: 0; left: 40px; max-height: 700px; margin-bottom: 5px; background-color: rgba(23, 49, 71, 0.8); } /**cesium 帮助面板*/ .cesium-navigation-help { top: auto; bottom: 0; left: 40px; transform-origin: left bottom; background: none; background-color: rgba(23, 49, 71, 0.8); .cesium-navigation-help-instructions { background: none; } .cesium-navigation-button { background: none; } .cesium-navigation-button-selected, .cesium-navigation-button-unselected:hover { background: rgba(0, 138, 255, 0.2); } } /**cesium 二维三维切换*/ .cesium-sceneModePicker-wrapper { width: auto; } .cesium-sceneModePicker-wrapper .cesium-sceneModePicker-dropDown-icon { float: right; margin: 0 3px; } /**cesium POI查询输入框*/ .cesium-viewer-geocoderContainer .search-results { left: 0; right: 40px; width: auto; z-index: 9999; } .cesium-geocoder-searchButton { background-color: rgba(23, 49, 71, 0.8); } .cesium-viewer-geocoderContainer .cesium-geocoder-input { background-color: rgba(63, 72, 84, 0.7); } .cesium-viewer-geocoderContainer .cesium-geocoder-input:focus { background-color: rgba(63, 72, 84, 0.9); } .cesium-viewer-geocoderContainer .search-results { background-color: rgba(23, 49, 71, 0.8); } /**cesium info信息框*/ .cesium-infoBox { top: 50px; background-color: rgba(23, 49, 71, 0.8); } .cesium-infoBox-title { background-color: rgba(23, 49, 71, 0.8); } /**cesium 任务栏的FPS信息*/ .cesium-performanceDisplay-defaultContainer { top: auto; bottom: 35px; right: 50px; } .cesium-performanceDisplay-ms, .cesium-performanceDisplay-fps { color: #fff; } /**cesium tileset调试信息面板*/ .cesium-viewer-cesiumInspectorContainer { top: 10px; left: 10px; right: auto; } .cesium-cesiumInspector { background-color: rgba(23, 49, 71, 0.8); } /**覆盖mars3d内部控件的颜色等样式*/ .mars3d-compass .mars3d-compass-outer { fill: rgba(23, 49, 71, 0.8); } .mars3d-contextmenu-ul, .mars3d-sub-menu { background-color: rgba(23, 49, 71, 0.8); > li > a:hover, > li > a:focus, > li > .active { background-color: #3ea6ff; } > .active > a, > .active > a:hover, > .active > a:focus { background-color: #3ea6ff; } } /* Popup样式*/ .mars3d-popup-color { color: #ffffff; } .mars3d-popup-background { background: rgba(23, 49, 71, 0.8); } .mars3d-popup-content { margin: 15px; } .mars3d-template-content label { padding-right: 6px; } .mars3d-template-titile { border-bottom: 1px solid #3ea6ff; } .mars3d-template-titile a { font-size: 16px; } .mars3d-tooltip { background: rgba(23, 49, 71, 0.8); border: 1px solid rgba(23, 49, 71, 0.8); } .mars3d-popup-btn-custom { padding: 3px 10px; border: 1px solid #209ffd; background: #209ffd1c; } .mars-dialog .mars-dialog__content { height: 100%; width: 100%; overflow: auto; padding: 5px; } .image { border: solid 2px #fff; } .content { height: 90%; padding-top: 10px; overflow-x: auto; overflow-y: auto; } .content-text { padding: 0 10px; text-indent: 30px; font-size: 17px; } .details-video { width: 100%; height: 760px; background-color: #000; } :where(.css-lt97qq9).ant-space { display: inline-flex; } :where(.css-lt97qq9).ant-space-align-center { align-items: center; } :where(.css-lt97qq9).ant-image .ant-image-mask { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: #fff; background: rgba(0, 0, 0, 0.5); cursor: pointer; opacity: 0; transition: opacity 0.3s; } :where(.css-lt97qq9).ant-image .ant-image-mask .ant-image-mask-info { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; padding: 0 4px; } :where(.css-1t97qq9)[class^="ant-image"] [class^="ant-image"], :where(.css-1t97qq9)[class*=" ant-image"] [class^="ant-image"], :where(.css-1t97qq9)[class^="ant-image"] [class*=" ant-image"], :where(.css-1t97qq9)[class*=" ant-image"] [class*=" ant-image"] { box-sizing: border-box; } :where(.css-lt97qq9).ant-image .ant-image-img { width: 100%; height: auto; vertical-align: middle; } </style> <style scoped> .mini-map-container { position: relative; width: 100%; height: 100%; } .main-viewer { width: 100%; height: 100%; } .mini-map { position: absolute; right: 3vw; bottom: 6vh; width: 12vw; height: 17vh; border: 2px solid #fff; box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); z-index: 999; cursor: pointer; overflow: hidden; } .location-indicator { position: absolute; width: 14px; height: 14px; background: #ff3e3e; border: 2px solid white; border-radius: 50%; transform: translate(-50%, -50%); box-shadow: 0 0 15px rgba(255, 62, 62, 1); z-index: 100; } .view-rectangle { position: absolute; border: 2px solid #00f2fe; z-index: 99; pointer-events: none; box-shadow: 0 0 20px rgba(0, 242, 254, 0.7); } /* 相机聚焦样式 - 四个角折角 */ .corner { position: absolute; width: 25px; height: 25px; z-index: 100; pointer-events: none; } .corner::before, .corner::after { content: ""; position: absolute; background: #00f2fe; box-shadow: 0 0 10px rgba(0, 242, 254, 0.8); } .corner-top-left { top: -2px; left: -2px; } .corner-top-left::before { top: 0; left: 0; width: 15px; height: 3px; } .corner-top-left::after { top: 0; left: 0; width: 3px; height: 15px; } .corner-top-right { top: -2px; right: -2px; } .corner-top-right::before { top: 0; right: 0; width: 15px; height: 3px; } .corner-top-right::after { top: 0; right: 0; width: 3px; height: 15px; } .corner-bottom-left { bottom: -2px; left: -2px; } .corner-bottom-left::before { bottom: 0; left: 0; width: 15px; height: 3px; } .corner-bottom-left::after { bottom: 0; left: 0; width: 3px; height: 15px; } .corner-bottom-right { bottom: -2px; right: -2px; } .corner-bottom-right::before { bottom: 0; right: 0; width: 15px; height: 3px; } .corner-bottom-right::after { bottom: 0; right: 0; width: 3px; height: 15px; } .camera-icon { position: absolute; top: 10px; right: 10px; color: #00f2fe; font-size: 24px; z-index: 100; text-shadow: 0 0 10px rgba(0, 242, 254, 0.8); } .focus-effect { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 98; border: 2px solid rgba(0, 242, 254, 0.2); border-radius: 5px; box-shadow: inset 0 0 30px rgba(0, 242, 254, 0.1); } .pulse { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 10px; height: 10px; border-radius: 50%; background: rgba(0, 242, 254, 0.7); box-shadow: 0 0 0 0 rgba(0, 242, 254, 0.7); animation: pulse 2s infinite; } ::v-deep.cesium-viewer-toolbar { display: none; } </style> 如上代码,但是效果图中鹰眼地图加载了株洲遥感影像,但是鹰眼地图中其他部分就没了,呈现为全蓝色,而且红点也没有,不会随主地图变化红点,基于以上问题告诉我原因并修改代码
最新发布
07-07
import CircleRippleMaterialProperty from “./CircleRippleMaterialProperty”; // 从 public/circle.json 加载坐标数据 export async function loadRipplePoints() { const response = await fetch(“/circle.json”); // 注意路径是相对于 public 目录 return await response.json(); } // 创建多个波纹圆 export function createMultipleRippleCircles( viewer, ripplePoints, options = {} ) { const zIndex = options.zIndex || 1000; // 可选传入 zIndex ripplePoints.forEach((point) => { const position = Cesium.Cartesian3.fromDegrees( point.longitude, point.latitude ); viewer.entities.add({ name: point.name, position: position, ellipse: { semiMinorAxis: 5000.0, semiMajorAxis: 8000.0, height: 0, zIndex: zIndex, // 设置 zIndex 提升层级 material: new CircleRippleMaterialProperty({ color: Cesium.Color.fromCssColorString("#00FFFF").withAlpha(0.8), speed: 30.0, count: 2, gradient: 0.2, }), }, }); }); } 如图所示生成动态波纹圆代码,生成是生成了,但是波纹圆一旦放大就变得很模糊,看起来感觉断断续续的,有问题,你结合下面的vue文件找一些原因更改,但是注意最好不要更改vue文件,或者最小量更改: <div id="cesiumContainer"></div> <div ref="miniMapContainer" class="mini-map" @click="handleMiniMapClick"> <div class="location-indicator" :style="indicatorStyle"></div> <!-- 四个角折角 --> <div class="corner corner-top-left"></div> <div class="corner corner-top-right"></div> <div class="corner corner-bottom-left"></div> <div class="corner corner-bottom-right"></div> <!-- <div class="camera-icon">📷</div> --> <div class="focus-effect"></div> <div class="pulse"></div> </div> <Search /> <LocationBar v-if="loaded" :update-interval="100" :use-dms-format="useDmsFormat" /> </template> <style> /* @import "/temp/css/divGraphic.css"; */ </style> <script setup lang="ts"> import { computed, onUnmounted, onMounted, reactive } from "vue"; import LocationBar from "./location-bar.vue"; import Search from "./search.vue"; import initMap from "./init"; import { ref } from "vue"; import { loadRipplePoints, createMultipleRippleCircles } from './circle.js'; import { $ prototype } from "../../main.ts"; const miniMapContainer = ref<HTMLElement>(); let viewIndicator: Rectangle; // 视图指示器样式 const currentPosition = reactive({ longitude: 113.361538, latitude: 27.339318, }); // 更指示器位置 const updateIndicatorPosition = () => { if (!$ prototype.$ map) return; const camera = $ prototype.$ map.camera; const rect = camera.computeViewRectangle(); if (!rect) return; // 计算指示器在鹰眼中的位置 const miniMapWidth = miniMapContainer.value?.clientWidth || 200; const miniMapHeight = miniMapContainer.value?.clientHeight || 150; // 更CSS指示器(用于点击交互) const westPercent = (((rect.west * 180) / Math.PI + 180) / 360) * 100; const eastPercent = (((rect.east * 180) / Math.PI + 180) / 360) * 100; const southPercent = ((90 - (rect.south * 180) / Math.PI) / 180) * 100; const northPercent = ((90 - (rect.north * 180) / Math.PI) / 180) * 100; indicatorStyle.value = { left: `${westPercent}%`, top: `${northPercent}%`, width: `${eastPercent - westPercent}%`, height: `${southPercent - northPercent}%`, }; return rect; }; // 更鹰眼地图 const updateOverview = () => { if (!$ prototype.$ map || !overviewViewer.value) return; // 获取主地图的当前视图范围 const rectangle = $ prototype.$ map.camera.computeViewRectangle(); if (!rectangle) return; // 更当前中心位置 const center = Cesium.Rectangle.center(rectangle); currentPosition.longitude = Cesium.Math.toDegrees(center.longitude); currentPosition.latitude = Cesium.Math.toDegrees(center.latitude); // 计算视图矩形在鹰眼地图上的位置 const scene = overviewViewer.value.scene; const canvas = scene.canvas; const southwest = Cesium.Cartesian3.fromRadians( rectangle.west, rectangle.south ); const northeast = Cesium.Cartesian3.fromRadians( rectangle.east, rectangle.north ); const swPixel = Cesium.SceneTransforms.wgs84ToWindowCoordinates( scene, southwest ); const nePixel = Cesium.SceneTransforms.wgs84ToWindowCoordinates( scene, northeast ); if (!swPixel || !nePixel) return; // 更视图矩形 viewRectangle.width = Math.abs(nePixel.x - swPixel.x); viewRectangle.height = Math.abs(nePixel.y - swPixel.y); viewRectangle.left = Math.min(swPixel.x, nePixel.x); viewRectangle.top = Math.min(swPixel.y, nePixel.y); syncView(); }; const overviewViewer = ref(null); const initMiniMap = () => { Cesium.Ion.defaultAccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxMDhlNDdmYy03NzFhLTQ1ZTQtOWQ3NS1lZDAzNDc3YjE4NDYiLCJpZCI6MzAxNzQyLCJpYXQiOjE3NDcwNTMyMDN9.eaez8rQxVbPv2LKEU0sMDclPWyHKhh1tR27Vg-_rQSM"; if (!miniMapContainer.value) return; // 鹰眼地图初始化 overviewViewer.value = new Cesium.Viewer(miniMapContainer.value, { sceneMode: Cesium.SceneMode.SCENE2D, baseLayerPicker: false, homeButton: false, timeline: false, navigationHelpButton: false, animation: false, scene3DOnly: true, selectionIndicator: false, infoBox: false, imageryProvider: new Cesium.ArcGisMapServerImageryProvider({ url: "https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer", }), terrainProvider: window.Cesium.createWorldTerrain(), }); var toolbar = overviewViewer.value.container.getElementsByClassName( "cesium-viewer-toolbar" )[0]; if (toolbar) { toolbar.style.display = "none"; } // 隐藏鹰眼控件 overviewViewer.value.cesiumWidget.creditContainer.style.display = "none"; // 设置鹰眼固定视角 // overviewViewer.value.camera.setView({ // destination: new Cesium.Cartesian3( // -2432812.6687511606, // 5559483.804371395, // 2832009.419525571 // ), // }); }; const syncView = () => { if (!$ prototype.$ map || !overviewViewer.value) return; const rectangle = $ prototype.$ map.camera.computeViewRectangle(); if (!rectangle) return; // 鹰眼地图飞往相同范围 overviewViewer.value.camera.flyTo({ destination: Cesium.Rectangle.fromDegrees( Cesium.Math.toDegrees(rectangle.west), Cesium.Math.toDegrees(rectangle.south), Cesium.Math.toDegrees(rectangle.east), Cesium.Math.toDegrees(rectangle.north) ), duration: 1.5, }); }; function initRectangle() { overviewViewer.value.camera.flyTo({ destination: Cesium.Cartesian3.fromDegrees(113.200224, 27.004546, 50000), orientation: { heading: 3.1769448901508976, pitch: -0.2880443992926125, roll: 6.283184370499525, }, duration: 3.0, // 飞行时间() }); // 创建视图指示器 viewIndicator = overviewViewer.value.entities.add({ rectangle: { // coordinates: new window.Cesium.CallbackProperty( // updateIndicatorPosition, // false // ), coordinates: new Cesium.CallbackProperty(function () { // 必须返回 Cesium.Rectangle 对象 return new Cesium.Rectangle( Cesium.Math.toRadians(113.125), // 西经 Cesium.Math.toRadians(26.9541), // 南纬 Cesium.Math.toRadians(113.2542), // 东经 Cesium.Math.toRadians(27.2545225) // 北纬 ); }, false), // false 表示不持续更(性能优化) material: Cesium.Color.RED.withAlpha(0.3), outline: true, outlineColor: Cesium.Color.RED, outlineWidth: 2, }, }); overviewViewer.value.flyTo(viewIndicator, { duration: 2, // 飞行持续时间(秒) offset: new Cesium.HeadingPitchRange( Cesium.Math.toRadians(0), // 朝向角度(0表示正北) Cesium.Math.toRadians(-45), // 俯仰角度(-45度俯视) 1000000 // 距离目标的距离(米) ), }); console.log(overviewViewer.value.entities); } const viewRectangle = reactive({ width: 0, height: 0, left: 0, top: 0, }); // 指示器样式计算 const indicatorStyle = computed(() => { if (!overviewViewer.value) return {}; // 将经纬度转换为屏幕坐标 const position = Cesium.Cartesian3.fromDegrees( currentPosition.longitude, currentPosition.latitude ); const scene = overviewViewer.value.scene; const canvas = scene.canvas; const pixel = Cesium.SceneTransforms.wgs84ToWindowCoordinates( scene, position ); if (!pixel) return { display: "none" }; return { left: `${pixel.x}px`, top: `${pixel.y}px`, display: "block", }; }); // 视图矩形样式计算 const rectangleStyle = computed(() => { return { width: `${viewRectangle.width}px`, height: `${viewRectangle.height}px`, left: `${viewRectangle.left}px`, top: `${viewRectangle.top}px`, display: viewRectangle.width > 0 ? "block" : "none", }; }); const loaded = ref(false); const useDmsFormat = ref(false); function addDemoGraphics() { const chinaBoundary = $ prototype.$ map.dataSources.add( Cesium.GeoJsonDataSource.load("/shp_zz.geojson", { stroke: Cesium.Color.WHITE, fill: false, clampToGround: true, describe: null, // 禁用默认样式描述 }) ); // 添加标签 chinaBoundary.then((dataSource) => { const entities = dataSource.entities.values; for (let entity of entities) { if (entity.polyline) { entity.polyline.fill = false; // entity.polyline.material.color = Cesium.Color.BLACK; // 彻底移除材质 } } }); } function flyToDes() { const center = Cesium.Cartesian3.fromDegrees(-98.0, 40.0); // map.camera.lookAt(center, new Cesium.Cartesian3(0.0, -4790000.0, 3930000.0)); // 第一视角飞行 84.330408,38.24518 $ prototype.$ map.camera.flyTo({ destination: new Cesium.Cartesian3( -2432812.6687511606, 5559483.804371395, 2832009.419525571 ), orientation: { heading: 6.283185307179421, pitch: -1.0472145569408116, roll: 6.2831853071795205, }, complete: function () { // map.camera.lookAt( // Cesium.Cartesian3.fromDegrees(113.300224, 27.004546, 500), // new Cesium.HeadingPitchRange( // 3.1769448901508976, // -0.2880443992926125, // 500 // ) // ); // map.camera.flyTo({ // destination: Cesium.Cartesian3.fromDegrees(113.300224, 27.004546, 500), // orientation: { // heading: 3.1769448901508976, // pitch: -0.2880443992926125, // roll: 6.283184370499525, // }, // duration: 3.0, // 飞行时间() // }); }, }); } // 监听主地图相机变化 const setupCameraListener = () => { $ prototype.$ map.camera.changed.addEventListener(updateOverview); // viewIndicator.rectangle.coordinates = updateIndicatorPosition(); }; const handleMiniMapClick = (event: MouseEvent) => { if (!miniMapContainer.value) return; const rect = miniMapContainer.value.getBoundingClientRect(); const x = event.clientX - rect.left; const y = event.clientY - rect.top; // 计算点击位置的经纬度 const lon = (x / rect.width) * 360 - 180; const lat = 90 - (y / rect.height) * 180; // 主地图飞向点击位置 $ prototype.$ map.camera.flyTo({ destination: Cesium.Cartesian3.fromDegrees(lon, lat, 1000000), }); }; function addImage() { var rightImageProvider = new Cesium.UrlTemplateImageryProvider({ name: "影像图", type: "xyz", layer: "vec_d", url: "http://124.232.190.30:9000/proxy/pk1725866655224/map/zzzsyx_18/{z}/{x}/{y}.png", minimumLevel: 1, maximumLevel: 17, crs: "EPSG:3857", }); $ prototype.$ map.imageryLayers.addImageryProvider(rightImageProvider); rightImageProvider.splitDirection = Cesium.SplitDirection.right; } onMounted(() => { // console.clear() initMap(); addImage(); loaded.value = true; addDemoGraphics(); flyToDes(); initMiniMap(); setupCameraListener(); setTimeout(function () { initRectangle(); }, 2000); // 增部分:加载并创建波纹圆(不影响其他逻辑) (async () => { try { const ripplePoints = await loadRipplePoints(); createMultipleRippleCircles($ prototype.$ map, ripplePoints); // 注意这里没有空格 } catch (error) { console.error('加载波纹圆失败:', error); } })(); //测试加载wmts服务的geojson格式 //此处很重要,很重要如果是4326的话就需要,如果不是4326是900913就不需要下面的了 // var options = { // url: "http://localhost:8080/geoserver/zhuzhou/gwc/service/wmts", // layer: "zhuzhou:lukou_farmland", // name: "zhuzhou:lukou_farmland", // show: true, // alpha: 1.0, // serviceType: "wmts", // type: "raster", // // rectangle: layerData.rectangle, // minimumLevel: 1, // maximumLevel: 14, // tileMatrixSetID: "EPSG:4326", // style: "", // format: "application/json;type=geojson", // }; // options.tileMatrixLabels = [...Array(20).keys()].map((level) => // ("EPSG:4326:" + level).toString() // ); // if (options.tileMatrixSetID == "EPSG:4326") { // options.tilingScheme = new Cesium.GeographicTilingScheme({ // numberOfLevelZeroTilesX: 2, // numberOfLevelZeroTilesY: 1, // }); // } // const provider = new Cesium.WebMapTileServiceImageryProvider(options); // // $ prototype.$ map.imageryLayers.remove( // // $ prototype.$ map.imageryLayers._layers[0] // // ); // $ prototype.$ map!.imageryLayers.addImageryProvider(provider); }); onUnmounted(() => { if ($ prototype.$ map) { $ prototype.$ map.destroy(); $ prototype.$ map = null; } console.log("组件销毁"); }); // onload事件将在地图渲染后触发 const emit = defineEmits(["onload", "onclick"]); const initMars3d = async (option: any) => { emit("onclick", true); emit("onload", $ prototype.$ map); }; </script> <style lang="less"> /**cesium 工具按钮栏*/ .cesium-viewer-toolbar { top: auto !important; bottom: 35px !important; left: 12px !important; right: auto !important; } .cesium-toolbar-button img { height: 100%; } .cesium-viewer-toolbar > .cesium-toolbar-button, .cesium-navigationHelpButton-wrapper, .cesium-viewer-geocoderContainer { margin-bottom: 5px; float: left; clear: both; text-align: center; } .cesium-button { background-color: rgba(23, 49, 71, 0.8); color: #e6e6e6; fill: #e6e6e6; box-shadow: 0 1px 4px rgba(0, 0, 0, 0.3); line-height: 32px; } .cesium-button:hover { background: #3ea6ff; } /**cesium 底图切换面板*/ .cesium-baseLayerPicker-dropDown { bottom: 0; left: 40px; max-height: 700px; margin-bottom: 5px; background-color: rgba(23, 49, 71, 0.8); } /**cesium 帮助面板*/ .cesium-navigation-help { top: auto; bottom: 0; left: 40px; transform-origin: left bottom; background: none; background-color: rgba(23, 49, 71, 0.8); .cesium-navigation-help-instructions { background: none; } .cesium-navigation-button { background: none; } .cesium-navigation-button-selected, .cesium-navigation-button-unselected:hover { background: rgba(0, 138, 255, 0.2); } } /**cesium 二维三维切换*/ .cesium-sceneModePicker-wrapper { width: auto; } .cesium-sceneModePicker-wrapper .cesium-sceneModePicker-dropDown-icon { float: right; margin: 0 3px; } /**cesium POI查询输入框*/ .cesium-viewer-geocoderContainer .search-results { left: 0; right: 40px; width: auto; z-index: 9999; } .cesium-geocoder-searchButton { background-color: rgba(23, 49, 71, 0.8); } .cesium-viewer-geocoderContainer .cesium-geocoder-input { background-color: rgba(63, 72, 84, 0.7); } .cesium-viewer-geocoderContainer .cesium-geocoder-input:focus { background-color: rgba(63, 72, 84, 0.9); } .cesium-viewer-geocoderContainer .search-results { background-color: rgba(23, 49, 71, 0.8); } /**cesium info信息框*/ .cesium-infoBox { top: 50px; background-color: rgba(23, 49, 71, 0.8); } .cesium-infoBox-title { background-color: rgba(23, 49, 71, 0.8); } /**cesium 任务栏的FPS信息*/ .cesium-performanceDisplay-defaultContainer { top: auto; bottom: 35px; right: 50px; } .cesium-performanceDisplay-ms, .cesium-performanceDisplay-fps { color: #fff; } /**cesium tileset调试信息面板*/ .cesium-viewer-cesiumInspectorContainer { top: 10px; left: 10px; right: auto; } .cesium-cesiumInspector { background-color: rgba(23, 49, 71, 0.8); } /**覆盖mars3d内部控件的颜色等样式*/ .mars3d-compass .mars3d-compass-outer { fill: rgba(23, 49, 71, 0.8); } .mars3d-contextmenu-ul, .mars3d-sub-menu { background-color: rgba(23, 49, 71, 0.8); > li > a:hover, > li > a:focus, > li > .active { background-color: #3ea6ff; } > .active > a, > .active > a:hover, > .active > a:focus { background-color: #3ea6ff; } } /* Popup样式*/ .mars3d-popup-color { color: #ffffff; } .mars3d-popup-background { background: rgba(23, 49, 71, 0.8); } .mars3d-popup-content { margin: 15px; } .mars3d-template-content label { padding-right: 6px; } .mars3d-template-titile { border-bottom: 1px solid #3ea6ff; } .mars3d-template-titile a { font-size: 16px; } .mars3d-tooltip { background: rgba(23, 49, 71, 0.8); border: 1px solid rgba(23, 49, 71, 0.8); } .mars3d-popup-btn-custom { padding: 3px 10px; border: 1px solid #209ffd; background: #209ffd1c; } .mars-dialog .mars-dialog__content { height: 100%; width: 100%; overflow: auto; padding: 5px; } .image { border: solid 2px #fff; } .content { height: 90%; padding-top: 10px; overflow-x: auto; overflow-y: auto; } .content-text { padding: 0 10px; text-indent: 30px; font-size: 17px; } .details-video { width: 100%; height: 760px; background-color: #000; } :where(.css-lt97qq9).ant-space { display: inline-flex; } :where(.css-lt97qq9).ant-space-align-center { align-items: center; } :where(.css-lt97qq9).ant-image .ant-image-mask { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: #fff; background: rgba(0, 0, 0, 0.5); cursor: pointer; opacity: 0; transition: opacity 0.3s; } :where(.css-lt97qq9).ant-image .ant-image-mask .ant-image-mask-info { overflow: hidden; white-space: nowrap; text-overflow: ellipsis; padding: 0 4px; } :where(.css-1t97qq9)[class^="ant-image"] [class^="ant-image"], :where(.css-1t97qq9)[class*=" ant-image"] [class^="ant-image"], :where(.css-1t97qq9)[class^="ant-image"] [class*=" ant-image"], :where(.css-1t97qq9)[class*=" ant-image"] [class*=" ant-image"] { box-sizing: border-box; } :where(.css-lt97qq9).ant-image .ant-image-img { width: 100%; height: auto; vertical-align: middle; } </style> <style scoped> .mini-map-container { position: relative; width: 100%; height: 100%; } .main-viewer { width: 100%; height: 100%; } .mini-map { position: absolute; right: 3vw; bottom: 6vh; width: 12vw; height: 17vh; border: 2px solid #fff; box-shadow: 0 0 10px rgba(0, 0, 0, 0.5); z-index: 999; cursor: pointer; overflow: hidden; } .location-indicator { position: absolute; width: 14px; height: 14px; background: #ff3e3e; border: 2px solid white; border-radius: 50%; transform: translate(-50%, -50%); box-shadow: 0 0 15px rgba(255, 62, 62, 1); z-index: 100; } .view-rectangle { position: absolute; border: 2px solid #00f2fe; z-index: 99; pointer-events: none; box-shadow: 0 0 20px rgba(0, 242, 254, 0.7); } /* 相机聚焦样式 - 四个角折角 */ .corner { position: absolute; width: 25px; height: 25px; z-index: 100; pointer-events: none; } .corner::before, .corner::after { content: ""; position: absolute; background: #00f2fe; box-shadow: 0 0 10px rgba(0, 242, 254, 0.8); } .corner-top-left { top: -2px; left: -2px; } .corner-top-left::before { top: 0; left: 0; width: 15px; height: 3px; } .corner-top-left::after { top: 0; left: 0; width: 3px; height: 15px; } .corner-top-right { top: -2px; right: -2px; } .corner-top-right::before { top: 0; right: 0; width: 15px; height: 3px; } .corner-top-right::after { top: 0; right: 0; width: 3px; height: 15px; } .corner-bottom-left { bottom: -2px; left: -2px; } .corner-bottom-left::before { bottom: 0; left: 0; width: 15px; height: 3px; } .corner-bottom-left::after { bottom: 0; left: 0; width: 3px; height: 15px; } .corner-bottom-right { bottom: -2px; right: -2px; } .corner-bottom-right::before { bottom: 0; right: 0; width: 15px; height: 3px; } .corner-bottom-right::after { bottom: 0; right: 0; width: 3px; height: 15px; } .camera-icon { position: absolute; top: 10px; right: 10px; color: #00f2fe; font-size: 24px; z-index: 100; text-shadow: 0 0 10px rgba(0, 242, 254, 0.8); } .focus-effect { position: absolute; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 98; border: 2px solid rgba(0, 242, 254, 0.2); border-radius: 5px; box-shadow: inset 0 0 30px rgba(0, 242, 254, 0.1); } .pulse { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 10px; height: 10px; border-radius: 50%; background: rgba(0, 242, 254, 0.7); box-shadow: 0 0 0 0 rgba(0, 242, 254, 0.7); animation: pulse 2s infinite; } ::v-deep.cesium-viewer-toolbar { display: none; } </style> 还有同时结合 // CircleRippleMaterialProperty.js // import * as Cesium from 'cesium'; class CircleRippleMaterialProperty { constructor(options = {}) { this._definitionChanged = new Cesium.Event(); this._color = Cesium.defaultValue(options.color, Cesium.Color.BLUE); this._speed = Cesium.defaultValue(options.speed, 5.0); this._count = Cesium.defaultValue(options.count, 4); this._gradient = Cesium.defaultValue(options.gradient, 0.2); } get isConstant() { return false; } get definitionChanged() { return this._definitionChanged; } get color() { return this._color; } set color(value) { this._color = value; } get speed() { return this._speed; } set speed(value) { this._speed = value; } get count() { return this._count; } set count(value) { this._count = value; } get gradient() { return this._gradient; } set gradient(value) { this._gradient = value; } getType() { return 'CircleRipple'; } getValue(time, result) { if (!result) result = {}; result.color = this._color; result.speed = this._speed; result.count = this._count; result.gradient = this._gradient; return result; } equals(other) { return this === other || (other instanceof CircleRippleMaterialProperty && Cesium.Color.equals(this._color, other._color) && this._speed === other._speed && this._count === other._count && this._gradient === other._gradient); } } // 注册材质类型 Cesium.Material.CircleRippleType = 'CircleRipple'; Cesium.Material.CircleRippleSource = ` uniform vec4 color; uniform float speed; uniform float count; uniform float gradient; czm_material czm_getMaterial(czm_materialInput materialInput) { czm_material material = czm_getDefaultMaterial(materialInput); vec2 st = materialInput.st; float time = czm_frameNumber * speed / 1000.0; float d = distance(st, vec2(0.5, 0.5)); // 多圈波纹效果 float alpha = 0.0; for(float i = 0.0; i < count; i++) { float ripple = sin(d * 20.0 - time * 2.0 - i * 0.5); float fade = smoothstep(0.0, 0.3, d) * (1.0 - smoothstep(0.3, 0.5, d)); alpha += abs(ripple) * fade * pow(1.0 - d, gradient * 10.0); } material.alpha = alpha * color.a; material.diffuse = mix(color.rgb, vec3(1.0), d * 0.5); return material; }`; Cesium.Material._materialCache.addMaterial(Cesium.Material.CircleRippleType, { fabric: { type: Cesium.Material.CircleRippleType, uniforms: { color: new Cesium.Color(0.0, 0.8, 1.0, 0.7), speed: 5.0, count: 4.0, gradient: 0.2 }, source: Cesium.Material.CircleRippleSource }, translucent: function() { return true; } }); export default CircleRippleMaterialProperty; 加上这个circleRippleMaterialProperty.js怎么修改
07-06
function https(url,data,fu){ $.ajax({ contentType:"application/json", url: url, // 假设后端 API 地址 method: "POST", data: JSON.stringify(data), type: "json", dataType: "json", success:function(e){ console.log(e.data) if(e.status==200){ console.log(e.data) fu(e.data) }else{ alert(e.text) } }, error: function (e) { console.log(e.data) console.error(e) alert("请求失败,请稍后再试!"+e); } }); } function checkLoginStatus() { if (window.location.href.includes('/login.html')) return; } window.addEventListener('beforeunload', function(e) { console.trace('触发页面跳转的堆栈跟踪:'); }); //安全验证函数 function validateUserSession() { try { // 防御性数据获取 + 数据清洗 const rawValue = localStorage.getItem("name"); const username = String(rawValue ?? '') .trim() .replace(/[\u200B-\u200D\uFEFF]/g, ''); // 移除零宽字符 // 调试信息 console.log('[Auth] Raw:', rawValue, 'Processed:', username); // 复合验证条件 const isValid = ( username.length >= 2 && // 最小长度要求 !/[<>]/.test(username) && // 防止XSS username !== 'null' && username !== 'undefined' ); if (!isValid) { console.warn('无效用户标识:', username); // 安全跳转方法 //window.location.replace('/KuCun2/login.html'); // 立即终止执行 return Promise.reject('Invalid session'); } // 返回清洗后的用户名 return username; } catch (error) { console.error('会话验证失败:', error); // window.location.replace('/KuCun2/login.html'); return Promise.reject(error); } } function deepMergeArrays(frontend, backend) { const resultMap = new Map(); // 遍历前端数据并存入 Map 中以便快速查找 frontend.forEach(item => resultMap.set(item.id, { ...item })); // 遍历后端数据并与前端数据进行合并 backend.forEach(item => { if (resultMap.has(item.id)) { // 如果存在相同 ID,则合并两者的内容 resultMap.set( item.id, Object.assign(resultMap.get(item.id), item) ); } else { // 如果不存在相同 ID,则增该条目 resultMap.set(item.id, { ...item }); } }); // 将最终结果转回数组形式 return Array.from(resultMap.values()); } (function ($){ // 页面加载时检查登录状态 checkLoginStatus(); })(jQuery); function removeSpecificCharactersAndConvertToNumber(str, charsToRemove) { const regex = new RegExp(`[${charsToRemove}]`, 'g'); // 创建用于匹配指定字符的正则表达式 const cleanedStr = str.replace(regex, ''); // 移除指定字符 const numberValue = parseFloat(cleanedStr); // 转换为浮点数 return isNaN(numberValue) ? null : numberValue; // 如果无法解析,则返回 null } <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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>KuCun2</groupId> <artifactId>KuCun2</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>KuCun2</name> <description/> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.12.RELEASE</version> <!-- 请根据需要选择版本 --> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <webVersion>4.0</webVersion> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <protobuf.version>3.21.12</protobuf.version> </properties> <dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>8.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.servlet.jsp.jstl</artifactId> <version>1.2.4</version> </dependency> <!-- Spring Boot Starter Data JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> <exclusions> <exclusion> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> </exclusion> </exclusions> </dependency> <!-- Optional: Lombok for reducing boilerplate code --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> </dependency> <!-- Jackson Databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <!-- Jackson Core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> </dependency> <!-- Jackson Annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> </dependency> <dependency> <groupId>org.mindrot</groupId> <artifactId>jbcrypt</artifactId> <version>0.4</version> </dependency> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>${protobuf.version}</version> </dependency> <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.30</version> <!-- 统一版本号 --> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <compilerArgs> <arg>-parameters</arg> </compilerArgs> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project> package com.kucun; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication( ) public class DemoApplication extends SpringBootServletInitializer { public static void main(String[] args) { // // ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args); // Arrays.stream(ctx.getBeanNamesForType(SecurityFilterChain.class)) // .forEach(System.out::println); // // // // 测试密码加密示例 // BCryptPasswordEncoder encoder = new BCrypt(); // String rawPassword = "987987"; // String encodedPassword = encoder.encode(rawPassword); // System.out.println("加密后的密码:" + encodedPassword); SpringApplication.run(DemoApplication.class, args); } }package com.kucun.Config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.kucun.Config.Role.RoleConverter; import com.kucun.Config.user.CustomUserDetails; import com.kucun.data.entity.User; import com.kucun.dataDo.UserRepository; /** * 获取数据 * @author Administrator * */ @Service public class CustomUserDetailsService/* implements UserDetailsService */{ // // @Autowired // private UserRepository userRepository; // // @Autowired // private RoleConverter roleConverter; // // public CustomUserDetailsService() { // // super(); // System.out.println("11111"); // } ///** // * 获取数据库中用户信息 // * @param andy 账号 // * // * @return // * // */ // @Override // public UserDetails loadUserByUsername(String andy) { // System.out.println(andy); // User user = userRepository.findByAndy(andy); // System.out.println(user); // return new CustomUserDetails(user, // roleConverter.convert(user.getRole()) // 关键转换点[^1] // ); // } }package com.kucun.Config; // 2. 基础安全配置 //@Configuration //@EnableWebSecurity // 启用Web安全功能 public class SecurityConfig //extends WebSecurityConfigurerAdapter { // @Override // public void configure(WebSecurity web) { // web.ignoring().antMatchers("/check-session"); // } // // 添加自定义Controller // @RestController // public static class SessionCheckController { // @GetMapping("/check-session") // public ResponseEntity<?> checkSession(HttpServletRequest request) { // return request.getSession(false) != null ? // ResponseEntity.ok().build() : // ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); // } // } // /** // * 核心安全过滤器链配置 // * @param http HTTP安全构建器 // * @return 安全过滤器链 // * @throws Exception 配置异常 // * // * █ 配置逻辑说明: // * 1. authorizeHttpRequests: 定义访问控制规则 // * 2. formLogin: 配置表单登录 // * 3. logout: 配置注销行为 // * 4. exceptionHandling: 处理权限异常[^3] // */ // // // 修正后的配置方法 // @Override // protected void configure(HttpSecurity http) throws Exception { // // // // http // .csrf().disable() // .sessionManagement() // .sessionCreationPolicy(SessionCreationPolicy.ALWAYS) // .invalidSessionUrl("/login.html?session=invalid") // .maximumSessions(1) // .maxSessionsPreventsLogin(false) // .and() // .and() // .addFilterBefore(jsonAuthFilter(), UsernamePasswordAuthenticationFilter.class) // 关键配置 // .authorizeRequests() // .antMatchers("/login.html", "/users/login").permitAll() // .antMatchers("/js/**", "/css/**", "/fonts/**", "/images/**","/check-session","/main/bootstrap-3.3.7-dist/**").permitAll() // .antMatchers("/users/guanli/**").hasAuthority("ROLE_ADMIN") // .anyRequest().authenticated() // .and() // .formLogin().disable() //// .loginPage("/login.html") //// .loginProcessingUrl("/users/login") //// //// .successHandler(ajaxAuthenticationSuccessHandler()) // 自定义成功处理器 //// .failureHandler(ajaxAuthenticationFailureHandler()) // 自定义失败处理器 //// .defaultSuccessUrl("/index.html") //// .failureUrl("/login.html?error=true") //// .usernameParameter("andy") // 修改用户名参数名 //// .passwordParameter("pass") // 修改密码参数名 //// .and() // // .logout() // .logoutUrl("/logout") // .logoutSuccessUrl("/login.html") // .and() // .csrf() // .ignoringAntMatchers("/users/login") // .and() // .headers() // .frameOptions().sameOrigin() // .and() // .exceptionHandling() // .accessDeniedHandler(accessDeniedHandler()); // 统一使用Handler // } // // // // // // // 返回JSON格式的成功响应 // @Bean // public AuthenticationSuccessHandler ajaxAuthenticationSuccessHandler() { // return (request, response, authentication) -> { // // // // // 强制创建服务端会话 // request.getSession(true); // // // // // String contextPath = request.getContextPath(); // HttpSession session = request.getSession(true); // Cookie cookie = new Cookie("JSESSIONID", session.getId()); // cookie.setPath(contextPath.isEmpty() ? "/" : contextPath + "/"); // cookie.setMaxAge(1800); // 30分钟 // response.addCookie(cookie); // // // //构建安全响应数据 // Map<String, Object> responseData = new HashMap<>(); // responseData.put("sessionId", request.getSession().getId()); // responseData.put("userInfo",Collections.unmodifiableMap(new HashMap<String, Object>() {/** // * // */ // private static final long serialVersionUID = 1L; // // { // put("Name", ((CustomUserDetails)authentication.getPrincipal()).getName()); // put("role", ((CustomUserDetails)authentication.getPrincipal()).getRole()); // }})); // // // // // 统一返回JSON格式 // response.setContentType(MediaType.APPLICATION_JSON_VALUE); // // new ObjectMapper().writeValue(response.getWriter(), responseData); // // // // // // // // // // response.setContentType(MediaType.APPLICATION_JSON_VALUE); // CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal(); // // response.setStatus(HttpStatus.OK.value()); // System.out.println(authentication.getPrincipal()+""+authentication.getName()); // // if (request.getHeader("X-Requested-With") == null) { // 非AJAX请求 // response.sendRedirect("/index.html"); // } else { // // //String re=userDetails.getUser().toString() // new ObjectMapper().writeValue(response.getWriter(), userDetails.getUser() // ); // // } // // // // // // // }; // } // // // 返回401状态码和错误信息 // @Bean // public AuthenticationFailureHandler ajaxAuthenticationFailureHandler() { // return (request, response, exception) -> { // if (request.getHeader("X-Requested-With") == null) { // response.sendRedirect("/login.html?error=true"); // } else { // response.setStatus(HttpStatus.UNAUTHORIZED.value()); // response.getWriter().write("{\"error\":\"Authentication failed\"}"); // } // }; // } // // // 处理未认证请求 // @Bean // public AuthenticationEntryPoint ajaxAuthenticationEntryPoint() { // return (request, response, exception) -> { // if (request.getHeader("X-Requested-With") == null) { // response.sendRedirect("/login.html?error=true"); // } else { // response.setStatus(HttpStatus.UNAUTHORIZED.value()); // response.getWriter().write("{\"error\":\"Authentication failed\"}"); // } // }; // } // // // // // // @Bean // public JsonUsernamePasswordAuthenticationFilter jsonAuthFilter() throws Exception { // // JsonUsernamePasswordAuthenticationFilter filter = // new JsonUsernamePasswordAuthenticationFilter(); // filter.setAuthenticationManager(authenticationManagerBean()); // filter.setUsernameParameter("andy"); // 设置自定义参数名 // filter.setPasswordParameter("pass"); // filter.setFilterProcessesUrl("/users/login"); // filter.setAuthenticationSuccessHandler(ajaxAuthenticationSuccessHandler()); // filter.setAuthenticationFailureHandler(ajaxAuthenticationFailureHandler()); // // return filter; // } // // // /** // * 密码编码器(必须配置) // * 使用BCrypt强哈希算法加密 // */ // @Bean // public PasswordEncoder passwordEncoder() { // return new BCryptPasswordEncoder(); // } // // // @Bean // public AccessDeniedHandler accessDeniedHandler() { // System.out.println("0000"); // return (request, response, ex) -> { // if (!response.isCommitted()) { // response.sendRedirect("/error/403"); // } // }; // } // // //} // // // // // // //class JsonUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter { // private final ObjectMapper objectMapper = new ObjectMapper(); // // @Override // public Authentication attemptAuthentication(HttpServletRequest request, // HttpServletResponse response) // throws AuthenticationException { // System.out.println("收到认证请求,路径:" + request.getRequestURI()); // System.out.println("请求方法:" + request.getMethod()); // System.out.println("Content-Type:" + request.getContentType()); // if (request.getContentType() != null && // request.getContentType().startsWith(MediaType.APPLICATION_JSON_VALUE)) { // // try (InputStream is = request.getInputStream()) { // Map<String, String> authMap = objectMapper.readValue(is, Map.class); // // String username = authMap.getOrDefault(getUsernameParameter(), ""); // String password = authMap.getOrDefault(getPasswordParameter(), ""); // // // 调试日志 // System.out.println("Authentication attempt with: " + username+'_'+ password); // // UsernamePasswordAuthenticationToken authRequest = // new UsernamePasswordAuthenticationToken(username, password); // // setDetails(request, authRequest); // return this.getAuthenticationManager().authenticate(authRequest); // } catch (IOException e) { // throw new AuthenticationServiceException("认证请求解析失败", e); // } // } // Authentication aut= super.attemptAuthentication(request, response); // System.out.println("结果:"+aut.isAuthenticated()); // // return aut; // } } package com.kucun.Config.Role; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.json.Json; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** * 权限转化 * @author Administrator * */ @Component public class RoleConverter { // private static final Map<Integer, String> ROLE_MAP = new HashMap<>(); // // @PostConstruct // public void init() { // ROLE_MAP.put(0, "ROLE_ADMIN"); // ROLE_MAP.put(1, "ROLE_USER"); // ROLE_MAP.put(2, "ROLE_MANAGER"); // ROLE_MAP.put(3, "ROLE_AUDITOR"); // } // // public List<GrantedAuthority> convert(int roleCode) { // ObjectMapper mapper = new ObjectMapper(); // try { // System.out.println(mapper.writeValueAsString(Collections.singletonList( // new SimpleGrantedAuthority(ROLE_MAP.getOrDefault(roleCode, "ROLE_GUEST")))).toString());//输出[{"authority":"ROLE_ADMIN"}] // } catch (JsonProcessingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return Collections.singletonList( // new SimpleGrantedAuthority(ROLE_MAP.getOrDefault(roleCode, "ROLE_GUEST")) // ); // } // }package com.kucun.Config.user; import java.util.Collection; import com.kucun.data.entity.User; public class CustomUserDetails /*implements UserDetails*/ { // /** // * // */ // private static final long serialVersionUID = 1L; // private final String andy; // 对应andy字段 // private final String name; // private final int role; // private final String password; // private final User users; // private final Collection<? extends GrantedAuthority> authorities; // // public CustomUserDetails(User user, Collection<? extends GrantedAuthority> authorities) { // this.andy = user.getAndy(); // this.name = user.getName(); // this.role = user.getRole(); // this.password = user.getPass(); // user.setPass(null); // this.users=user; // this.authorities = authorities; // } // // // 实现UserDetails接口方法 // @Override public String getUsername() { return andy; } // @Override public String getPassword() { return password; } // @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } // // // 自定义字段访问方法 // public String getName() { return name; } // public User getUser() { return users; } // public int getRole() { return role; } // // // 其他必要方法 // @Override public boolean isAccountNonExpired() { return true; } // @Override public boolean isAccountNonLocked() { return true; } // @Override public boolean isCredentialsNonExpired() { return true; } // @Override public boolean isEnabled() { return true; } } <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"> <title>峤丞板材库存管理</title> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="css/util.css"> <link rel="stylesheet" type="text/css" href="css/main.css"> <link rel="stylesheet" type="text/css" href="css/index2.css"> <style type="text/css"> *{ margin:0; padding:0; } .frame-header { height: 60px; background-color: #23262E; justify-content: space-between; } .frame-header-li{ font-family: Arial, Helvetica, sans-serif; font-size:40px; } .frame-ul{ } .frame-ul li{ border-style: solid; border-width:1px 0px 1px 0px; margin-top: 1px; height: 35px; text-align: center } #username{ position: absolute; right: 0; /* 靠右 */ } .frame-body { position: fixed; top: 60px; right: 0; bottom: 0; left: 0; display: flex; flex-direction: row; } .frame-side { scrollbar-width: none; /* firefox隐藏滚动条 */ -ms-overflow-style: none; /* IE 10+隐藏滚动条 */ overflow-x: hidden; overflow-y: auto; width: 200px; background-color:#9e5; } .frame-side::-webkit-scrollbar { display: none; /* Chrome Safari 隐藏滚动条*/ } .frame-main { flex-grow: 1; background-color:#fff; } .jiaoluo{ margin: auto; margin-right: 0px; } </style> </head> <body> <div class="frame-header"> <a class='frame-header-li' style="color:#fff">峤丞木材仓库管理</a> <a id="username" class='frame-header-li' style="color:#520">峤丞木材仓库管理</a> <button class=".menu-button" style="">注销</button> </div> <div class="frame-body"> <div class="frame-side"> <ul class='frame-ul' style="text-align:center;"> <li ><a href="main/test.html" target="main">首页</a></li> <li><a href="main/LuRul.html" target="main">材料录入</a></li> <li><a href="main/Guanli.html" target="main">材料录入</a></li> </ul> </div> <div class="frame-main"> <!-- 内容主体区域 --> <iframe id="iframeid" name="main" src="main/index.html" width="100%" height="100%" frameborder="0"> </iframe> </div> </div> </body> <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="js/jsyilai.js"></script> </html><!DOCTYPE html> <html lang="zh-CN"> <head> <title>扁平简洁的登录页面演示_dowebok</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" type="text/css" href="fonts/font-awesome-4.7.0/css/font-awesome.min.css"> <link rel="stylesheet" type="text/css" href="css/util.css"> <link rel="stylesheet" type="text/css" href="css/main.css"> </head> <body> <div class="limiter"> <div class="container-login100"> <div class="wrap-login100"> <div class="login100-form-title" style="background-image: url(images/bg-01.jpg);"> <span class="login100-form-title-1">登 录</span> </div> <form class="login100-form validate-form"> <div class="wrap-input100 validate-input m-b-26" data-validate="用户名不能为空"> <span class="label-input100">用户名</span> <input class="input100" type="text" name="andy" placeholder="请输入用户名"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input m-b-18" data-validate="密码不能为空"> <span class="label-input100">密码</span> <input class="input100" type="password" name="pass" placeholder="请输入用户密码"> <span class="focus-input100"></span> </div> <div class="flex-sb-m w-full p-b-30"> <div class="contact100-form-checkbox"> <input class="input-checkbox100" id="ckb1" type="checkbox" name="remember-me"> <label class="label-checkbox100" for="ckb1">记住我</label> </div> <div> <a href="javascript:" class="txt1">忘记密码?</a> </div> </div> <div class="container-login100-form-btn"> <button class="login100-form-btn">登 录</button> </div> </form> </div> </div> </div> <script type="text/javascript"> </script> <script src="js/jquery-3.2.1.min.js"></script> <script type="text/javascript" src="js/jsyilai.js"></script> </body> </html> yilai.js (function ($) { var pathName = window.location.pathname; console.log(pathName); // 输出类似于 '/index.html' //alert(pathName) switch (pathName){ case "/KuCun2/login.html": jQuery.getScript('/KuCun2/js/main.js?'+Date.now()) jQuery.getScript('/KuCun2/js/login.js?'+Date.now()) break; case "/KuCun2/main/Guanli.html": jQuery.getScript('/KuCun2/js/main.js?'+Date.now()) jQuery.getScript('/KuCun2/js/guanli.js?'+Date.now()) jQuery.getScript('/KuCun2/main/bootstrap-3.3.7-dist/js/FileSaver.js?'+Date.now()) jQuery.getScript('/KuCun2/main/bootstrap-3.3.7-dist/js/MyTable.js?'+Date.now()) break; case "/KuCun2/index.html": jQuery.getScript('/KuCun2/js/main.js?'+Date.now()) jQuery.getScript('/KuCun2/js/index.js?'+Date.now()) break; } })(jQuery) main.js function https(url,data,fu){ $.ajax({ contentType:"application/json", url: url, // 假设后端 API 地址 method: "POST", data: JSON.stringify(data), type: "json", dataType: "json", success:function(e){ console.log(e.data) if(e.status==200){ console.log(e.data) fu(e.data) }else{ alert(e.text) } }, error: function (e) { console.log(e.data) console.error(e) alert("请求失败,请稍后再试!"+e); } }); } function checkLoginStatus() { if (window.location.href.includes('/login.html')) return; } window.addEventListener('beforeunload', function(e) { console.trace('触发页面跳转的堆栈跟踪:'); }); //安全验证函数 function validateUserSession() { try { // 防御性数据获取 + 数据清洗 const rawValue = localStorage.getItem("name"); const username = String(rawValue ?? '') .trim() .replace(/[\u200B-\u200D\uFEFF]/g, ''); // 移除零宽字符 // 调试信息 console.log('[Auth] Raw:', rawValue, 'Processed:', username); // 复合验证条件 const isValid = ( username.length >= 2 && // 最小长度要求 !/[<>]/.test(username) && // 防止XSS username !== 'null' && username !== 'undefined' ); if (!isValid) { console.warn('无效用户标识:', username); // 安全跳转方法 //window.location.replace('/KuCun2/login.html'); // 立即终止执行 return Promise.reject('Invalid session'); } // 返回清洗后的用户名 return username; } catch (error) { console.error('会话验证失败:', error); // window.location.replace('/KuCun2/login.html'); return Promise.reject(error); } } function deepMergeArrays(frontend, backend) { const resultMap = new Map(); // 遍历前端数据并存入 Map 中以便快速查找 frontend.forEach(item => resultMap.set(item.id, { ...item })); // 遍历后端数据并与前端数据进行合并 backend.forEach(item => { if (resultMap.has(item.id)) { // 如果存在相同 ID,则合并两者的内容 resultMap.set( item.id, Object.assign(resultMap.get(item.id), item) ); } else { // 如果不存在相同 ID,则增该条目 resultMap.set(item.id, { ...item }); } }); // 将最终结果转回数组形式 return Array.from(resultMap.values()); } (function ($){ // 页面加载时检查登录状态 checkLoginStatus(); })(jQuery); function removeSpecificCharactersAndConvertToNumber(str, charsToRemove) { const regex = new RegExp(`[${charsToRemove}]`, 'g'); // 创建用于匹配指定字符的正则表达式 const cleanedStr = str.replace(regex, ''); // 移除指定字符 const numberValue = parseFloat(cleanedStr); // 转换为浮点数 return isNaN(numberValue) ? null : numberValue; // 如果无法解析,则返回 null } logi.js/// <reference path="jquery.d.ts" /> // $(document).ready(function(){ // $("#submit").click(function(){ // // // $.ajax({ // url:"../users/login", // async:false, // data:JSON.stringify({ // andy:$("#andy").val(), // pass:$("#pass").val(), // name:$("#name").val()}), // type:"post", // contentType:"application/json", // success:function(e){ // alert(e) // } // }); // // // }); // }) (function ($) { "use strict"; /*================================================================== [ Focus Contact2 ]*/ $('.input100').each(function () { $(this).on('blur', function () { if ($(this).val().trim() != "") { $(this).addClass('has-val'); } else { $(this).removeClass('has-val'); } }) }) /*================================================================== [ Validate ]*/ var input = $('.validate-input .input100'); $('.validate-form').on('submit', function (e) { e.preventDefault(); var check = true; for (var i = 0; i < input.length; i++) { if (validate(input[i]) == false) { showValidate(input[i]); check = false; } } confirm(input) if(check) login(input); return check; }); $('.validate-form .input100').each(function () { $(this).focus(function () { hideValidate(this); }); }); function validate(input) { if ($(input).attr('type') == 'email' || $(input).attr('name') == 'email') { if ($(input).val().trim().match(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{1,5}|[0-9]{1,3})(\]?)$/) == null) { return false; } } else { if ($(input).val().trim() == '') { return false; } } } function showValidate(input) { var thisAlert = $(input).parent(); alert(input) $(thisAlert).addClass('alert-validate'); } function hideValidate(input) { var thisAlert = $(input).parent(); $(thisAlert).removeClass('alert-validate'); } // 登录按钮点击事件 function login(datas) { var data={} datas.each(function(a,element){ data[$(element).attr('name')]=$(element).val() }) alert(data.name); //var data={ andy,pass } // 模拟 AJAX 请求 https("/KuCun2/users/login",data,function (response) { alert("122222"); if (response.name) { localStorage.setItem("name", response.name); // 保存用户名到本地存储 localStorage.setItem("role", response.role); // 保存权限到本地存储 alert( response.name) window.location.href = '/KuCun2/index.html'; } else { alert("登录失败,请检查用户名和密码!"); } }) }; // 注销按钮点击事件 $("#logout-btn").click(function () { localStorage.removeItem("name"); // 清除本地存储中的用户名 checkLoginStatus(); // 更登录状态 }); })(jQuery);index.js$().ready(function () { const username = localStorage.getItem("name"); $("#username").text(username) const $username = $('#username'); const $menuButton = $('.menu-button'); let hideTimeout = null; // 点击显示按钮 $username.on('click', function(e) { e.stopPropagation(); $menuButton.show(); }); // 区域外点击隐藏 $(document).on('click', function(e) { if (!$username.add($menuButton).is(e.target) && $username.has(e.target).length === 0 && $menuButton.has(e.target).length === 0) { $menuButton.hide(); } }); // 智能隐藏逻辑 const elements = $username.add($menuButton); elements.on('mouseleave', function() { hideTimeout = setTimeout(() => { $menuButton.hide(); }, 200); }).on('mouseenter', function() { clearTimeout(hideTimeout); }); var $iframe = $('<iframe>') // 使用 jQuery 监听 iframe 的 load 事件 $iframe.on('load', function() { try { // 确保 iframe 的内容可以被访问(非跨域情况下) var iframeDocument = $(this).contents(); var result = iframeDocument.find('body').text(); // 获取 iframe 内部的内容作为返回值 console.log("Iframe 加载完成后的返回值:", result); window.location.href="/KuCun2/login.html" } catch (error) { console.error("无法访问 iframe 内容,可能是因为跨域限制:", error.message); } }); // 将 iframe 添加到文档中 $('body').append($iframe); }); guanli.js(function ($) { //checkLoginStatus();//权限 https("/KuCun2/users/guanli/getusers",null,function(e){ $("#DataTable").remove() const c=[{id:" 序号 ", name:"名字", andy:"账号", role:"权限" }] let row = e.length+1; //c.concat(b); //const combinedArray = [c,e]; var r=deepMergeArrays(c,e) console.log(r ) let sclass = "table table-hover"; let bodys=[`<table id='DataTable' class='text-center ${sclass}'>`] let table=$("#TableView") table.append(bodys) let te= table.find("table") $.each(r, function(index, value) { var tr="" var boo=false if(index==0){var tr="<thead>"; boo=false} tr+="<tr>" $.each(value, function(name,val) { if(name!="pass"){ if(name!="id"){ tr+=`<td name='${name}' ><div contenteditable='${name!="id"&&boo}' style='float: left;width: 70%'>${val}</div></td>`; }else{ tr+=`<td name='${name}' style='float: left;width: 70%'>${val}</td>`; } } }) tr+="</tr>" if(index==0){ tr+="</thead>"} te.append(tr) }); addRight("#DataTable"); // // let sclass = "table table-striped"; // let bodys=[`<table id='DataTable' class='text-center ${sclass}'>`] // // for(let i = -1; i <= row; i++) { // bodys.push("<tr>"); // // if(i=-1){ // // for(var a in c[0]) { // // var bo= "<td><div contenteditable='true' style='float: left;width: 70%'>"+c[0][a]+"</div>"; // bodys.push(bo) // // } // // // }else{ // // // for(let j = 0; j <= col; j++) { // if(j == 0) { // var bo = "<td><div style='text-align: center;height: 100%'>" + e[i][b[j]] + "#</div></td>"; // bodys.push(bo) // } else { // var bo= "<td><div contenteditable='true' style='text-align: center;height: 100%'>" // + // // '<span class="glyphicon glyphicon-remove-sign" style="color: #999;font-size: 16px;" onclick="Deleterow(this)" aria-hidden="true"></span>' // +"</div></td>"; // bodys.push(bo) // } // } // } // bodys.push( "</tr>"); // // } // bodys.push("</table>"); // var s=bodys.join('') // $("#TableView").append(s); // addRight("#DataTable"); // }) })(jQuery) 访问index.html会被重定向到login.html其他以页面不回
05-31
function https(url,data,fu){ $.ajax({ contentType:“application/json”, url: url, // 假设后端 API 地址 method: “POST”, data: JSON.stringify(data), type: “json”, dataType: “json”, success:function(e){ console.log(e.data) if(e.status==200){ console.log(e.data) fu(e.data) }else{ alert(e.text) } }, error: function (e) { console.log(e.data) console.error(e) alert(“请求失败,请稍后再试!”+e); } }); } function checkLoginStatus() { if (window.location.href.includes(‘/login.html’)) return; } window.addEventListener(‘beforeunload’, function(e) { console.trace(‘触发页面跳转的堆栈跟踪:’); }); //安全验证函数 function validateUserSession() { try { // 防御性数据获取 + 数据清洗 const rawValue = localStorage.getItem(“name”); const username = String(rawValue ?? ‘’) .trim() .replace(/[\u200B-\u200D\uFEFF]/g, ‘’); // 移除零宽字符 // 调试信息 console.log('[Auth] Raw:', rawValue, 'Processed:', username); // 复合验证条件 const isValid = ( username.length >= 2 && // 最小长度要求 !/[<>]/.test(username) && // 防止XSS username !== 'null' && username !== 'undefined' ); if (!isValid) { console.warn('无效用户标识:', username); // 安全跳转方法 //window.location.replace('/KuCun2/login.html'); // 立即终止执行 return Promise.reject('Invalid session'); } // 返回清洗后的用户名 return username; } catch (error) { console.error(‘会话验证失败:’, error); // window.location.replace(‘/KuCun2/login.html’); return Promise.reject(error); } } function deepMergeArrays(frontend, backend) { const resultMap = new Map(); // 遍历前端数据并存入 Map 中以便快速查找 frontend.forEach(item => resultMap.set(item.id, { ...item })); // 遍历后端数据并与前端数据进行合并 backend.forEach(item => { if (resultMap.has(item.id)) { // 如果存在相同 ID,则合并两者的内容 resultMap.set( item.id, Object.assign(resultMap.get(item.id), item) ); } else { // 如果不存在相同 ID,则增该条目 resultMap.set(item.id, { ...item }); } }); // 将最终结果转回数组形式 return Array.from(resultMap.values()); } (function ($){ // 页面加载时检查登录状态 checkLoginStatus(); })(jQuery); function removeSpecificCharactersAndConvertToNumber(str, charsToRemove) { const regex = new RegExp([${charsToRemove}], ‘g’); // 创建用于匹配指定字符的正则表达式 const cleanedStr = str.replace(regex, ‘’); // 移除指定字符 const numberValue = parseFloat(cleanedStr); // 转换为浮点数 return isNaN(numberValue) ? null : numberValue; // 如果无法解析,则返回 null } <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/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>KuCun2</groupId> <artifactId>KuCun2</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <name>KuCun2</name> <description/> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.3.12.RELEASE</version> <!-- 请根据需要选择版本 --> <relativePath/> <!-- lookup parent from repository --> </parent> <properties> <webVersion>4.0</webVersion> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <protobuf.version>3.21.12</protobuf.version> </properties> <dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-api</artifactId> <version>8.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>org.glassfish.web</groupId> <artifactId>javax.servlet.jsp.jstl</artifactId> <version>1.2.4</version> </dependency> <!-- Spring Boot Starter Data JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <!-- MySQL Connector --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> <exclusions> <exclusion> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> </exclusion> </exclusions> </dependency> <!-- Optional: Lombok for reducing boilerplate code --> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-tomcat</artifactId> <scope>provided</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> <exclusions> <exclusion> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.fasterxml.jackson.datatype</groupId> <artifactId>jackson-datatype-jsr310</artifactId> </dependency> <!-- Jackson Databind --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> </dependency> <!-- Jackson Core --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> </dependency> <!-- Jackson Annotations --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> </dependency> <dependency> <groupId>org.mindrot</groupId> <artifactId>jbcrypt</artifactId> <version>0.4</version> </dependency> <dependency> <groupId>com.google.protobuf</groupId> <artifactId>protobuf-java</artifactId> <version>${protobuf.version}</version> </dependency> <dependency> <groupId>org.yaml</groupId> <artifactId>snakeyaml</artifactId> <version>1.30</version> <!-- 统一版本号 --> </dependency> </dependencies> <build> <plugins> <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <compilerArgs> <arg>-parameters</arg> </compilerArgs> </configuration> </plugin> <plugin> <artifactId>maven-war-plugin</artifactId> <version>2.6</version> <configuration> <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> </plugins> </build> </project> package com.kucun; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.support.SpringBootServletInitializer; @SpringBootApplication( ) public class DemoApplication extends SpringBootServletInitializer { public static void main(String[] args) { // // ConfigurableApplicationContext ctx = SpringApplication.run(Application.class, args); // Arrays.stream(ctx.getBeanNamesForType(SecurityFilterChain.class)) // .forEach(System.out::println); // // // // 测试密码加密示例 // BCryptPasswordEncoder encoder = new BCrypt(); // String rawPassword = “987987”; // String encodedPassword = encoder.encode(rawPassword); // System.out.println(“加密后的密码:” + encodedPassword); SpringApplication.run(DemoApplication.class, args); } }package com.kucun.Config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.kucun.Config.Role.RoleConverter; import com.kucun.Config.user.CustomUserDetails; import com.kucun.data.entity.User; import com.kucun.dataDo.UserRepository; /** 获取数据 @author Administrator / @Service public class CustomUserDetailsService/ implements UserDetailsService /{ // // @Autowired // private UserRepository userRepository; // // @Autowired // private RoleConverter roleConverter; // // public CustomUserDetailsService() { // // super(); // System.out.println(“11111”); // } ///* // * 获取数据库中用户信息 // * @param andy 账号 // * // * @return // * // */ // @Override // public UserDetails loadUserByUsername(String andy) { // System.out.println(andy); // User user = userRepository.findByAndy(andy); // System.out.println(user); // return new CustomUserDetails(user, // roleConverter.convert(user.getRole()) // 关键转换点1 // ); // } }package com.kucun.Config; // 2. 基础安全配置 //@Configuration //@EnableWebSecurity // 启用Web安全功能 public class SecurityConfig //extends WebSecurityConfigurerAdapter { // @Override // public void configure(WebSecurity web) { // web.ignoring().antMatchers(“/check-session”); // } // // 添加自定义Controller // @RestController // public static class SessionCheckController { // @GetMapping(“/check-session”) // public ResponseEntity<?> checkSession(HttpServletRequest request) { // return request.getSession(false) != null ? // ResponseEntity.ok().build() : // ResponseEntity.status(HttpStatus.UNAUTHORIZED).build(); // } // } // /** // * 核心安全过滤器链配置 // * @param http HTTP安全构建器 // * @return 安全过滤器链 // * @throws Exception 配置异常 // * // * █ 配置逻辑说明: // * 1. authorizeHttpRequests: 定义访问控制规则 // * 2. formLogin: 配置表单登录 // * 3. logout: 配置注销行为 // * 4. exceptionHandling: 处理权限异常3 // / // // // 修正后的配置方法 // @Override // protected void configure(HttpSecurity http) throws Exception { // // // // http // .csrf().disable() // .sessionManagement() // .sessionCreationPolicy(SessionCreationPolicy.ALWAYS) // .invalidSessionUrl(“/login.html?session=invalid”) // .maximumSessions(1) // .maxSessionsPreventsLogin(false) // .and() // .and() // .addFilterBefore(jsonAuthFilter(), UsernamePasswordAuthenticationFilter.class) // 关键配置 // .authorizeRequests() // .antMatchers(“/login.html”, “/users/login”).permitAll() // .antMatchers(“/js/", "/css/”, “/fonts/", "/images/”,“/check-session”,“/main/bootstrap-3.3.7-dist/“).permitAll() // .antMatchers(”/users/guanli/”).hasAuthority(“ROLE_ADMIN”) // .anyRequest().authenticated() // .and() // .formLogin().disable() //// .loginPage(“/login.html”) //// .loginProcessingUrl(“/users/login”) //// //// .successHandler(ajaxAuthenticationSuccessHandler()) // 自定义成功处理器 //// .failureHandler(ajaxAuthenticationFailureHandler()) // 自定义失败处理器 //// .defaultSuccessUrl(“/index.html”) //// .failureUrl(“/login.html?error=true”) //// .usernameParameter(“andy”) // 修改用户名参数名 //// .passwordParameter(“pass”) // 修改密码参数名 //// .and() // // .logout() // .logoutUrl(“/logout”) // .logoutSuccessUrl(“/login.html”) // .and() // .csrf() // .ignoringAntMatchers(“/users/login”) // .and() // .headers() // .frameOptions().sameOrigin() // .and() // .exceptionHandling() // .accessDeniedHandler(accessDeniedHandler()); // 统一使用Handler // } // // // // // // // 返回JSON格式的成功响应 // @Bean // public AuthenticationSuccessHandler ajaxAuthenticationSuccessHandler() { // return (request, response, authentication) -> { // // // // // 强制创建服务端会话 // request.getSession(true); // // // // // String contextPath = request.getContextPath(); // HttpSession session = request.getSession(true); // Cookie cookie = new Cookie(JSESSIONID”, session.getId()); // cookie.setPath(contextPath.isEmpty() ? “/” : contextPath + “/”); // cookie.setMaxAge(1800); // 30分钟 // response.addCookie(cookie); // // // //构建安全响应数据 // Map<String, Object> responseData = new HashMap<>(); // responseData.put(“sessionId”, request.getSession().getId()); // responseData.put(“userInfo”,Collections.unmodifiableMap(new HashMap<String, Object>() {/* // * // / // private static final long serialVersionUID = 1L; // // { // put(“Name”, ((CustomUserDetails)authentication.getPrincipal()).getName()); // put(“role”, ((CustomUserDetails)authentication.getPrincipal()).getRole()); // }})); // // // // // 统一返回JSON格式 // response.setContentType(MediaType.APPLICATION_JSON_VALUE); // // new ObjectMapper().writeValue(response.getWriter(), responseData); // // // // // // // // // // response.setContentType(MediaType.APPLICATION_JSON_VALUE); // CustomUserDetails userDetails = (CustomUserDetails) authentication.getPrincipal(); // // response.setStatus(HttpStatus.OK.value()); // System.out.println(authentication.getPrincipal()+“”+authentication.getName()); // // if (request.getHeader(“X-Requested-With”) == null) { // 非AJAX请求 // response.sendRedirect(“/index.html”); // } else { // // //String re=userDetails.getUser().toString() // new ObjectMapper().writeValue(response.getWriter(), userDetails.getUser() // ); // // } // // // // // // // }; // } // // // 返回401状态码和错误信息 // @Bean // public AuthenticationFailureHandler ajaxAuthenticationFailureHandler() { // return (request, response, exception) -> { // if (request.getHeader(“X-Requested-With”) == null) { // response.sendRedirect(“/login.html?error=true”); // } else { // response.setStatus(HttpStatus.UNAUTHORIZED.value()); // response.getWriter().write(“{"error":"Authentication failed"}”); // } // }; // } // // // 处理未认证请求 // @Bean // public AuthenticationEntryPoint ajaxAuthenticationEntryPoint() { // return (request, response, exception) -> { // if (request.getHeader(“X-Requested-With”) == null) { // response.sendRedirect(“/login.html?error=true”); // } else { // response.setStatus(HttpStatus.UNAUTHORIZED.value()); // response.getWriter().write(“{"error":"Authentication failed"}”); // } // }; // } // // // // // // @Bean // public JsonUsernamePasswordAuthenticationFilter jsonAuthFilter() throws Exception { // // JsonUsernamePasswordAuthenticationFilter filter = // new JsonUsernamePasswordAuthenticationFilter(); // filter.setAuthenticationManager(authenticationManagerBean()); // filter.setUsernameParameter(“andy”); // 设置自定义参数名 // filter.setPasswordParameter(“pass”); // filter.setFilterProcessesUrl(“/users/login”); // filter.setAuthenticationSuccessHandler(ajaxAuthenticationSuccessHandler()); // filter.setAuthenticationFailureHandler(ajaxAuthenticationFailureHandler()); // // return filter; // } // // // /* // * 密码编码器(必须配置) // * 使用BCrypt强哈希算法加密 // */ // @Bean // public PasswordEncoder passwordEncoder() { // return new BCryptPasswordEncoder(); // } // // // @Bean // public AccessDeniedHandler accessDeniedHandler() { // System.out.println(“0000”); // return (request, response, ex) -> { // if (!response.isCommitted()) { // response.sendRedirect(“/error/403”); // } // }; // } // // //} // // // // // // //class JsonUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter { // private final ObjectMapper objectMapper = new ObjectMapper(); // // @Override // public Authentication attemptAuthentication(HttpServletRequest request, // HttpServletResponse response) // throws AuthenticationException { // System.out.println(“收到认证请求,路径:” + request.getRequestURI()); // System.out.println(“请求方法:” + request.getMethod()); // System.out.println(“Content-Type:” + request.getContentType()); // if (request.getContentType() != null && // request.getContentType().startsWith(MediaType.APPLICATION_JSON_VALUE)) { // // try (InputStream is = request.getInputStream()) { // Map<String, String> authMap = objectMapper.readValue(is, Map.class); // // String username = authMap.getOrDefault(getUsernameParameter(), “”); // String password = authMap.getOrDefault(getPasswordParameter(), “”); // // // 调试日志 // System.out.println("Authentication attempt with: " + username+‘_’+ password); // // UsernamePasswordAuthenticationToken authRequest = // new UsernamePasswordAuthenticationToken(username, password); // // setDetails(request, authRequest); // return this.getAuthenticationManager().authenticate(authRequest); // } catch (IOException e) { // throw new AuthenticationServiceException(“认证请求解析失败”, e); // } // } // Authentication aut= super.attemptAuthentication(request, response); // System.out.println(“结果:”+aut.isAuthenticated()); // // return aut; // } } package com.kucun.Config.Role; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.PostConstruct; import javax.json.Json; import org.springframework.stereotype.Component; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; /** 权限转化 @author Administrator */ @Component public class RoleConverter { // private static final Map<Integer, String> ROLE_MAP = new HashMap<>(); // // @PostConstruct // public void init() { // ROLE_MAP.put(0, “ROLE_ADMIN”); // ROLE_MAP.put(1, “ROLE_USER”); // ROLE_MAP.put(2, “ROLE_MANAGER”); // ROLE_MAP.put(3, “ROLE_AUDITOR”); // } // // public List<GrantedAuthority> convert(int roleCode) { // ObjectMapper mapper = new ObjectMapper(); // try { // System.out.println(mapper.writeValueAsString(Collections.singletonList( // new SimpleGrantedAuthority(ROLE_MAP.getOrDefault(roleCode, “ROLE_GUEST”)))).toString());//输出[{“authority”:“ROLE_ADMIN”}] // } catch (JsonProcessingException e) { // // TODO Auto-generated catch block // e.printStackTrace(); // } // // return Collections.singletonList( // new SimpleGrantedAuthority(ROLE_MAP.getOrDefault(roleCode, “ROLE_GUEST”)) // ); // } // }package com.kucun.Config.user; import java.util.Collection; import com.kucun.data.entity.User; public class CustomUserDetails /implements UserDetails/ { // /** // * // */ // private static final long serialVersionUID = 1L; // private final String andy; // 对应andy字段 // private final String name; // private final int role; // private final String password; // private final User users; // private final Collection<? extends GrantedAuthority> authorities; // // public CustomUserDetails(User user, Collection<? extends GrantedAuthority> authorities) { // this.andy = user.getAndy(); // this.name = user.getName(); // this.role = user.getRole(); // this.password = user.getPass(); // user.setPass(null); // this.users=user; // this.authorities = authorities; // } // // // 实现UserDetails接口方法 // @Override public String getUsername() { return andy; } // @Override public String getPassword() { return password; } // @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } // // // 自定义字段访问方法 // public String getName() { return name; } // public User getUser() { return users; } // public int getRole() { return role; } // // // 其他必要方法 // @Override public boolean isAccountNonExpired() { return true; } // @Override public boolean isAccountNonLocked() { return true; } // @Override public boolean isCredentialsNonExpired() { return true; } // @Override public boolean isEnabled() { return true; } } <!doctype html> <html> <head> <meta charset=“utf-8”> <meta name=“viewport” content=“width=device-width, initial-scale=1, maximum-scale=1”> <title>峤丞板材库存管理</title> <meta name=“viewport” content=“width=device-width, initial-scale=1”> <link rel=“stylesheet” type=“text/css” href=“fonts/font-awesome-4.7.0/css/font-awesome.min.css”> <link rel=“stylesheet” type=“text/css” href=“css/util.css”> <link rel=“stylesheet” type=“text/css” href=“css/main.css”> <link rel=“stylesheet” type=“text/css” href=“css/index2.css”> <style type=“text/css”> *{ margin:0; padding:0; } .frame-header { height: 60px; background-color: #23262E; justify-content: space-between; } .frame-header-li{ font-family: Arial, Helvetica, sans-serif; font-size:40px; } .frame-ul{ } .frame-ul li{ border-style: solid; border-width:1px 0px 1px 0px; margin-top: 1px; height: 35px; text-align: center } #username{ position: absolute; right: 0; /* 靠右 */ } .frame-body { position: fixed; top: 60px; right: 0; bottom: 0; left: 0; display: flex; flex-direction: row; } .frame-side { scrollbar-width: none; /* firefox隐藏滚动条 / -ms-overflow-style: none; / IE 10+隐藏滚动条 / overflow-x: hidden; overflow-y: auto; width: 200px; background-color:#9e5; } .frame-side::-webkit-scrollbar { display: none; / Chrome Safari 隐藏滚动条*/ } .frame-main { flex-grow: 1; background-color:#fff; } .jiaoluo{ margin: auto; margin-right: 0px; } </style> </head> <body> <div class=“frame-header”> <a class=‘frame-header-li’ style=“color:#fff”>峤丞木材仓库管理</a> <a id=“username” class=‘frame-header-li’ style=“color:#520”>峤丞木材仓库管理</a> <button class=“.menu-button” style=“”>注销</button> </div> <div class=“frame-body”> <div class=“frame-side”> <ul class=‘frame-ul’ style=“text-align:center;”> <li ><a href=“main/test.html” target=“main”>首页</a></li> <li><a href=“main/LuRul.html” target=“main”>材料录入</a></li> <li><a href="main/Guanli.html" target="main">材料录入</a></li> </ul> </div> <div class="frame-main"> <!-- 内容主体区域 --> <iframe id="iframeid" name="main" src="main/index.html" width="100%" height="100%" frameborder="0"> </iframe> </div> </div> </body> <script type=“text/javascript” src=“js/jquery-3.2.1.min.js”></script> <script type=“text/javascript” src=“js/jsyilai.js”></script> </html><!DOCTYPE html> <html lang=“zh-CN”> <head> <title>扁平简洁的登录页面演示_dowebok</title> <meta charset=“utf-8”> <meta name=“viewport” content=“width=device-width, initial-scale=1”> <link rel=“stylesheet” type=“text/css” href=“fonts/font-awesome-4.7.0/css/font-awesome.min.css”> <link rel=“stylesheet” type=“text/css” href=“css/util.css”> <link rel=“stylesheet” type=“text/css” href=“css/main.css”> </head> <body> <div class=“limiter”> <div class=“container-login100”> <div class=“wrap-login100”> <div class=“login100-form-title” style=“background-image: url(images/bg-01.jpg);”> <span class=“login100-form-title-1”>登 录</span> </div> <form class="login100-form validate-form"> <div class="wrap-input100 validate-input m-b-26" data-validate="用户名不能为空"> <span class="label-input100">用户名</span> <input class="input100" type="text" name="andy" placeholder="请输入用户名"> <span class="focus-input100"></span> </div> <div class="wrap-input100 validate-input m-b-18" data-validate="密码不能为空"> <span class="label-input100">密码</span> <input class="input100" type="password" name="pass" placeholder="请输入用户密码"> <span class="focus-input100"></span> </div> <div class="flex-sb-m w-full p-b-30"> <div class="contact100-form-checkbox"> <input class="input-checkbox100" id="ckb1" type="checkbox" name="remember-me"> <label class="label-checkbox100" for="ckb1">记住我</label> </div> <div> <a href="javascript:" class="txt1">忘记密码?</a> </div> </div> <div class="container-login100-form-btn"> <button class="login100-form-btn">登 录</button> </div> </form> </div> </div> </div> <script type=“text/javascript”> </script> <script src=“js/jquery-3.2.1.min.js”></script> <script type=“text/javascript” src=“js/jsyilai.js”></script> </body> </html> yilai.js (function ($) { var pathName = window.location.pathname; console.log(pathName); // 输出类似于 ‘/index.html’ //alert(pathName) switch (pathName){ case "/KuCun2/login.html": jQuery.getScript('/KuCun2/js/main.js?'+Date.now()) jQuery.getScript('/KuCun2/js/login.js?'+Date.now()) break; case "/KuCun2/main/Guanli.html": jQuery.getScript('/KuCun2/js/main.js?'+Date.now()) jQuery.getScript('/KuCun2/js/guanli.js?'+Date.now()) jQuery.getScript('/KuCun2/main/bootstrap-3.3.7-dist/js/FileSaver.js?'+Date.now()) jQuery.getScript('/KuCun2/main/bootstrap-3.3.7-dist/js/MyTable.js?'+Date.now()) break; case "/KuCun2/index.html": jQuery.getScript('/KuCun2/js/main.js?'+Date.now()) jQuery.getScript('/KuCun2/js/index.js?'+Date.now()) break; } })(jQuery) main.js function https(url,data,fu){ $.ajax({ contentType:“application/json”, url: url, // 假设后端 API 地址 method: “POST”, data: JSON.stringify(data), type: “json”, dataType: “json”, success:function(e){ console.log(e.data) if(e.status==200){ console.log(e.data) fu(e.data) }else{ alert(e.text) } }, error: function (e) { console.log(e.data) console.error(e) alert(“请求失败,请稍后再试!”+e); } }); } function checkLoginStatus() { if (window.location.href.includes(‘/login.html’)) return; } window.addEventListener(‘beforeunload’, function(e) { console.trace(‘触发页面跳转的堆栈跟踪:’); }); //安全验证函数 function validateUserSession() { try { // 防御性数据获取 + 数据清洗 const rawValue = localStorage.getItem(“name”); const username = String(rawValue ?? ‘’) .trim() .replace(/[\u200B-\u200D\uFEFF]/g, ‘’); // 移除零宽字符 // 调试信息 console.log('[Auth] Raw:', rawValue, 'Processed:', username); // 复合验证条件 const isValid = ( username.length >= 2 && // 最小长度要求 !/[<>]/.test(username) && // 防止XSS username !== 'null' && username !== 'undefined' ); if (!isValid) { console.warn('无效用户标识:', username); // 安全跳转方法 //window.location.replace('/KuCun2/login.html'); // 立即终止执行 return Promise.reject('Invalid session'); } // 返回清洗后的用户名 return username; } catch (error) { console.error(‘会话验证失败:’, error); // window.location.replace(‘/KuCun2/login.html’); return Promise.reject(error); } } function deepMergeArrays(frontend, backend) { const resultMap = new Map(); // 遍历前端数据并存入 Map 中以便快速查找 frontend.forEach(item => resultMap.set(item.id, { ...item })); // 遍历后端数据并与前端数据进行合并 backend.forEach(item => { if (resultMap.has(item.id)) { // 如果存在相同 ID,则合并两者的内容 resultMap.set( item.id, Object.assign(resultMap.get(item.id), item) ); } else { // 如果不存在相同 ID,则增该条目 resultMap.set(item.id, { ...item }); } }); // 将最终结果转回数组形式 return Array.from(resultMap.values()); } (function ($){ // 页面加载时检查登录状态 checkLoginStatus(); })(jQuery); function removeSpecificCharactersAndConvertToNumber(str, charsToRemove) { const regex = new RegExp([${charsToRemove}], ‘g’); // 创建用于匹配指定字符的正则表达式 const cleanedStr = str.replace(regex, ‘’); // 移除指定字符 const numberValue = parseFloat(cleanedStr); // 转换为浮点数 return isNaN(numberValue) ? null : numberValue; // 如果无法解析,则返回 null } logi.js/// <reference path=“jquery.d.ts” /> // ParseError: KaTeX parse error: Expected '}', got 'EOF' at end of input: …function(){ // (“#submit”).click(function(){ // // // ParseError: KaTeX parse error: Expected '}', got 'EOF' at end of input: … // andy:(“#andy”).val(), // pass:ParseError: KaTeX parse error: Expected 'EOF', got '#' at position 3: ("#̲pass").val(), /…(“#name”).val()}), // type:“post”, // contentType:“application/json”, // success:function(e){ // alert(e) // } // }); // // // }); // }) (function ($) { “use strict”; /*================================================================== [ Focus Contact2 ]*/ $('.input100').each(function () { $(this).on('blur', function () { if ($(this).val().trim() != "") { $(this).addClass('has-val'); } else { $(this).removeClass('has-val'); } }) }) /*================================================================== [ Validate ]*/ var input = $('.validate-input .input100'); $('.validate-form').on('submit', function (e) { e.preventDefault(); var check = true; for (var i = 0; i < input.length; i++) { if (validate(input[i]) == false) { showValidate(input[i]); check = false; } } confirm(input) if(check) login(input); return check; }); $('.validate-form .input100').each(function () { $(this).focus(function () { hideValidate(this); }); }); function validate(input) { if ($(input).attr('type') == 'email' || $(input).attr('name') == 'email') { if ($(input).val().trim().match(/^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{1,5}|[0-9]{1,3})(\]?)$/) == null) { return false; } } else { if ($(input).val().trim() == '') { return false; } } } function showValidate(input) { var thisAlert = $(input).parent(); alert(input) $(thisAlert).addClass('alert-validate'); } function hideValidate(input) { var thisAlert = $(input).parent(); $(thisAlert).removeClass('alert-validate'); } // 登录按钮点击事件 function login(datas) { var data={} datas.each(function(a,element){ data[$(element).attr('name')]=$(element).val() }) alert(data.name); //var data={ andy,pass } // 模拟 AJAX 请求 https("/KuCun2/users/login",data,function (response) { alert("122222"); if (response.name) { localStorage.setItem("name", response.name); // 保存用户名到本地存储 localStorage.setItem("role", response.role); // 保存权限到本地存储 alert( response.name) window.location.href = '/KuCun2/index.html'; } else { alert("登录失败,请检查用户名和密码!"); } }) }; // 注销按钮点击事件 $("#logout-btn").click(function () { localStorage.removeItem("name"); // 清除本地存储中的用户名 checkLoginStatus(); // 更登录状态 }); })(jQuery);index.js$().ready(function () { const username = localStorage.getItem("name"); $("#username").text(username) const $username = $('#username'); const $menuButton = $('.menu-button'); let hideTimeout = null; // 点击显示按钮 $username.on('click', function(e) { e.stopPropagation(); $menuButton.show(); }); // 区域外点击隐藏 $(document).on('click', function(e) { if (!$username.add($menuButton).is(e.target) && $username.has(e.target).length === 0 && $menuButton.has(e.target).length === 0) { $menuButton.hide(); } }); // 智能隐藏逻辑 const elements = $username.add($menuButton); elements.on('mouseleave', function() { hideTimeout = setTimeout(() => { $menuButton.hide(); }, 200); }).on('mouseenter', function() { clearTimeout(hideTimeout); }); var $iframe = $('<iframe>') // 使用 jQuery 监听 iframe 的 load 事件 $iframe.on('load', function() { try { // 确保 iframe 的内容可以被访问(非跨域情况下) var iframeDocument = $(this).contents(); var result = iframeDocument.find('body').text(); // 获取 iframe 内部的内容作为返回值 console.log("Iframe 加载完成后的返回值:", result); window.location.href="/KuCun2/login.html" } catch (error) { console.error("无法访问 iframe 内容,可能是因为跨域限制:", error.message); } }); // 将 iframe 添加到文档中 $('body').append($iframe); }); guanli.js(function ($) { //checkLoginStatus();//权限 https(“/KuCun2/users/guanli/getusers”,null,function(e){ $(“#DataTable”).remove() const c=[{id:" 序号 ", name:“名字”, andy:“账号”, role:“权限” }] let row = e.length+1; //c.concat(b); //const combinedArray = [c,e]; var r=deepMergeArrays(c,e) console.log(r ) let sclass = "table table-hover"; let bodys=[`<table id='DataTable' class='text-center ${sclass}'>`] let table=$("#TableView") table.append(bodys) let te= table.find("table") $.each(r, function(index, value) { var tr="" var boo=false if(index==0){var tr="<thead>"; boo=false} tr+="<tr>" $.each(value, function(name,val) { if(name!="pass"){ if(name!="id"){ tr+=`<td name='${name}' ><div contenteditable='${name!="id"&&boo}' style='float: left;width: 70%'>${val}</div></td>`; }else{ tr+=`<td name='${name}' style='float: left;width: 70%'>${val}</td>`; } } }) tr+="</tr>" if(index==0){ tr+="</thead>"} te.append(tr) }); addRight("#DataTable"); // // let sclass = “table table-striped”; // let bodys=[<table id='DataTable' class='text-center ${sclass}'>] // // for(let i = -1; i <= row; i++) { // bodys.push(“<tr>”); // // if(i=-1){ // // for(var a in c[0]) { // // var bo= “<td><div contenteditable=‘true’ style=‘float: left;width: 70%’>”+c[0][a]+“</div>”; // bodys.push(bo) // // } // // // }else{ // // // for(let j = 0; j <= col; j++) { // if(j == 0) { // var bo = “<td><div style=‘text-align: center;height: 100%’>” + e[i][b[j]] + “#</div></td>”; // bodys.push(bo) // } else { // var bo= “<td><div contenteditable=‘true’ style=‘text-align: center;height: 100%’>” // + // // ‘<span class=“glyphicon glyphicon-remove-sign” style=“color: #999;font-size: 16px;” onclick=“Deleterow(this)” aria-hidden=“true”></span>’ // +“</div></td>”; // bodys.push(bo) // } // } // } // bodys.push( “</tr>”); // // } // bodys.push(“</table>”); // var s=bodys.join(‘’) // $(“#TableView”).append(s); // addRight(“#DataTable”); // }) })(jQuery) 登录后访问index.html会被重定向到login.html其他以页面不回,
06-01
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值