当我发送表单时,它会执行action="userlogin"method="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'。当我通过postman检查问题时,它说:""trace":"org. springframe.web.bind.MissingServletRequest estParameterException:方法参数类型String的必需请求参数'username'不存在\r\n\tat"和"message":"必需参数'username'不存在。"我该怎么办。谢谢
RequestMapping(value = "userlogin", method = RequestMethod.POST)
public String userlogin( @RequestParam("username") String username, @RequestParam("password") String pass,Model model) {
正如你所定义的,它需要作为请求URL的一部分,而不是一个主体。
http://localhost:8080/spring-mvc-basics/api/login?username=abc
例如https://www.baeldung.com/spring-request-param
如果您打算将其作为主体的一部分(它必须这样做,因为密码不应该在URL中),然后使用以下loginInfo是存储用户名和密码的DTO。
RequestMapping(value = "userlogin", method = RequestMethod.POST)
public String userlogin( @RequestBody LoginInfo loginInfo) {