可以对target="_blank"进行控制吗?比如我想要如果下载的文件不存在时我就不跳转新标签页
时间: 2025-08-01 21:21:00 浏览: 12
<think>我们需要控制的是:当文件存在时才在新标签页打开,否则不打开新标签页(即不执行跳转)。但是,PrimeFaces的`<p:commandLink>`本身没有提供条件判断来控制`target`属性。因此,我们需要通过其他方式实现。
思路:
1. 在用户点击链接时,先通过AJAX请求检查文件是否存在。
2. 如果文件存在,则创建一个隐藏的iframe来触发下载(这样就不会离开当前页面,但会打开新标签页或下载窗口)。
3. 如果文件不存在,则显示错误消息,不进行跳转。
但是,注意:我们之前设置了`ajax="false"`,因为文件下载需要完整请求。现在我们需要在下载前先检查文件是否存在,所以需要分两步:第一步检查(AJAX),第二步下载(非AJAX)。
然而,由于安全原因,我们不能直接通过JavaScript访问文件系统。因此,我们需要一个后端服务来检查文件是否存在。
具体步骤:
1. 在点击链接时,阻止默认行为(即不立即跳转)。
2. 发送一个AJAX请求到服务器,检查文件是否存在。
3. 根据服务器返回的结果:
- 如果文件存在,则动态创建一个iframe,设置其src为下载URL,这样就会在新标签页中打开下载(或者触发下载对话框)。
- 如果文件不存在,则显示错误消息。
注意:由于我们使用了AJAX来检查,所以需要确保下载操作本身不是通过AJAX进行的(因为AJAX无法处理文件下载)。因此,我们通过动态创建iframe的方式来触发下载。
实现:
首先,修改后端方法,提供一个检查文件是否存在的方法:
```java
// 在FileDownloadController中添加
public boolean isFileExists(String filePath) {
if (filePath == null || filePath.isEmpty()) {
return false;
}
File file = new File(filePath);
return file.exists() && file.isFile();
}
```
然后,修改前端,使用JavaScript控制:
```xhtml
<p:column style="text-align:center;width:100px" headerText="附件">
<!-- 注意:这里我们不再使用commandLink,而使用普通链接,但通过JavaScript控制 -->
<h:outputLink id="fileLink_#{index}" value="#" styleClass="file-download-link"
onclick="return handleFileDownload(event, '#{index}', '#{item.filePath}');">
<h:outputText value="#{item.fileName}" />
</h:outputLink>
<p:spacer width="10px"/>
<!-- 隐藏的下载表单,用于触发下载 -->
<h:form id="downloadForm_#{index}" style="display:none;">
<p:fileDownload value="#{tool_personClear.downloadFile(item.filePath)}" />
</h:form>
</p:column>
```
然后,编写JavaScript函数:
```javascript
function handleFileDownload(event, index, filePath) {
event.preventDefault(); // 阻止链接默认行为
// 发送AJAX请求检查文件是否存在
PrimeFaces.abmojax({
formId: 'yourFormId', // 需要替换为实际的表单ID
params: [
{name: 'filePath', value: filePath}
],
url: '#{request.contextPath}/your-check-endpoint', // 替换为检查文件存在的后端端点
method: 'POST',
async: true,
oncomplete: function(xhr, status, args) {
var data = JSON.parse(args); // 假设返回JSON
if (data.exists) {
// 文件存在,触发下载
var downloadForm = document.getElementById('downloadForm_' + index);
if (downloadForm) {
downloadForm.submit();
}
} else {
// 文件不存在,显示错误消息
alleet('文件不存在!');
// 或者使用PrimeFaces的growl
PrimeFaces.cw('Growl', 'widget_growl', {
msgs: [{summary: '错误', detail: '文件不存在!', severity: 'error'}]
});
}
}
});
return false;
}
```
但是,PrimeFaces提供了更便捷的方式,我们可以使用`p:remoteCommand`来调用后端方法并获取结果。
另一种更集成JSF的方式:
1. 在`FileDownloadController`中添加一个方法,用于检查文件是否存在并设置一个标志。
2. 使用`p:remoteCommand`来执行检查,然后根据结果决定是否下载。
修改后的前端代码:
```xhtml
<p:column style="text-align:center;width:100px" headerText="附件">
<p:commandLink id="downloadLink_#{index}" value="#{item.fileName}"
actionListener="#{tool_personClear.checkFile(item.filePath)}"
oncomplete="if (#{tool_personClear.fileExists}) {
PF('downloadWidget_#{index}').start();
} else {
PF('growl').renderMessage({summary:'错误', detail:'文件不存在', severity:'error'});
}"
process="@this" update="@none" />
<p:fileDownload id="fd_#{index}" value="#{tool_personClear.downloadFile}"
widgetVar="downloadWidget_#{index}" />
</p:column>
```
后端:
```java
private boolean fileExists;
private StreamedContent downloadFile;
private String currentFilePath;
public void checkFile(String filePath) {
currentFilePath = filePath;
fileExists = isFileExists(filePath); // 使用之前写的isFileExists方法
}
public StreamedContent getDownloadFile() {
if (fileExists) {
return downloadFile(currentFilePath); // 调用下载方法
}
return null;
}
```
但是,这种方法在每次下载前都会检查两次文件(一次在checkFile,一次在downloadFile),并且需要管理状态,可能不是线程安全的。
因此,我推荐使用第一种方法:使用JavaScript和隐藏表单。
然而,在PrimeFaces中,我们可以使用`p:remoteCommand`来调用检查方法,然后根据结果动态提交下载表单。
最终方案:
步骤:
1. 为每一行创建一个隐藏的`p:remoteCommand`,用于检查文件是否存在。
2. 当点击链接时,调用该`p:remoteCommand`,在`oncomplete`中根据结果决定是否下载。
代码示例:
```xhtml
<p:column style="text-align:center;width:100px" headerText="附件">
<!-- 显示文件名,点击时触发remoteCommand -->
<h:outputLink value="#" onclick="downloadFileCheck(#{index}, '#{item.filePath}'); return false;">
<h:outputText value="#{item.fileName}" />
</h:outputLink>
<!-- 隐藏的remoteCommand,用于检查文件并触发下载 -->
<p:remoteCommand name="downloadFileCheckCmd_#{index}"
actionListener="#{tool_personClear.checkFile}"
oncomplete="handleCheckComplete(xhr, status, args, #{index})"
process="@this" />
<!-- 隐藏的下载表单 -->
<h:form id="downloadForm_#{index}" style="display:none;">
<p:fileDownload value="#{tool_personClear.downloadFile}" />
</h:form>
</p:column>
<script>
function downloadFileCheck(index, filePath) {
// 设置filePath到后端,可以通过remoteCommand的params传递
downloadFileCheckCmd_#{index}([{name:'filePath', value: filePath}]);
}
function handleCheckComplete(xhr, status, args, index) {
if (args && args.exists) {
// 文件存在,提交下载表单
document.getElementById('downloadForm_' + index).submit();
} else {
// 文件不存在,显示错误
alleet('文件不存在');
}
}
</script>
```
后端:
```java
private String filePath; // 需要getter和setter
public void checkFile() {
// 从请求参数中获取filePath
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
String requestedFilePath = params.get("filePath");
// 检查文件是否存在,并将结果放入args
boolean exists = isFileExists(requestedFilePath);
RequestContext.getCurrentInstance().addCallbackParam("exists", exists);
// 如果存在,设置当前要下载的文件路径
if (exists) {
this.filePath = requestedFilePath;
}
}
public StreamedContent getDownloadFile() {
return downloadFile(filePath); // 调用之前实现的下载方法
}
```
注意:这种方法中,`downloadFile`方法会在提交下载表单时被调用,因此需要确保在提交下载表单时,`filePath`是正确的(即当前检查通过的那个文件路径)。由于每个文件行都有自己的表单和remoteCommand,所以不会混淆。
但是,这种方法需要为每一行都创建一个remoteCommand和一个隐藏表单,如果列表很长,可能会影响性能。
因此,我们可以优化为只使用一个remoteCommand和一个隐藏表单,但需要动态设置要检查的文件路径。
优化后的方案:
1. 在页面上放置一个remoteCommand和一个隐藏表单。
2. 点击链接时,将当前行的文件路径存储在一个全局变量中,然后调用remoteCommand。
3. remoteCommand检查该文件,将结果返回。
4. 如果存在,则用该文件路径设置隐藏表单中的参数,然后提交表单。
代码:
```xhtml
<h:form id="downloadForm" style="display:none;">
<p:fileDownload value="#{tool_personClear.downloadFile}" />
<!-- 隐藏字段用于传递文件路径 -->
<h:inputHidden id="filePath" value="#{tool_personClear.filePath}" />
</h:form>
<p:remoteCommand name="downloadFileCheckCmd"
actionListener="#{tool_personClear.checkFile}"
oncomplete="handleCheckComplete(xhr, status, args)" />
<script>
var currentFilePath = null;
function downloadFileCheck(filePath) {
currentFilePath = filePath;
downloadFileCheckCmd([{name:'filePath', value: filePath}]);
}
function handleCheckComplete(xhr, status, args) {
if (args && args.exists) {
// 设置隐藏表单中的文件路径
// 这里我们通过更新隐藏字段的值,然后提交表单
document.getElementById('downloadForm:filePath').value = currentFilePath;
document.getElementById('downloadForm').submit();
} else {
alleet('文件不存在');
}
}
</script>
```
在每一行中:
```xhtml
<p:column style="text-align:center;width:100px" headerText="附件">
<h:outputLink value="#" onclick="downloadFileCheck('#{item.filePath}'); return false;">
<h:outputText value="#{item.fileName}" />
</h:outputLink>
</p:column>
```
后端:
```java
public void checkFile() {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, String> params = context.getExternalContext().getRequestParameterMap();
String requestedFilePath = params.get("filePath");
boolean exists = isFileExists(requestedFilePath);
RequestContext.getCurrentInstance().addCallbackParam("exists", exists);
// 注意:这里不需要设置this.filePath,因为下载表单提交时会通过隐藏字段设置
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public StreamedContent getDownloadFile() {
return downloadFile(filePath);
}
```
这样,我们就实现了按需检查文件是否存在,并且只在文件存在时才触发下载(打开新标签页)。
注意:隐藏字段`filePath`必须绑定到后台bean的`filePath`属性,并且该属性有setter方法,这样在提交下载表单时,JSF会调用setter方法设置当前文件路径,然后调用getDownloadFile方法获取文件流。
总结:我们通过结合AJAX检查、隐藏表单和JavaScript控制,实现了条件触发下载。这样当文件不存在时,就不会跳转新标签页。
注意:这种方法在下载时仍然会打开新标签页(因为表单提交会打开新标签页),但这是符合预期的,因为文件下载通常在新标签页或下载窗口中显示。
如果希望下载时不打开新标签页,而是直接下载(不离开当前页面),那么可以使用动态创建iframe的方式,但这样不会显示下载进度。不过,大多数浏览器会直接在底部显示下载进度条,而不会打开新标签页。
修改下载触发方式(使用iframe):
在`handleCheckComplete`函数中,不提交表单,而是动态创建iframe:
```javascript
function handleCheckComplete(xhr, status, args) {
if (args && args.exists) {
// 动态创建iframe
var iframe = document.createElement("iframe");
iframe.style.display = "none";
iframe.src = "#{request.contextPath}/download?filePath=" + encodeURIComponent(currentFilePath);
document.body.appendChild(iframe);
} else {
alleet('文件不存在');
}
}
```
但是,这种方法需要单独的文件下载Servlet,而不是使用PrimeFaces的fileDownload组件。因此,我们可能需要额外创建一个下载Servlet。
考虑到我们已经在使用PrimeFaces,建议使用之前隐藏表单的方式即可。
因此,最终我们采用隐藏表单提交的方式,这样会打开新标签页(或浏览器的下载管理器),但这是正常的文件下载行为。
注意:隐藏表单提交会触发整个页面的刷新?不会,因为表单设置了`display:none`,并且提交表单下载文件时,浏览器会处理下载响应,不会刷新页面。
因此,我们使用优化后的方案:一个remoteCommand,一个隐藏表单,通过全局变量传递当前文件路径。
这样,我们就实现了对`target="_blank"`的条件控制:只有当文件存在时才触发下载(即打开新标签页或下载对话框),否则提示错误。
注意:由于我们不再使用`p:commandLink`,所以之前代码中的`p:spacer`可以去掉,或者用其他方式调整布局。
最后,关于样式,我们可以继续使用链接样式,不影响用户体验。
相关问题:
§§相关问题§§:
1. 在PrimeFaces中如何实现文件上传?
2. 如何防止用户重复提交文件下载请求?
3. 在JSF中如何实现文件下载的进度条显示?
4. 如何处理文件下载时的大文件内存溢出问题?</think># 条件控制文件下载行为:动态处理 target="_blank" 和文件存在性检查
在 PrimeFaces 中,您可以通过条件渲染和 JavaScript 控制来实现:只有当文件存在时才在新标签页打开下载链接,否则不跳转。以下是完整的解决方案:
## 核心实现思路
1. **后端添加文件存在性检查方法**
2. **前端使用条件渲染控制 target 属性**
3. **使用 JavaScript 处理下载失败情况**
4. **添加用户友好的错误提示**
## 后端实现(Java)
```java
import org.primefaces.model.StreamedContent;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
@ManagedBean
@ViewScoped
public class FileDownloadController {
// 检查文件是否存在
public boolean fileExists(String filePath) {
if (filePath == null || filePath.isEmpty()) {
return false;
}
File file = new File(filePath);
return file.exists() && file.isFile();
}
// 获取文件下载内容
public StreamedContent getDownloadContent(String filePath) {
if (!fileExists(filePath)) {
return null;
}
try {
File file = new File(filePath);
InputStream inputStream = new FileInputStream(file);
String contentType = determineContentType(file.getName());
return DefaultStreamedContent.builder()
.name(file.getName())
.contentType(contentType)
.stream(() -> inputStream)
.build();
} catch (IOException e) {
throw new RuntimeException("文件下载失败", e);
}
}
// 其他辅助方法...
}
```
## 前端实现(XHTML)
```xhtml
<p:column style="text-align:center;width:100px" headerText="附件">
<!-- 文件存在时 - 在新标签页打开 -->
<p:commandLink rendered="#{fileDownloadController.fileExists(item.filePath)}"
value="#{item.fileName}"
ajax="false"
target="_blank"
action="#{fileDownloadController.prepareDownload(item.filePath)}">
<p:fileDownload value="#{fileDownloadController.downloadContent}"
contentDisposition="inline" />
</p:commandLink>
<!-- 文件不存在时 - 显示错误提示 -->
<h:outputText rendered="#{not fileDownloadController.fileExists(item.filePath)}"
value="#{item.fileName} (文件不存在)"
style="color: red; cursor: not-allowed;"
title="文件不存在或已被删除">
<p:tooltip />
</h:outputText>
<!-- 添加下载状态监听 -->
<p:ajaxStatus onstart="showDownloadStatus()"
oncomplete="handleDownloadComplete(xhr, status, args)" />
</p:column>
<!-- 下载状态提示 -->
<p:dialog widgetVar="statusDialog" modal="true" draggable="false" closable="false">
<p:graphicImage value="/resources/images/loading.gif" />
<h:outputText value="正在准备下载..." />
</p:dialog>
<!-- 错误提示 -->
<p:growl id="growl" showDetail="true" sticky="true" />
```
## JavaScript 控制逻辑
```javascript
// 显示下载状态
function showDownloadStatus() {
PF('statusDialog').show();
}
// 处理下载完成事件
function handleDownloadComplete(xhr, status, args) {
PF('statusDialog').hide();
// 检查下载是否成功
if (args && args.error) {
// 显示错误消息
PF('growl').renderMessage({
summary: '下载失败',
detail: args.errorMessage,
severity: 'error'
});
// 关闭可能已打开的空标签页
closeNewTabIfNeeded();
}
}
// 关闭可能已打开的空标签页
function closeNewTabIfNeeded() {
// 检查是否有新打开的空白标签页
if (window.openTabs && window.openTabs.length > 0) {
const tab = window.openTabs.pop();
try {
if (tab && !tab.closed && tab.location.href === 'about:blank') {
tab.close();
}
} catch (e) {
// 跨域安全限制,无法直接关闭
}
}
}
// 存储打开的新标签页引用
window.openTabs = [];
// 重写 window.open 方法以跟踪打开的标签页
const originalOpen = window.open;
window.open = function(url, name, features) {
const newTab = originalOpen(url, name, features);
if (newTab) {
window.openTabs.push(newTab);
}
return newTab;
};
```
## 增强的后端控制(处理下载错误)
```java
// 在 FileDownloadController 中添加
private String currentFilePath;
private StreamedContent downloadContent;
private String errorMessage;
public void prepareDownload(String filePath) {
this.currentFilePath = filePath;
this.errorMessage = null;
try {
if (!fileExists(filePath)) {
throw new FileNotFoundException("文件不存在: " + filePath);
}
this.downloadContent = getDownloadContent(filePath);
} catch (Exception e) {
this.downloadContent = null;
this.errorMessage = e.getMessage();
addErrorMessageToRequest();
}
}
private void addErrorMessageToRequest() {
FacesContext context = FacesContext.getCurrentInstance();
if (context != null) {
Map<String, Object> requestMap = context.getExternalContext().getRequestMap();
requestMap.put("error", true);
requestMap.put("errorMessage", errorMessage);
}
}
public StreamedContent getDownloadContent() {
return downloadContent;
}
```
## 完整工作流程
1. **文件存在性检查**:
- 后端 `fileExists()` 方法检查文件是否存在
- 前端使用 `rendered` 属性条件显示链接或错误提示
2. **下载准备**:
- 用户点击链接时调用 `prepareDownload()` 方法
- 后端再次验证文件存在性并准备下载内容
3. **错误处理**:
- 如果文件不存在,设置错误信息
- 将错误信息添加到请求属性中
4. **前端处理**:
- `ajaxStatus` 组件监听下载状态
- 下载完成时检查错误信息
- 显示错误提示并尝试关闭空标签页
5. **标签页控制**:
- 重写 `window.open` 方法跟踪新开标签页
- 下载失败时尝试关闭空标签页
## 替代方案:纯 JavaScript 实现
如果不想依赖后端检查,可以使用前端 AJAX 检查文件存在性:
```xhtml
<p:commandLink value="#{item.fileName}"
onclick="return checkFileExists(event, '#{item.filePath}')">
<p:fileDownload value="#{tool_personClear.downloadFile(item.filePath)}"
contentDisposition="inline" />
</p:commandLink>
<script>
function checkFileExists(event, filePath) {
// 发送AJAX请求检查文件是否存在
PrimeFaces.abmojax({
url: '#{request.contextPath}/file-exists',
params: [{name: 'filePath', value: filePath}],
async: false, // 同步请求确保顺序执行
success: function(data) {
if (!data.exists) {
event.preventDefault(); // 阻止默认行为
PF('growl').renderMessage({
summary: '文件不存在',
detail: '请求的文件 ' + filePath + ' 不存在',
severity: 'error'
});
}
}
});
return true; // 允许继续执行
}
</script>
```
后端实现检查端点:
```java
@Path("/file-exists")
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response checkFileExists(@QueryParam("filePath") String filePath) {
boolean exists = fileExists(filePath);
return Response.ok().entity(Collections.singletonMap("exists", exists)).build();
}
```
## 安全增强措施
1. **路径安全验证**:
```java
public boolean fileExists(String filePath) {
// 规范化路径并检查是否在安全目录内
Path normalizedPath = Paths.get(filePath).normalize();
if (!normalizedPath.startsWith(SAFE_DOWNLOAD_DIR)) {
return false;
}
// 继续检查...
}
```
2. **下载频率限制**:
```java
// 使用Guava RateLimiter限制下载频率
private static final RateLimiter downloadLimiter = RateLimiter.create(5.0); // 每秒5次
public StreamedContent getDownloadContent(String filePath) {
if (!downloadLimiter.tryAcquire()) {
throw new RuntimeException("下载请求过于频繁,请稍后再试");
}
// 继续下载...
}
```
3. **文件类型白名单**:
```java
private static final Set<String> ALLOWED_TYPES = Set.of(
"pdf", "jpg", "png", "docx", "xlsx"
);
public StreamedContent getDownloadContent(String filePath) {
String extension = getFileExtension(filePath);
if (!ALLOWED_TYPES.contains(extension.toLowerCase())) {
throw new SecurityException("不允许下载此类型文件");
}
// 继续下载...
}
```
## 相关问题
阅读全文
相关推荐















<?php
include './include/class.main.php';
include './save/config.php';
include './save/top.inc.php';
$skin=array(
'color'=>'#50b2c8', //文本颜色
'input_border'=>'#6599aa', //搜索边框颜色
'input_color'=>'white', //搜索文本颜色
'background'=>'#0f3854', //背景颜色
'background_style'=>'#0a2e38 0%,#000000 80%', //背景渐变样式
);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge"/><meta name="renderer" content="webkit"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
<script type="text/javascript" src="./include/jquery.min.js"></script>
<script type="text/javascript" src="./include/class.main.js" ></script>
<script type="text/javascript" src="./include/jquery.autocomplete.js?ver=1.2"></script>
<title><?php echo $CONFIG["TITLE"]; ?></title>
<style>
html,body{
overflow:auto !important;
width:100%;
height: 100%;
margin: 0;
padding: 0;
}
body{
text-align: center;
background: <?php echo $skin["background"];?>;
background: -webkit-radial-gradient(<?php echo $skin["background_style"];?>); /* Safari 5.1-6.0 */
background: -o-radial-gradient(<?php echo $skin["background_style"];?>); /* Opera 11.6-12.0 */
background: -moz-radial-gradient(<?php echo $skin["background_style"];?>); /* Firefox 3.6-15 */
background: radial-gradient(<?php echo $skin["background_style"];?>); /* 标准语法 */
background-size: 100%;
}
p {
margin: 0;
padding: 0;
}
a{
color:<?php echo $skin["color"]; ?>;
}
#clock {
font-family: 'Share Tech Mono', monospace;
text-align: center;
color: #daf6ff;
/* text-shadow: 0 0 20px #0aafe6, 0 0 20px rgba(10, 175, 230, 0); */
}
#clock .time {
letter-spacing: 0.05em;
font-size: 60px;
padding: 5px 0;
}
#clock .date {
letter-spacing: 0.1em;
font-size: 15px;
}
#clock .text {
letter-spacing: 0.1em;
font-size: 12px;
padding: 20px 0 0;
}
#word{
background: #fff;
color: #000;
max-height:170px;
overflow-y:auto;
overflow-x:hidden;
}
#main{
text-align: center;
background-size: cover
}
h1{ color:red;}
h2{color:green;}
h3{color:#a7e9c3}
h4{color:blue;font-size:50px}
*{ box-sizing: border-box;}
div.search {padding: 5px 0;}
form {
position: relative;
width: 300px;
margin: 0 auto;
}
input, button {
border: none;
outline: none;
color:<?php echo $skin["input_color"]; ?>;
}
input {
width: 100%;
height: 42px;
padding-left: 13px;
}
button {
height: 42px;
width: 42px;
cursor: pointer;
position: absolute;
}
/*搜索框6*/
.bar6 input {
background: transparent;
border-radius:3px;
border:2px solid <?php echo $skin["input_border"]; ?> ;
top: 0;
right: 0;
}
.bar6 button {
background:<?php echo $skin["input_border"]; ?>;
border-radius: 0 5px 5px 0;
width: 60px;
top: 0;
right: 0;
}
.bar6 button:before {
content: "搜索";
font-size: 13px;
color: <?php echo $skin["input_color"] ?>;
}
/* 搜索内容样式 */
.list_btn{
display: inline-block;
text-decoration: inherit;
/* 内外边距及宽高属性 */
margin: 1%; padding: 5px;
height: 30px;
min-width:31%;
max-width:95%;
/* 文字及边框属性 */
color:<?php echo $skin["color"]; ?>;
font-size:13px;
border-radius: 5px;
border: 2px solid <?php echo $skin["color"]; ?>;
/* 文字剪裁 */
text-overflow: ellipsis;
overflow: hidden;
white-space: nowrap !important;
outline: 0 !important
}
/* 移动设备自适应宽高 */
@media screen and (max-width: 650px){.list_btn{min-width:95%;}}
/*清除浮动代码*/
.clearfloat{clear:both}
.resou{
padding-top: 15px;
}
.resou a{
color:<?php echo $skin["color"] ?>;
padding: 5px;
text-decoration:none;
}
a{text-decoration:none;}
</style>
<script>
function check_str(field){
with(field){
var arr=['{','}','(',')','=',',',';','"','<','>','script','iframe','@','&','%','$','#','*',':','.','if','/','\\'];
if("<?php echo $CONFIG["socode"]["not_off"];?>"=='1'){
var str="<?php echo base64_decode($CONFIG["socode"]["not_val"]); ?>";
if(str!=''){strs = str.split("|");arr = arr.concat(strs);}
}
for (var key in arr) {
if( value.toLowerCase().indexOf(arr[key].toLowerCase()) > -1){
return true;
}
}
return false;
}
}
function validate_form(thisform){
with(thisform){
if(wd.value.indexOf('http')===-1){action='./so.php';wd.name='wd'}else{action='./';wd.name='url';}
if(typeof wd!=="undefined" && wd.name=='wd'){
if (check_str(wd)){
alert("请勿输入非法字符!");
return false
}
}
}
}
</script>
<script>
// 检查是否为移动设备
function isMobileDevice() {
return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
}
// 加载随机背景图片
function loadRandomBackground() {
if(isMobileDevice()) {
var backgroundURL = './208896.jpg'
} else {
backgroundURL = './208899.jpg'
}
console.log(backgroundURL)
// 设置body的背景图片为随机图片
$('body').css('background', 'url(' + backgroundURL + ') no-repeat center center fixed');
$('body').css('background-size', 'cover');
}
// 页面加载时加载随机背景
$(document).ready(function() {
loadRandomBackground();
});
</script>
</head>
<body>
00:00:00
2018-08-08 星期一
<form target="_parent" action="./" onsubmit="return validate_form(this);" method="get" >
<input id="wd" type="text" name="v" placeholder="请输入视频名称或视频链接" value="<?php echo $_GET['wd']; ?>" >
<button type="submit"></button>
</form>
<?php if($CONFIG["socode"]["top_off"]): ?>
;"> 热门搜索:
<?php arsort($TOPDATA);$i=0; foreach ($TOPDATA as $key=>$val ): ?>
<?php echo $key; ?>
<?php $i++; if($i==5){break;}?>
<?php endforeach; ?>
更多...
<?php endif; ?>
<?php if($CONFIG["socode"]["diy_off"]): ?>
<?php echo base64_decode($CONFIG["socode"]["diy_val"]); ?>
<?php endif; ?>
<script id="LA-DATA-WIDGET" crossorigin="anonymous" charset="UTF-8" src="https://v6-widget.51.la/v6/JmppOQcqqd5xRMl7/quote.js?theme=#0EEBF2,#333333,#04F2EA,#333333,#FFFFFF,#1690FF,12&f=12&display=0,1,0,1,0,1,0,1"></script>
<?php if($CONFIG["FOOTER_LINK"]['off']): ?>
;"> 友情链接:
<?php foreach( $CONFIG["FOOTER_LINK"]['info'] as $key=>$val) : ?>
<?php echo $key; ?>
<?php endforeach; ?>
<?php endif; ?>
<script>
//显示日期时间
var week = ['星期天', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
var timerID = setInterval(updateTime, 1000);
var sitetime="<?php echo $CONFIG["sitetime"];?>";
updateTime();
function updateTime() {
var cd = new Date();
$('#time').text(zeroPadding(cd.getHours(), 2) + ':' + zeroPadding(cd.getMinutes(), 2) + ':' + zeroPadding(cd.getSeconds(), 2));
$('#text').text(zeroPadding(cd.getFullYear(), 4) + '-' + zeroPadding(cd.getMonth()+1, 2) + '-' + zeroPadding(cd.getDate(), 2) + ' ' + week[cd.getDay()]);
SiteTime(sitetime);
};
function zeroPadding(num, digit) {
var zero = '';
for(var i = 0; i < digit; i++) {
zero += '0';
}
return (zero + num).slice(-digit);
}
//网站运行时间
function SiteTime(time){
var seconds =1000;
var minutes = seconds *60;
var hours = minutes *60;
var days = hours *24;
var years = days *365;
var dateBegin = new Date(time.replace(/-/g, "/"));//将-转化为/,使用new Date
var dateEnd = new Date();//获取当前时间
var diff = dateEnd.getTime() - dateBegin.getTime();//时间差的毫秒数;
var diffYears =Math.floor(diff/years);
var diffDays =Math.floor((diff/days)-diffYears*365);
var diffHours =Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
var diffMinutes =Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
var diffSeconds =Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
document.getElementById("sitetime").innerHTML=" 已运行"+diffYears+" 年 "+diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
}
</script>
<script>
//入口
function init() {
var wd= _GET("wd");
var url= _GET("url");
if(wd==="" && url==="" ){
//w="...请输入视频地址... ";
w='
">...视">频地址不能为空...';
$(".date").html(w);
}
if(wd!==""){getvideo(wd);}
w="<?php echo $CONFIG["play"]["all"]["by"]; ?>";
w+=' 免责声明
';
$("#footer").html(w);
toggleCenter();
}
//显示版权
function echoby() {
alert("本站所有视频均来自外部引用,本站不存储不制作任何视频!\r\n 如有侵权问题,请与源站联系,谢谢合作!");
}
//搜索排行
function echotop(){
if ($("#main").html().indexOf("搜索排行榜")!=-1){
$("#main").html("");
}else{
var w = "
搜索排行榜-TOP100";
<?php arsort($TOPDATA);$i=0; foreach ($TOPDATA as $key=>$val ): ?>
title="<?php echo $key; ?>";
w+= "" + title+ "";
<?php $i++; if($i==100){break;}?>
<?php endforeach; ?>
w+= "";
$("#main").html(w);
}
toggleCenter();
}
//刷新列表
function relist(data){
if(data&&data.success)
{
var v=data.info;
var w = "
搜索到相关视频" + v.length + "个,请点击访问";
for (i = 0, len = v.length; i < len; i++)
{
/*
_blank:新窗口打开。
_parent:在父窗口中打开链接。
_self:默认,当前页面跳转。
_top:在当前窗体打开链接,并替换当前的整个窗体(框架页)。
*/
var href="./?index"+v[i].id +"-" + v[i].flag+"-1.htm";
var title=removeHTMLTag(v[i].title,true)+"(" +(v[i].from)+")";
w+= "<a class='list_btn ' target='_self' href='" +href +"' title='"+ title+"' >" + title + "
";
}
w+= "";
}else{
var w='很抱歉,未搜索到相关资源';
$("#info").html('请修改影片名后重新搜索');
}
$("#main").html(w);
$("#body").show();
toggleCenter();
}
//取视频数据
function getvideo(word){
$.ajax({
url: './<?php echo $CONFIG["API_PATH"]; ?>?out=jsonp&wd='+word,
timeout:30000,
dataType: 'jsonp',
jsonp: 'cb',
beforeSend: function() {
$("#body").hide();
$("#main").html('正在搜索中,请稍后...');
},
success: function (data) {
relist(data);
},
error: function () {
relist();
}
});
}
//自适应大小位置
function toggleCenter() {
if($("#main").height() + $("#clock").height()>$(window).height()){
$("#clock").css("position","static");
}else{
$("#clock").css("position","absolute");$("#clock").css("top",($(window).height() -$("#clock").height())/2-20);
}
if($(window).width()<=$("#clock").width()){$("#clock").css("left",0);}else{ $("#clock").css("left",($(window).width()-$("#clock").width())/2);}
}
$(window).resize(function(){ toggleCenter();});
init();
</script>
</body>
</html>美化搜索结果页面 



<%-- Created by IntelliJ IDEA. User: vili Date: 2019/8/23 Time: 13:42 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%@page isELIgnored="false" %> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> Toggle navigation </button> 叮当书城 <a href="index.action" <c:if test="${param.flag==1}">class="active"</c:if>>首页
active</c:if>" data-toggle="dropdown">商品分类 商品分类 全部系列 <c:forEach items="${bookTypes}" var="t"> ${t.btname} </c:forEach> <a href="recommend_books.action?rtype=2&pageNumber=1" <c:if test="${param.flag==3 && t==2}">class="active"</c:if>>热销 <a href="recommend_books.action?rtype=3&pageNumber=1" <c:if test="${param.flag==3 && t==3}">class="active"</c:if>>新品 <c:choose> <c:when test="${empty user }"> <a href="user_register.jsp" <c:if test="${param.flag==10 }">class="active"</c:if>>注册 <a href="user_login.jsp" <c:if test="${param.flag==9 }">class="active"</c:if>>登录 </c:when> <c:otherwise> <a href="order_list.action" <c:if test="${param.flag==5 }">class="active"</c:if>>我的订单 <a href="user_center.jsp" <c:if test="${param.flag==4 }">class="active"</c:if>>个人中心 退出 后台管理 </c:otherwise> </c:choose> <form class="navbar-form" action="search_books.action"> <input type="hidden" name="pageNumber" value="1"/> <input type="text" class="form-control" name="keyword"> <button type="submit" class="btn btn-default <c:if test="${param.flag==7 }">active</c:if>" aria-label="Left Align">搜索</button> </form> active</c:if>" aria-hidden="true"><c:choose><c:when test="${empty order}">0</c:when><c:otherwise>${order.itemMap.size()}</c:otherwise></c:choose>
