Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angularjs/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Angularjs 可以在spring引导控制器中使用缓存控制缓存响应吗?_Angularjs_Http_Caching_Spring Boot_Cache Control - Fatal编程技术网

Angularjs 可以在spring引导控制器中使用缓存控制缓存响应吗?

Angularjs 可以在spring引导控制器中使用缓存控制缓存响应吗?,angularjs,http,caching,spring-boot,cache-control,Angularjs,Http,Caching,Spring Boot,Cache Control,我的要求是在浏览器级别重用一些元数据,而不是每次都从服务器请求。我的rest端点已使用spring boot编写,我已在响应中添加了缓存控制和最大年龄头。我已将最大年龄设置为10秒。据我所知,我们可以为固定资产(如css和js文件)执行此操作。是否可以处理对象(响应) @CrossOrigin @RequestMapping(value=“/retrieve/{name}”,method=RequestMethod.GET) 公共响应属性getCourses(@PathVariable字符串名称

我的要求是在浏览器级别重用一些元数据,而不是每次都从服务器请求。我的rest端点已使用spring boot编写,我已在响应中添加了缓存控制和最大年龄头。我已将最大年龄设置为10秒。据我所知,我们可以为固定资产(如css和js文件)执行此操作。是否可以处理对象(响应)

@CrossOrigin
@RequestMapping(value=“/retrieve/{name}”,method=RequestMethod.GET)
公共响应属性getCourses(@PathVariable字符串名称){
课程=新课程();
HttpHeaders=新的HttpHeaders();
试一试{
System.out.println(“呼叫在此”);
course=courseService.getCourse(名称);
添加(“缓存控制”、“专用”);
标题。添加(“最大年龄”、“10”);
}捕获(例外e){
返回新的响应属性(课程,HttpStatus.BAD_请求);
}
返回新的ResponseEntity(课程、标题、HttpStatus.OK);
}
但在前端级别,请求仍将进入服务器并提供新的响应。我使用angualr作为客户端框架。我想在完成响应头中提到的最大年龄值后清除响应数据

这是相关的角度分量

app.component('searchCourseComponent', {
bindings: {
    name: '<',
},
templateUrl: 'components/course-search/course-search.component.html',
controller: function (localStorageService, CourseService) {

    var vm = this;
    vm.searchCourseByName = function (name) {

        if (localStorageService.isSupported) {
            console.log("localStrage is supporting in this browser");
            var course = CourseService.searchCourse(name).then(function (response) {
                localStorageService.set("course", response.data);
            });
        }
        else {
            console.log("Local storage is not supporting");
        }
    };
}
app.component('searchCourseComponent'{
绑定:{

名称:'您可以在angularJs中使用本地存储服务。 为此,请在
index.html

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-local-storage/0.7.1/angular-local-storage.min.js"></script>
在控制器中使用时,将
localStorageService
注入控制器,并设置要存储到本地存储中的值


例如:
localStorageService.set(“nameForStoringData”,dataToBeSet);

您可以为此使用Angualr$http缓存。它将不再发送相同的请求

    $http({
            method: type,
            url: url,
            params: params,
            cache: true,
            responseType: responseType
        }).then(function (response) {
           // success response
        }, function (response) {
          // when something went wrong
        });

更好的方法是,创建
servlet过滤器
,并添加标题以响应您需要的内容

首先创建此配置

import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableCaching 
public class CacheConfiguration { 

}
这个servlet过滤器:

import java.io.IOException;
import java.util.concurrent.TimeUnit;

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

public class CachingHttpHeadersFilter implements Filter {

    // We consider the last modified date is the start up time of the server
    private final static long LAST_MODIFIED = System.currentTimeMillis();

    private long CACHE_TIME_TO_LIVE = TimeUnit.DAYS.toMillis(1461L);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        CACHE_TIME_TO_LIVE = TimeUnit.DAYS.toMillis(365); //365 days
    }

    @Override
    public void destroy() {
        // Nothing to destroy
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

        HttpServletResponse httpResponse = (HttpServletResponse) response;

        httpResponse.setHeader("Cache-Control", "max-age=" + CACHE_TIME_TO_LIVE + ", public");
        httpResponse.setHeader("Pragma", "cache");

        // Setting Expires header, for proxy caching
        httpResponse.setDateHeader("Expires", CACHE_TIME_TO_LIVE + System.currentTimeMillis());

        // Setting the Last-Modified header, for browser caching
        httpResponse.setDateHeader("Last-Modified", LAST_MODIFIED);

        chain.doFilter(request, response);
    }
}
并注册此筛选器并添加所需的URL模式:

@Bean
public FilterRegistrationBean cachingHttpHeadersFilter() throws IOException {
    log.info("Registering Caching HTTP Headers Filter");

    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(new CachingHttpHeadersFilter());
    registration.setDispatcherTypes(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC));
    registration.setName("cachingHttpHeadersFilter");
    List<String> urlPatterns = new ArrayList<>();
    urlPatterns.add("/asset*");
    registration.setUrlPatterns(urlPatterns);
    return registration;
}
@Bean
public FilterRegistrationBean cachingHttpHeadersFilter()引发IOException{
info(“注册缓存HTTP头过滤器”);
FilterRegistrationBean注册=新建FilterRegistrationBean();
registration.setFilter(新的CachingHttpHeadersFilter());
registration.setDispatcherTypes(EnumSet.of(DispatcherType.REQUEST,DispatcherType.FORWARD,DispatcherType.ASYNC));
registration.setName(“cachingHttpHeadersFilter”);
List urlPatterns=newarraylist();
urlPatterns.add(“/asset*”);
注册.setUrlPatterns(urlPatterns);
申报登记;
}
已注册筛选器将缓存控制头添加到与
/asset*

.

我在angular应用程序中也做了同样的事情。但是它可以在浏览器中保存值。但是如果我再次发送请求,它会转到服务器。它不会使用缓存副本。这就是问题所在。你能分享你的angular代码以便更好地理解检查条件
var course=localStorageService.get(course);如果(course==undefined&&course==null){//然后只点击服务}
如果条件错误,因为所有浏览器都支持本地存储。并且不要忘记在终止应用程序后清除本地存储
import java.io.IOException;
import java.util.concurrent.TimeUnit;

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

public class CachingHttpHeadersFilter implements Filter {

    // We consider the last modified date is the start up time of the server
    private final static long LAST_MODIFIED = System.currentTimeMillis();

    private long CACHE_TIME_TO_LIVE = TimeUnit.DAYS.toMillis(1461L);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        CACHE_TIME_TO_LIVE = TimeUnit.DAYS.toMillis(365); //365 days
    }

    @Override
    public void destroy() {
        // Nothing to destroy
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

        HttpServletResponse httpResponse = (HttpServletResponse) response;

        httpResponse.setHeader("Cache-Control", "max-age=" + CACHE_TIME_TO_LIVE + ", public");
        httpResponse.setHeader("Pragma", "cache");

        // Setting Expires header, for proxy caching
        httpResponse.setDateHeader("Expires", CACHE_TIME_TO_LIVE + System.currentTimeMillis());

        // Setting the Last-Modified header, for browser caching
        httpResponse.setDateHeader("Last-Modified", LAST_MODIFIED);

        chain.doFilter(request, response);
    }
}
@Bean
public FilterRegistrationBean cachingHttpHeadersFilter() throws IOException {
    log.info("Registering Caching HTTP Headers Filter");

    FilterRegistrationBean registration = new FilterRegistrationBean();
    registration.setFilter(new CachingHttpHeadersFilter());
    registration.setDispatcherTypes(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ASYNC));
    registration.setName("cachingHttpHeadersFilter");
    List<String> urlPatterns = new ArrayList<>();
    urlPatterns.add("/asset*");
    registration.setUrlPatterns(urlPatterns);
    return registration;
}