Java Spring:必需参数'username'不存在



当我发送表单时,它会做action="userlogin"方法="post"这是我的代码:

package com.home_project.oop_project.controllers;
import java.sql.*;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
@Controller
public class UserController {
int adminlogcheck = 0;
String usernameforclass = "";
//Some code
@GetMapping("userlogin")
public String userlog(Model model) {

return "userLogin";
}
@RequestMapping(value = "userlogin", method = RequestMethod.POST)
public String userlogin( @RequestParam("username") String username, @RequestParam("password") String pass,Model model) {
try
{
System.out.println(username);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/springproject","root","");
Statement stmt = con.createStatement();
ResultSet rst = stmt.executeQuery("select * from users where username = '"+username+"' and password = '"+ pass+"' ;");
if(rst.next()) {
usernameforclass = rst.getString(2);
return "redirect:/index";
}
else {
model.addAttribute("message", "Invalid Username or Password");
return "userLogin";
}

}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
return "userLogin";
}
}

但是它不会像我期望的那样去'index'。当我通过邮差检查问题时,它说:"trace"org.springframework.web.bind。MissingServletRequestParameterException:方法参数类型字符串的所需请求参数"username"不存在rntat"and "message": "所需参数'username'不存在。"我该怎么办呢?由于

Http请求不包含userName,因为您明确设置了需要的username

// you code -> @RequestParam("username") String username,
// the http request(Missing username!)-> do action="userlogin" method="post". This is my code:
RequestMapping(value = "userlogin", method = RequestMethod.POST)
public String userlogin( @RequestParam("username") String username, @RequestParam("password") String pass,Model model) {

由于您已经定义了RequestParam,它需要作为请求URL的一部分,而不是正文。

http://localhost: 8080/spring-mvc-basics/api/登录吗?用户名= abc

。https://www.baeldung.com/spring-request-param

如果你打算把它作为正文的一部分(它必须,因为密码不应该在URL中),然后使用下面的loginInfo是存储用户名和密码的DTO。

RequestMapping(value = "userlogin", method = RequestMethod.POST)
public String userlogin( @RequestBody LoginInfo loginInfo) {

最新更新