[英]JSP giving NullPointerException for request.getParameter()
I'm new to jsp and am creating a webpage that has a form with a select box and a few other input boxes. 我是jsp的新手,正在创建一个包含带有选择框和其他一些输入框的表单的网页。 I'm populating these input boxes automatically with values from properties file: 我使用属性文件中的值自动填充这些输入框:
NumConfig.properties NumConfig.properties
SELECT= , ,
ONE=1,I,FIRST
TWO=2,II,SECOND
THREE=3,III,THIRD
Here is my form: 这是我的表格:
<html> <body> <form name="NumDetail" id="NumDetail" method="post"> <div> <table> <tr> <th rowspan="2">Select <select id="SelectText" name="SelectText" onchange="this.form.submit()"> <option value="ONE">ONE</option> <option value="TWO">TWO</option> <option value="THREE">THREE</option> </select> </th> <th align="center">Number</th> <th align="center">Roman</th> <th align="center">Position</th> </tr> <tr> <td align="center"> <input type="text" size=10 id="number"> </td> <td align="center"> <input type="text" id="roman"> </td> <td align="center"> <input type="text" id="position"> </td> </tr> </table> </div> </form> </body> </html>
And this is the JS code I'm using to load values from properties file: 这是我用来从属性文件加载值的JS代码:
< script type = "text/javascript" >
<%
ResourceBundle resource = ResourceBundle.getBundle("NumConfig");
String dbname;
if (request.getParameter("SelectText") == null)
dbname = "SELECT";
dbname = request.getParameter("SelectText");
String[] num = resource.getString(dbname).split(","); %>
var number = "<%= num[0]%>";
var rom = "<%= num[1]%>";
var pos = "<%= num[2]%>";
document.getElementById("number").value = number;
document.getElementById("roman").value = rom;
document.getElementById("position").value = pos; < /script>
I can indirectly open this page by appending ?SelectText value in the URL. 我可以通过在URL中附加?SelectText值来间接打开此页面。 But when opening this page directly I get NullPointerException at the line 但是当直接打开此页面时,我在行中得到NullPointerException
String[] num = resource.getString(dbname).split(",");
Two Questions: 两个问题:
You just need an else
statement 您只需要一个else
语句
if (request.getParameter("SelectText") == null)
dbname = "SELECT";
else
dbname = request.getParameter("SelectText");
To make an option
selected by default, you should try this selected="selected"
. 要使一个option
默认为选中状态,您应该尝试使用selected="selected"
。 Stock the value somewhere and change your selected option dynamically. 在某处存储值并动态更改您选择的选项。
<option value="ONE" selected="selected">ONE</option>
Firstly my recommendation would be not to mix Java code within HTML code in a JSP page. 首先,我的建议是不要在JSP页面的HTML代码中混合Java代码。 Try using a Java Servlet to manage your request and respose so you don't end up having a messy code. 尝试使用Java Servlet来管理您的请求和重新放置,这样您就不会出现混乱的代码。
I'll answer your questions below: 我将在下面回答您的问题:
The code should look like this: 该代码应如下所示:
String dbname = "SELECT";
String requestValue = request.getParameter("SelectText");
if (requestValue != null) {
dbname = requestValue;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.