How to invoke a controller using a html link in Sp

2020-07-30 03:49发布

问题:

I have a jsp page called reports.jsp and I have displayed the links in the view for a user to click. How can I invoke Spring controller method by clicking on the link that will pass an argument.

回答1:

You have to use @PathVariable in order to do this. Example:

Jsp:

<a href="<c:url value="/test/${object.argument}" />" >hello</a>

Controller:

@RequestMapping(value = "/test/{argument}", method = RequestMethod.GET)
    public String Controller(@PathVariable("argument") String argument) {
       ...
    }


回答2:

I have resolved the answer by creating a link:

<a href=".../test?argName=arg1" >hello</a>

Controller:

@RequestMapping(value = "/test", method = RequestMethod.GET, params = {"argName"})
    public String Controller(@RequestParam(value="argName", required = true, defaultValue = null) String argName) {
       ...
       //Now do exciting things with variable argName
    }


回答3:

On the JSP page

<a class="opcion"  href="<%= request.getContextPath()%>/inicio">Inicio</a>

And in the controller part backend

@Controller
public class HomeController {
    @RequestMapping(value = "/inicio", method = RequestMethod.GET)
    public String index(ModelMap model){
        model.addAttribute("message", "cargaGeneracion");
        return "index";
    }
}