在我的Spring项目中,我将注销目标URL设置为"/ login?logout"以显示登录页面,并显示消息"您现在已注销".
在Spring Security配置中,我这样做了:
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/error").permitAll()
.anyRequest().fullyAuthenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.successHandler(loginSuccessHandler)
.failureUrl("/login?error")
.and()
.httpBasic()
.and()
.logout()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
.permitAll()
.logoutSuccessHandler(logoutSuccessHandler);
}
Run Code Online (Sandbox Code Playgroud)
和logoutSuccessHandler:
public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws IOException, ServletException {
if (authentication != null) {
Log.debug(authentication.getName() + " LOGOUT !!");
}
setDefaultTargetUrl("/login?logout");
super.onLogoutSuccess(request, response, authentication);
}
Run Code Online (Sandbox Code Playgroud)
当我尝试注销时,我到达页面"/ login"(没有?logout).我不明白为什么它会在这个页面上重定向我.
我认为该应用程序试图将我重定向到"/ login?logout",但由于我不再连接,Spring安全性要求我再次登录.
当我在登录时尝试访问"/ login?logout"页面时,它会显示正常页面.
我通过添加以下内容找到了解决此问题的方法:
.authorizeRequests()
.antMatchers("/error","/login").permitAll()
Run Code Online (Sandbox Code Playgroud)
为什么不loginPage("/login").permitAll()这样做?我做错什么了吗?
我有一个项目,我使用Jacoco来计算代码覆盖率.我在这里使用maven配置:
使用Jenkins,我运行"mvn clean install test".它在/ target/site/jacoco-ut /文件夹中生成报告.如果我打开index.html文件,我会看到:
但是当我在jenkins工作中打开JaCoCo Coverage报告时,我看到了:
它说每个测试覆盖0%的代码.我不明白为什么我在html报告中没有相同的结果.
<plugin>
<groupId>org.jacoco</groupId>
<artifactId>jacoco-maven-plugin</artifactId>
<version>0.7.5.201505241946</version>
<executions>
<!--
Prepares the property pointing to the JaCoCo runtime agent which
is passed as VM argument when Maven the Surefire plugin is executed.
-->
<execution>
<id>pre-unit-test</id>
<goals>
<goal>prepare-agent</goal>
</goals>
<configuration>
<!-- Sets the path to the file which contains the execution data. -->
<destFile>${project.build.directory}/coverage-reports/jacoco-ut.exec</destFile>
<!--
Sets the name of the property containing the settings
for JaCoCo runtime agent.
-->
<propertyName>surefireArgLine</propertyName>
</configuration>
</execution>
<!--
Ensures …Run Code Online (Sandbox Code Playgroud) 我正在将我的Spring应用程序从Spring-boot 1.5.9迁移到Spring-boot 2.0.0.有了这个新的Spring包,我在Redis中缓存数据时遇到了一些问题.
在我的配置中,我有3个不同的TTL(长,中,短)CacheManager:
@Bean(name = "longLifeCacheManager")
public CacheManager longLifeCacheManager() {
RedisCacheConfiguration cacheConfiguration =
RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(redisExpirationLong))
.disableCachingNullValues();
return RedisCacheManager.builder(jedisConnectionFactory()).cacheDefaults(cacheConfiguration).build();
}
Run Code Online (Sandbox Code Playgroud)
我还有一个自定义的RestTemplate:
@Bean
public RedisTemplate<?, ?> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<?, ?> template = new RedisTemplate<>();
template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
template.setConnectionFactory(connectionFactory);
return template;
}
Run Code Online (Sandbox Code Playgroud)
使用之前的Spring版本,每个缓存的数据都使用此RestTemplate并使用GenericJackson2JsonRedisSerializer进行序列化.
使用新的Spring版本,CacheManager不使用RestTemplate,而是使用自己的SerializationPair.这个结果是使用默认的JdkSerializationRedisSerializer序列化的所有内容.
是否可以将CacheManager配置为使用RestTemplate以及如何使用?如果不可能,我该怎么做才能使用JacksonSerializer而不是JdkSerializer?
我想创建一个在请求生命周期中唯一的UUID.为此,我使用@Scope("request")注释创建一个UUID bean.
@Bean
@Scope(scopeName = WebApplicationContext.SCOPE_REQUEST)
public UUID requestUUID() {
return UUID.randomUUID();
}
Run Code Online (Sandbox Code Playgroud)
我想在我的控制器中访问这个bean.所以我用@Autowired注入它.这很好用.
@Controller
public class DashboardController {
@Autowired
UUID uuid;
@Autowired
WelcomeMessageService welcomeMessageService;
@Autowired
IssueNotificationService issueNotificationService;
@RequestMapping("/")
public String index(Model model) throws InterruptedException, ExecutionException {
System.out.println(uuid);
PortalUserDetails userLog = getPortalUserDetails();
BusinessObjectCollection<WelcomeMessage> welcomeMessages = welcomeMessageService.findWelcomeMessages(
20,
0,
userLog.getZenithUser(),
userLog.getConnectionGroup().getConnectionGroupCode(),
"FR");
if(welcomeMessages!=null) {
model.addAttribute("welcomeMessages", welcomeMessages.getItems());
}
BusinessObjectCollection<IssueNotification> issueNotifications =
issueNotificationService.findIssueNotifications(userLog.getZenithUser());
if(welcomeMessages!=null) {
model.addAttribute("welcomeMessages", welcomeMessages.getItems());
}
model.addAttribute("issueNotifications", issueNotifications);
return "index";
}
}
Run Code Online (Sandbox Code Playgroud)
控制器调用多个服务.每个服务都使用RestTemplate bean.在这个RestTemplate bean中,我想得到UUID.
@Component
public class ZenithRestTemplate extends RestTemplate …Run Code Online (Sandbox Code Playgroud) 我有一个使用 Linux 的 systemd 作为服务启动的 Spring 启动应用程序。
它基于此文档:http : //docs.spring.io/spring-boot/docs/current/reference/html/deployment-install.html
使用默认脚本,jar 文件启动。它工作正常。
/etc/systemd/system/myapp.service :
[Unit]
Description=myapp
After=syslog.target
[Service]
User=myapp
ExecStart=/var/myapp/myapp.jar
SuccessExitStatus=143
[Install]
WantedBy=multi-user.target
Run Code Online (Sandbox Code Playgroud)
现在我想在 jar 启动时添加 VM 选项。我试图向项目添加一个 .conf 文件,但它不起作用。
/var/myapp/myapp.conf :
JAVA_OPTS=-Xms256M -Xmx512M
Run Code Online (Sandbox Code Playgroud)
如何添加 JVM 选项以使用 systemd 启动应用程序?
我有一个使用 Spring MVC 和 Spring Boot 的项目,我使用 IntelliJ。我的项目是这样的:
main -> java -> mypackage -> authentification -> WebSecurityConfig.java
-> configuration -> ApplicationConfiguration.java
-> controller -> WelcomeMessageController.java
-> service -> WelcomeMessageService.java
-> Impl -> WelcomeMessageServiceImpl.java
test -> java -> mypackage -> WelcomeMessageTest.java
Run Code Online (Sandbox Code Playgroud)
我用@Service.
我用
@Configuration
@ComponentScan(basePackages = "mypackage")
Run Code Online (Sandbox Code Playgroud)
在控制器中,我注入了服务
@Autowired
WelcomeMessageService welcomeMessageService;
Run Code Online (Sandbox Code Playgroud)
在测试类中,我使用相同的注解注入相同的服务:
@Autowired
WelcomeMessageService welcomeMessageService;
Run Code Online (Sandbox Code Playgroud)
我用以下注释测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = ApplicationConfiguration.class, loader = SpringApplicationContextLoader.class)
@WebAppConfiguration
Run Code Online (Sandbox Code Playgroud)
在控制器中,注入工作正常,但在测试类中,IntelliJ 说:
无法自动装配。未找到 WelcomeService 类型的 bean。
当我运行测试时,它可以工作,但我不明白为什么 IntelliJ 说它找不到 bean。
我发现这个主题说它在 IntelliJ 中发生了一段时间,但我不想使用@SuppressWarnings注释。 …
我有一个项目,我使用Spring MVC和Thymeleaf.我需要根据每个用户的偏好为每个用户显示不同格式的日期.例如,UserA希望显示像MM/dd/yyyy这样的日期,而UserB想要显示dd/MM/yyyy等日期.
为此,我使用此thymeleaf参数:
th:value="${#dates.format(myDate, dateFormat)}"
Run Code Online (Sandbox Code Playgroud)
值"dateFormat"基于用户首选项.这很好用.
我的问题是日期输入是一个表单,当我提交表单时,它不采用良好的格式.我总是得到MM/dd/yyyy.
如果我选择格式dd/MM/yyyy并输入18/01/2016,在我的春季控制器中我获得"Thu Jun 01 00:00:00 CEST 2017",对应于2017年6月1日在dd/MM/yyyy .
如何以我想要的格式提供日期?
这是我的代码:
<form th:action="@{/test}" th:object="${filter}" th:method="POST">
<input type="date" th:type="date" class="form-control" th:id="myDate"
th:name="myDate" th:value="${#dates.format(filter.myDate, dateFormat)}"/>
</form>
Run Code Online (Sandbox Code Playgroud)
控制器:
@RequestMapping(value = "/test", method = RequestMethod.POST)
public String myTest(@ModelAttribute Filter filter, Model model) {
Systeme.out.println(model.dateFormat);
// dd/MM/yyyy
Systeme.out.println(filter.myDate.toString());
// Thu Jun 01 00:00:00 CEST 2017
return "test";
}
Run Code Online (Sandbox Code Playgroud) 我有一个Spring mvc和Spring boot的项目.
该项目部署在JBoss服务器上,application.properties文件位于此服务器上.
现在我想为弹簧控制器编写一个测试.对于此测试,我需要使用安全配置.在安全配置文件中,我有@Value注释来从application.properties文件中获取值.
鉴于该文件不在项目中,我如何模拟它来运行我的测试?
这是我的测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {PortalWebSecurityConfig.class})
@WebAppConfiguration
public class DashboardControllerTests {
@Mock
private IssueNotificationManager issueNotificationManager;
@InjectMocks
private DashboardController dashboardController;
private MockMvc mockMvc;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders.standaloneSetup(dashboardController).build();
}
@Test
@WithMockCustomZenithUser(customUser = "LOGIN")
public void dashboardControllerTestOk() throws Exception {
when(issueNotificationManager.findIssueNotifications("User"))
.thenReturn(new BusinessObjectCollection<>());
mockMvc.perform(get("/").with(testSecurityContext()))
.andDo(print())
.andExpect(status().isOk())
.andExpect(view().name("index"))
.andExpect(model().size(4))
.andExpect(model().attributeExists("issueNotifications"));
verify(issueNotificationManager).findIssueNotifications("User");
}
}
Run Code Online (Sandbox Code Playgroud)
我的日志文件中有此错误:
09:16:19.899 [main] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Searching for key 'ad.domain' in [environmentProperties]
09:16:19.899 [main] DEBUG o.s.c.e.PropertySourcesPropertyResolver - Searching for key 'ad.domain' …Run Code Online (Sandbox Code Playgroud) 对于我的 Spring boot 应用程序,我有一个用于运行该应用程序的 .conf 文件。在这个文件中,我放置了一些 jvm 选项。目前它包含这个:
JAVA_OPTS="-Xms256m -Xmx512m -Dvisualvm.display.name=ApplicationWs -Dcom.sun.management.jmxremote.port=3333 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false"
Run Code Online (Sandbox Code Playgroud)
将来我肯定会添加其他选项,并且生产线的尺寸也会增加。我想通过逐行编写一两个选项来使其更具可读性。但我找不到合适的语法。
我想做这样的事情:
# Heap Size
JAVA_OPTS="-Xms256m -Xmx512m"
# JVisualVM Name in VisualVM
JAVA_OPTS="$JAVA_OPTS -Dvisualvm.display.name=ApplicationWs"
# Jmx Configuration
JAVA_OPTS="$JAVA_OPTS -Dcom.sun.management.jmxremote.port=3333 -Dcom.sun.management.jmxremote.ssl=false -Dcom.sun.management.jmxremote.authenticate=false"
Run Code Online (Sandbox Code Playgroud)
我已经尝试过了:
JAVA_OPTS="-Xms256m -Xmx512m"
JAVA_OPTS="$JAVA_OPTS -Dvisualvm.display.name=ApplicationWs"
export JAVA_OPTS
Run Code Online (Sandbox Code Playgroud)
JAVA_OPTS="-Xms256m -Xmx512m"
JAVA_OPTS="${JAVA_OPTS} -Dvisualvm.display.name=ApplicationWs"
export JAVA_OPTS
Run Code Online (Sandbox Code Playgroud)
JAVA_OPTS="-Xms256m -Xmx512m
-Dvisualvm.display.name=ApplicationWs"
Run Code Online (Sandbox Code Playgroud)
JAVA_OPTS="-Xms256m -Xmx512m "
+ " -Dvisualvm.display.name=ApplicationWs"
Run Code Online (Sandbox Code Playgroud)
spring-boot .conf 文件中多行字符串的正确语法是什么?