java—尝试在成功登录后将spring引导用户传输到/home或/index

toiithl6  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(249)

这是一个一般性的快速问题。由于我的母语不是英语,我在谷歌上搜索我需要的东西时遇到了困难。
情况:我创建了一个spring应用程序,我可以通过localhost:8080“它使用了SpringSecurity,在登录后显示了我放在main/resources/static文件夹中的index.html。
我想做的是:我想主页是和自动转移到“localhost:8080/home“或”localhost:8080/index“而不仅仅是”localhost:8080"
我的控制器类:

package com.lukas.ramonas.cms.DAO;

import com.lukas.ramonas.cms.Model.User;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Collection;

@Controller // This means that this class is a Controller
@RequestMapping(path="/home") // This means URL's start with /home (after Application path)
public class MainController {
     // This means to get the bean called user_tableRepository
    // Which is auto-generated by Spring, we will use it to handle the data

//    @GetMapping("/index")
//    public String index() {
//        return "index";
//    }

    @Autowired
    private UserRepository UserRepository;

    @PostMapping(path="/add") // Map ONLY POST Requests
    public @ResponseBody String addNewUser (
            @RequestParam String name,
            @RequestParam String username,
            @RequestParam String password,
            @RequestParam String email,
            @RequestParam Collection roles,
            @RequestParam Boolean confirmed) {
        // @ResponseBody means the returned String is the response, not a view name
        // @RequestParam means it is a parameter from the GET or POST request

        User n = new User();
        n.setName(name);
        n.setUsername(username);
        n.setPassword(password);
        n.setEmail(email);
        n.setRole(roles);
        n.setConfirmed(confirmed);
        UserRepository.save(n);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<User> getAllUsers() {
        // This returns a JSON or XML with the users
        return UserRepository.findAll();
    }

}

如果需要任何额外的信息或代码,我很乐意提供。

vkc1a9a2

vkc1a9a21#

@RequestMapping 接受多个Map,而不仅仅是一个Map:
您可以这样添加:

@GetMapping(value = {"/", "/home", "/index"})
public String index() {
    return "index";
}
8iwquhpp

8iwquhpp2#

默认情况下,Spring Security 会将您返回到您尝试访问的原始禁止url。
例如,如果你试图访问 http://locahost:8080/foobar 如果你是未经认证的,你会得到 302 Redirect/login ,当成功通过身份验证时,您将获得 302 Redirect 回到 /foobar .
如果你想改变这种行为,你可以用几种方法。
你可以设置 successForwardUrl 在你的 HttpSecurity 配置:

http.formLogin()
       .successForwardUrl("/foobar")

或者可以实现接口 AuthenticationSuccessHandler ```
http.formLogin()
.successHandler(customAuthenticationSuccessHandler)

并生成自定义重定向响应:

public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

@Override
public void onAuthenticationSuccess(
    HttpServletRequest request, 
    HttpServletResponse response,
    Authentication authentication
) throws IOException, ServletException {
    // Mutate the response here
}

}

相关问题