小编Pra*_*ngh的帖子

如何禁用特定URL的弹簧安全性

我正在使用无状态弹簧安全性,但在注册的情况下我想禁用spring security.I禁用使用

antMatchers("/api/v1/signup").permitAll().
Run Code Online (Sandbox Code Playgroud)

但它不起作用,我收到以下错误:

 message=An Authentication object was not found in the SecurityContext, type=org.springframework.security.authentication.AuthenticationCredentialsNotFoundException
Run Code Online (Sandbox Code Playgroud)

我认为这意味着Spring安全过滤器正在运行

我的网址顺序总是"/ api/v1"

我的春天配置是

@Override
    protected void configure(HttpSecurity http) throws Exception {

         http.
         csrf().disable().
         sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).
         and().
         authorizeRequests().
         antMatchers("/api/v1/signup").permitAll().
         anyRequest().authenticated().
         and().
         anonymous().disable();
        http.addFilterBefore(new AuthenticationFilter(authenticationManager()), BasicAuthenticationFilter.class);
    }
Run Code Online (Sandbox Code Playgroud)

我的验证过滤器是

@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest httpRequest = asHttp(request);
        HttpServletResponse httpResponse = asHttp(response);

        String username = httpRequest.getHeader("X-Auth-Username");
        String password = httpRequest.getHeader("X-Auth-Password");
        String token = httpRequest.getHeader("X-Auth-Token");

        String resourcePath = new UrlPathHelper().getPathWithinApplication(httpRequest);

        try { …
Run Code Online (Sandbox Code Playgroud)

java spring spring-mvc spring-security

65
推荐指数
5
解决办法
10万
查看次数

如何在Mongoose中创建和使用枚举

我正在尝试创建并使用enumMongoose中的类型.我检查了一下,但是我没有得到正确的结果.我enum在我的程序中使用如下:

我的架构是:

var RequirementSchema = new mongoose.Schema({
   status: {
        type: String,
        enum : ['NEW', 'STATUS'],
        default: 'NEW'
    },
})
Run Code Online (Sandbox Code Playgroud)

但我在这里有点困惑,我怎么能把enum类似的价值放进去Java NEW("new").如何enum根据它的可枚举值将数据保存到数据库中.我在express node.js中使用它.

enums mongodb node.js express

56
推荐指数
6
解决办法
6万
查看次数

为Spring启动应用程序编写Spock测试用例

我正在开发spring boot应用程序.我必须为它编写测试用例.我以前没有写过测试用例,所以有人建议使用spock框架.我探索了spock,我认为它与groovy语言更相关.

我可以为我的春季应用程序编写spock测试用例吗?

如果是这样,那么你能否建议我更好地记录"如何在春季启动应用程序中使用它"?

java groovy spring spock

6
推荐指数
1
解决办法
6303
查看次数

弹簧数据mongodb中的2d球面索引

我正在研究mongodb的地理空间查询,我已经在mongo控制台上执行了以下查询

db.items.find(
   {
     location:
       { $near :
          {
            $geometry: { type: "Point",  coordinates: [77.026638, 28.459497 ] },
            $maxDistance: 10000
          }
       }
   }
)
Run Code Online (Sandbox Code Playgroud)

但是如何使用spring数据mongodb标准编写此查询?

我尝试使用以下标准,但它无法正常工作

 Criteria criteria = Criteria.where("location").near(new Point(77.026638, 28.459497)).maxDistance(1000);

        Query query = new Query(criteria);
System.out.println(mongoTemplate.find(query, Item.class));
Run Code Online (Sandbox Code Playgroud)

堆栈跟踪

org.springframework.data.mongodb.UncategorizedMongoDbException: Unable to execute query: error processing query: ns=geolocation.items limit=0 skip=0
Tree: GEONEAR  field=location maxdist=1.79769e+308 isNearSphere=0
Sort: {}
Proj: {}
 planner returned error: unable to find index for $geoNear query; nested exception is com.mongodb.MongoException: Unable to execute query: error processing query: …
Run Code Online (Sandbox Code Playgroud)

java spring mongodb spring-data-mongodb

6
推荐指数
1
解决办法
1363
查看次数

Thymeleaf:Thymeleaf模板解析错误

我正在进行密码重置功能,为此,我使用百万美元模板.但这是我的简单html,它不会呈现.这告诉我波纹管错误:

@Bean
public ClassLoaderTemplateResolver emailTemplateResolver(){
    ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
    emailTemplateResolver.setPrefix("templates/mail/");
    emailTemplateResolver.setSuffix(".html");
    emailTemplateResolver.setTemplateMode("HTML5");
    emailTemplateResolver.setCharacterEncoding("UTF-8");
    emailTemplateResolver.setOrder(1);
    return emailTemplateResolver;
}
Run Code Online (Sandbox Code Playgroud)

我的百里香叶配置

<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
</head>
<body>
    <form th:action="@{/resetpassword(_key=${resetPasswordToken})}" method="post">
    <div>
    <input type="password" th:field="*{password}">
    <input type="password">
    </div>
    </form>
</body>
</html> 
Run Code Online (Sandbox Code Playgroud)

我的demo.html是

@RequestMapping(value = "/resetpassword", method = RequestMethod.GET)
public String resetpasswordView(@RequestParam(value = "_key") String resetPasswordToken, final Model model) {
    System.out.println(resetPasswordToken);
    model.addAttribute("resetPasswordToken", resetPasswordToken);
    return "demo";
}
Run Code Online (Sandbox Code Playgroud)

我的控制器是

@Bean
public ClassLoaderTemplateResolver emailTemplateResolver(){
    ClassLoaderTemplateResolver emailTemplateResolver = new ClassLoaderTemplateResolver();
    emailTemplateResolver.setPrefix("templates/mail/");
    emailTemplateResolver.setSuffix(".html");
    emailTemplateResolver.setTemplateMode("HTML5");
    emailTemplateResolver.setCharacterEncoding("UTF-8"); …
Run Code Online (Sandbox Code Playgroud)

spring-mvc thymeleaf spring-boot

4
推荐指数
1
解决办法
8780
查看次数

在静态块中加载库是正确的方法吗?

我通过 maven 依赖在我的应用程序中使用 opencv 库。当应用程序启动时,我正在静态块中加载 opencv。不过,我在开发环境中工作并且工作正常。但我想问一下,在静态块中加载 opencv 是正确的方法吗?

加载opencv

@SpringBootApplication
@EnableScheduling
public class SamepinchApplication extends SpringBootServletInitializer{

static {
        try{
            nu.pattern.OpenCV.loadShared();
            System.loadLibrary(org.opencv.core.Core.NATIVE_LIBRARY_NAME);
        }catch(Exception exception){
            System.out.println("Open CV Library could not load due to " + exception.getCause());
        }
    }

 public static void main(String[] args) {
        SpringApplication.run(SamepinchApplication.class, args);
    }

}
Run Code Online (Sandbox Code Playgroud)

Maven 依赖

<dependency>
            <groupId>nu.pattern</groupId>
            <artifactId>opencv</artifactId>
            <version>2.4.9-7</version>
        </dependency>
Run Code Online (Sandbox Code Playgroud)

请帮助我,加载 opencv 或其他本机库的好做法是什么?

java opencv spring-boot

3
推荐指数
1
解决办法
1276
查看次数

Eclipse paho Mqtt:获取java.io.EOF异常

当我试图订阅mqtt客户端时,我得到"java.io.eof"异常.我正在使用eclipse paho库并使用mosquitto broker.我没有得到任何答案,所以请帮助我为什么会这样?

Mqtt连接和订阅

我正在使用此代码连接和订阅mosquitto

private void buildClient(String clientId){
    log.debug("Connecting... "+clientId);
        try {
            mqttClient = new MqttClient(envConfiguration.getBrokerUrl(), clientId,new MemoryPersistence());
            System.out.println(mqttClient.isConnected());
        } catch (MqttException e) {
            log.debug("build client stopped due to "+e.getCause());
        }

        chatCallback = new ChatCallback(this.userService,this);
        mqttClient.setCallback(chatCallback);
        mqttConnectOptions = new MqttConnectOptions();
        mqttConnectOptions.setCleanSession(true);
    }

    @Override
    public void connect(String clientId,String topic) {

        try{
            if(mqttClient == null || !mqttClient.getClientId().equals(clientId)){
                buildClient(clientId);
                mqttClient.connect(mqttConnectOptions);
                subscribe(clientId,topic);
            } 
        }catch (Exception e) {
            log.debug("connection attempt failed "+ e.getCause() + " trying...");
        }
    }

    @Override
    public void subscribe(String clientId,String topic) …
Run Code Online (Sandbox Code Playgroud)

java mqtt paho

3
推荐指数
1
解决办法
5046
查看次数

LocalDateTime 以数组格式表示

我在 Java 8 中使用 spring boot 2.2.6 和 Jackson 2.10.3。我在整个项目中使用 localdatetime 对象。Jackson 无法正确解析 LocalDateTime(或者可能是默认格式)并以如下数组格式在 json 响应中发送日期

        "createdDate": [
            2020,
            8,
            31,
            0,
            0,
            0,
            80000000
        ]
Run Code Online (Sandbox Code Playgroud)

Spring Boot中的JSON Java 8 LocalDateTime 格式所述,Spring Boot 2 已经在类路径上默认设置了 jackson-datatype-jsr310:2.10.3。我希望日期在整个项目中以 json 表示为 2020-03-31:00。第一个解决方案在上面的链接中不起作用。在那之后,我尝试了 @JsonSerialize 注释并且它有效,但我不想应用于每个类。所以也试图覆盖对象映射器但它没有用

@Primary
    @Bean
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, true);
        SimpleModule module = new SimpleModule("my custom date serializer");
        module.addSerializer(LocalDateTime.class,new LocalDateTimeSerializer());
        mapper.registerModule(module);
        return mapper;
    }
Run Code Online (Sandbox Code Playgroud)

还尝试自定义 Jackson2ObjectMapperBuilder,但仍然有数组格式的日期

@Bean
    public Jackson2ObjectMapperBuilder …
Run Code Online (Sandbox Code Playgroud)

java spring-boot objectmapper jackson2

3
推荐指数
1
解决办法
709
查看次数

将Xml配置转换为resource.groovy

我是grails的新手,我想将xml配置转换为resource.groovy.但是xml中有名称空间.我不想在这里复制配置.应该有一个配置是resource.groovy

我的xml是

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:util="http://www.springframework.org/schema/util"
    xmlns:neo4j="http://www.springframework.org/schema/data/neo4j"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/data/neo4j
            http://www.springframework.org/schema/data/neo4j/spring-neo4j.xsd">

            <context:component-scan base-package="neo4j"></context:component-scan>


    <util:map id="config">
        <entry key="ha.server_id" value="2" />
        <entry key="ha.initial_hosts" value="127.0.0.1:5001,127.0.0.1:5002" />
        <!-- put in more config parameters here, http://docs.neo4j.org/chunked/stable/ha-configuration.html -->
    </util:map>
    <bean id="graphDbFactory"
        class="org.neo4j.graphdb.factory.HighlyAvailableGraphDatabaseFactory" />
    <bean id="graphDbBuilder" factory-bean="graphDbFactory"
        factory-method="newHighlyAvailableDatabaseBuilder">
        <constructor-arg value="/home/alok/Desktop/data4" />
    </bean>
    <bean id="graphDbBuilderFinal" factory-bean="graphDbBuilder"
        factory-method="setConfig">
        <constructor-arg ref="config" />
    </bean>
    <bean id="graphDatabaseService" factory-bean="graphDbBuilderFinal"
        factory-method="newGraphDatabase" destroy-method="shutdown" />

    <neo4j:config graphDatabaseService="graphDatabaseService"   base-package="neo4j"/>
    <neo4j:repositories base-package="neo4j" />

</beans>
Run Code Online (Sandbox Code Playgroud)

我想知道如何处理命名空间和构造函数参数

grails groovy

1
推荐指数
1
解决办法
645
查看次数

MQTT:在特定的 client_id 上一次又一次地断开连接

我面临特定 client_id 断开连接的问题。当我尝试连接时,它会突然断开连接并显示错误

1450599983: New connection from 192.168.2.245 on port 1883.
1450599983: Client 46144 disconnected.
1450599983: New client connected from 192.168.2.245 as 46144 (c0, k60).
1450599984: Socket error on client 46144, disconnecting.
Run Code Online (Sandbox Code Playgroud)

我的conf.d文件是

# Place your local configuration in /etc/mosquitto/conf.d/
#
# A full description of the configuration file is at
# /usr/share/doc/mosquitto/examples/mosquitto.conf.example

pid_file /var/run/mosquitto.pid

persistence true
persistence_location /var/lib/mosquitto/

log_dest file /var/log/mosquitto/mosquitto.log

include_dir /etc/mosquitto/conf.d
cleansession true
Run Code Online (Sandbox Code Playgroud)

有时会在发送消息后发生。为什么会发生这种情况,我们该如何解决这个问题?

谢谢

mqtt mosquitto

0
推荐指数
1
解决办法
3005
查看次数