![](/img/trans.png)
[英]How to call a java method from jsp by clicking a menu in html page?
[英]How to call a java method by clicking a button in JSP and also pass parameter?
我需要将用户给出的参数传递给java方法。
我有一个控制器类,两个JSP,一个index.jsp和bresult.jsp,我需要的是索引页面:用户可以给出一个输入,并通过“添加”按钮调用需要该参数的java方法。
在我的控制器中:
@Autowired
public void setA(Scheduler schedulerObject) {
this.schedulerObject = schedulerObject;
}
@GetMapping("/")
public String index() {
return "index";
}
@PostMapping("/bresult")
public String bresult(@RequestParam("newMachineType") String newMachineType, Model model) throws InterruptedException
{
schedulerObject.loadDataBase();
schedulerObject.createDefaultMachines();
some other codes here...
return "bresult";
}
的index.jsp:
<form action="bresult" method="post">
<table>
<tr>
<td>Enter new machine type:</td>
<td><input id="newMachineType" name ="newMachineType"></td>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form>
所以在索引中如果我想添加任何新机器,在给出类型后,一个按钮会将它添加到列表中,如果我点击提交,它将根据我的其他代码给出结果。
如何调用并将参数(机器类型)传递给我的java方法,但是只有点击添加按钮?
您的操作正确指向您的方法
<form action="bresult" method="post">
@PostMapping("/bresult")
你的param(在html中)在控制器中使用相同的名称
<td><input id="newMachineType" name ="newMachineType"></td>
@RequestParam("newMachineType") String newMachineType
它不起作用吗? 您可以在控制器类中正常使用String。 你在课堂上使用过@Controller吗? 尝试使用System.out.println(newMachineType)并查看控制台以验证该变量的值,并检查是否与您在html中传递的相同。
更改post方法以获取HttpServletRequest
以获取表单值作为参数。
https://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletRequest.html
@PostMapping("/bresult")
public String bresult(HttpServletRequest request, Model model) throws InterruptedException
{
// ----
String newMachineType = request.getParameter("newMachineType");
...
// If more than one parameter for machine type
String newMachineType2 = request.getParameter("newMachineType2");
String newMachineType3 = request.getParameter("newMachineType3");
String newMachineType4 = request.getParameter("newMachineType4");
...
// ----
schedulerObject.loadDataBase();
schedulerObject.createDefaultMachines();
some other codes here...
return "bresult";
}
对于多个动态实体。 你可以改变你的html方法:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js">
</script>
<script>
$(document).ready(function(){
var counter = 0;
$( "#addButton" ).click(function() {
$('body > form > table > tbody > tr > td:nth-child(2)').after('<td><input id="newMachineType" name ="newMachineType' + counter + '"></td>');
counter++;
});
});
</script>
<button id="addButton" type="button">Add new machine type</button>
<form action="bresult" method="post">
<table>
<tr>
<td>Enter new machine type:</td>
<td><input type="submit" value="Submit"/></td>
</tr>
</table>
</form>
编辑HTML以添加新机器的按钮。 所以你可以添加你需要的数量。 然后提交所有这些并从bresult()
获取值bresult()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.