首页 > 解决方案 > 如何从前端到后端检索 url 参数并在控制台中打印它们?

问题描述

我正在尝试在输入中插入文本并提交它,以便我可以在后端获取它。这是它在前端的样子:

<form th:action="@{/student/mypage/}">
        <label><h3><b>Friend Token:</b></h3>
        </label><br>
           <input type="text" th:name = "friendToken"/>
           <input type="submit" />
        </form>

这就是它在后端的样子:

@Controller
@RequestMapping(path = "/student/mypage")
public class MyPageController {

    //Fields
    private final StudentService studentService;
    private final StudentAccountService studentAccountService;

    //Constructor
    @Autowired
    public MyPageController(StudentService studentService, StudentAccountService studentAccountService) {
        this.studentService = studentService;
        this.studentAccountService = studentAccountService;
    }

    /* ~~~~~~~~~~~ Get MyPage View ~~~~~~~~~~~ */
    @GetMapping
    @PreAuthorize("hasRole('ROLE_STUDENT')")
    public String getMyPage(Model model)
    {

        LoggedAccount loggedAccount = new LoggedAccount();

        if(loggedAccount.checkIfStandardAccLogged())
        {
            model.addAttribute("devUsernameAccount", loggedAccount.getLoggedUsername());
        }
        else
        {
            StudentAccount loggedStudentAccount = studentAccountService.getLoggedStudentAccount();
            //query call in db to get info of logged student
            Student infoStudent = studentService.findStudentByNameAndSurname(loggedStudentAccount);

            //getting info about logged acc (credentials) && student info
            model.addAttribute("loggedStudentAccount", loggedStudentAccount);
            model.addAttribute("infoStudent", infoStudent);
            //checkup in case we log in with a dev account
            model.addAttribute("isDevAcc", loggedAccount.checkIfStandardAccLogged().toString());
        }

        return "pages/layer 4/info pages/mypage";
    }

    @RequestMapping(value = "/{friendToken}", method = RequestMethod.POST)
    public void updateFriendToken(
            @PathVariable(required = false, name = "friendToken") String friendToken,
            Model model
    )
    {
        System.out.println("Friend Tokenul este " + friendToken);
    }
}

正如您所看到的,当我按下提交调用名为 updateFriendToken 的请求方法并从 url 获取路径变量并在控制台中打印它时,我想要。我知道我可能做错了很多事情,所以请随意更改 html 代码和 java。我的项目使用 SpringBoot 和 Java 作为后端,HTML、CSS、JS 脚本和 Thymeleaf 作为前端。我正在添加网站的图片,我知道我的 url 不正确,并且我无法以这种方式获取任何路径变量,但我真的不知道如何获取我在 FriendToken 文本框中插入的文本。

在此处输入图像描述

非常感谢您的帮助!

标签: javaspringspring-bootthymeleafhttp-request-parameters

解决方案


尝试修改

@PathVariable(required = false, name = "friendToken") String friendToken

@RequestParam("friendToken") String friendToken

推荐阅读