JSP中的Form Action不能调用不同的方法



我有一段Java代码,它使用Spring框架调用JSP中的每个表单操作的不同方法。然而,它并没有像预期的那样工作。这两种形式分别工作,即当其中一种被移除时。但是它们加在一起调用的方法都是在form action中首先声明的那个。

JAVA方法:

package com.example.demo.controller;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.example.demo.dao.AlienRepo;
import com.example.demo.model.Alien;
@Controller
public class AlienController {
    @Autowired
    AlienRepo repo;
    
    @RequestMapping("/")
    public String home() {
        return "home.jsp";
    }
    @RequestMapping("add")
    public String add(Alien alien)
    {
        repo.save(alien);
        return "home.jsp";
    }
    @RequestMapping("get")
    public ModelAndView get(String text)
    {
        ModelAndView mv = new ModelAndView();
        int id = Integer.parseInt(text);
        mv.setViewName("show.jsp");
        mv.addObject("alien", repo.findById(id));
        return mv;
    }
}

JSP文件:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="get">
<input type="text" name="text"><br>
<input type="submit">
<form/>
<form action="add">
<input type="text" name="aid"><br>
<input type="text" name="aname"><br>
<input type="submit">
<form/>
</html>

我找不到任何错误,正如我独立说的,他们工作得很好。因此,所有其他文件应该是正确的,如果需要可以提供。你能帮我解决这个缺货的问题吗?

你必须指定你的方法参数是什么,因为你正在使用get方法,所以@RequestParam注释将被使用,例如:-

    @RequestMapping("/add")
public String add(@RequestParam("aid") String aid, @RequestParam("aname") String aname)
{
    Alien alien = new Alien();
    alien.setId(aid);
    alien.setName(aname);
    repo.save(alien);
    return "home.jsp";
}

    @RequestMapping("/get")
public ModelAndView get(@RequestParam("text") String text)
{
    ModelAndView mv = new ModelAndView();
    int id = Integer.parseInt(text);
    mv.setViewName("show.jsp");
    mv.addObject("alien", repo.findById(id));
    return mv;
}

用下面的代码修复了jsp文件:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="get">
<input type="text" name="text"><br>
<input type="submit">
</form>
<form action="add">
<input type="text" name="aid"><br>
<input type="text" name="aname"><br>
<input type="submit">
</form>
</body>
</html>

最新更新