我编写了一个jsp文件和servlet。在jsp中,我在表单中使用了数据列表。我想将该用户输入传递给servlet。我已经发布了下面的代码。
jsp代码
<form action="NewServlet1" method="Post" >
<center>
<input type="text" name="website" list="website" placeholder="Enter your website">
<datalist id="website">
<option value="https://www.google.lk/">GOOGLE</option>
<option value="https://www.yahoo.com/">YAHOO</option>
<option value="https://www.hackerrank.com/">HACKER RANK</option>
</datalist><br><br><br>
</center></form>
<div style="width: 400px; height: 400px">
<canvas id="myChart" width="1000" height="1000" ></canvas>
</div>
<center> <div>
<button id="button1" name="button1" onclick="submit()" class="btn btn-primary">submit</button>
</div></center>
<script>
function Test(today, time) {
var ctx = new Chart(document.getElementById("myChart")
, {
type: 'line',
data: {
labels: today,
datasets: [{
data: time,
label: "Web Service 1",
borderColor: "red",
fill: false
}
]
},
options:
{
scales: {xAxes: [{display: true, scaleLabel: {display: true, labelString: 'date and time'}}], yAxes: [{display: true, ticks: {beginAtZero: true, steps: 100, stepValue: 50, max: 6000}}]},
hover: {intersect: false },
title: {display: true, text: 'response time of selected website'},
tooltips: { mode: 'nearest'}
}
});
}
function submit()
{
$.post("NewServlet1",
{
},
function (data)
{
Test(data.today, data.time);
});
}
servlet代码
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String website = (String)request.getParameter("website");
但这不起作用。有人可以帮我解决这个问题吗?
答案 0 :(得分:1)
首先,您需要将表单提交给servlet,该路径映射到NewServlet1
<form action="NewServlet1" method="Get" >
<center>
<input type="text" name="website" placeholder="Enter your website">
<datalist id="website">
<option value="https://www.google.lk/">GOOGLE</option>
<option value="https://www.yahoo.com/">YAHOO</option>
<option value="https://www.hackerrank.com/">HACKER RANK</option>
</datalist>
</center>
<%
String website= request.getParameter("website"); // it is not needed
request.setAttribute("website",website); // it is not needed
%>
<input type="submit"/> <!--need to add submit button to submit it to the servlet-->
</form>
现在你的servlet代码很好,这是:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
String website = (String)request.getParameter("website");
}
注意:需要在website
文本框
或者,如果您想获得先前存储在attribute
对象中的request
,请使用RequestDispatcher
。