I made an index page in which you take the value of checkbox and pass it on to a file named AddToWork.java but it is showing null pointer exception. There is some problem in passing the value of the checkbox. Kindly help. Here is the code snipped for index page
<td>
<center>
<form action="addtowork?id2=<%=mail.getTempToken()%>" method="post">
<input type="submit" value="Add to my work">
<input type="checkbox" name="flag" value="flag">High Priority</form>
</center></td>
for AddToWork.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
EmailDesc mail = new EmailDesc();
String imp = new String();
imp = (String) request.getParameter("flag");
String thisid = request.getParameter("id2");
Home home = new Home();
User user = new User();
user = (User) request.getSession().getAttribute("user");
mail = home.getEmail(thisid, user);
home.givePermanentToken(mail,thisid);
if (imp.equals("flag")){
System.out.println("Priority Changed to " + mail.getPriority() + "!");
}
response.sendRedirect("index1.jsp");
}
If I remove the if statement in addtowork.java, the code runs perfectly.
it is because your "imp" Object is pointing to nothing (null) & it is throwing an exception. use "Yoda notation" like so
if("flag".equals(imp)){
// your code
}
this removes the possibility of getting a null pointer exception
Case 1: name.equals("Java") Compare unknown value with known value.
We are comparing name(unknown) value with another string Java(known) value. name will be decided based on some database call, calling another method, etc... It may possible you get null value of name and possible chances of java.lang.NullPointerException or you have to check explicitly for null value of name.
Case 2: "Java".equals(name) Compare known value with unknown value.
We are comparing Java(known) value with another string name(unknown) value. Same way name will be decided based on some database call, calling another method, etc... But equals and equalsIgnoreCase method of String will handle the null value and you don't have to check explicitly for null value of name.
In your case
/* You are getting `null` for variable `imp` */
imp = (String) request.getParameter("flag");
Change
if (imp.equals("flag")){
System.out.println("Priority Changed to " + mail.getPriority() + "!");
}
to
if ("flag".equals(imp)){
System.out.println("Priority Changed to " + mail.getPriority() + "!");
}
Case I : When you are submitting the form with checking the check box , it will work because the value is set in request parameter flag
Case II : When you are submitting the form without checking the "priority" check box then the request parameter sets to null and later you calling the equal method on null on if condition. so please use
if("flag".equals(imp))
Note :- It's bad practice to create string using new
String imp = new String(); //bad don't use this
String imp = ""; //use in this way
Related
I am working on HTML tables. For that I am returning JSON from my Java code. I have a UI as HTML page where there is a form having from date to date and a select tag having 4 options like this
<form id="formId" method="get">
<div class="container">
<h4>Start Date:</h4>
<input type="text" id="startdate" name="fromdate" width="276"
placeholder="dd/mm/yyyy" required />
<h4>End Date:</h4>
<input type="text" id="enddate" name="todate" width="276"
placeholder="dd/mm/yyyy" required />
<h4>Outlets:</h4>
<select name="outlet" id="all">
<option>ALL</option>
<c:forEach var="item" items="${obj.outlet}">
<option>${item}</option>
</c:forEach>
</select>
<br>
<br>
<div>
<button id="button" class="btn btn-default" type="submit">Search</button>
</div>
</div>
</form>
I am taking that input from the form and getting values in the servlet in doget method like below:
String fromdate=request.getParameter("fromdate");
String todate=request.getParameter("todate");
String outlet=request.getParameter("outlet");
// System.out.println(String.format("fromdate: %s, todate: %s, outlet: %s", new Object[]{fromdate, todate, outlet}));
List<String> outletList = Arrays.asList(outlet.split("\\s*,\\s*"));
try {
String json = HourlySalesDateOutlet.createJson(outletList, fromdate, todate);
response.getWriter().write(json);
// System.out.println("dheeraj"+json);
}
catch (Exception e) {
e.printStackTrace();
}
}
Now here is my Java class where I have written two queries one for if the user selects all and other if user select specific outlet. My problem is the if statement is not executing only else is executing if the user selects one outlet from FORM if the user selects ALL then it's not working.
Below is my code:
public static String createJson(List<String> outletList, String startDate, String endDate) throws Exception {
Connection con = null;
String query1;
List<Map<String, String>> mapList = new LinkedList<Map<String, String>>();
String outletStr = outletList.stream().collect(Collectors.joining("','", "('", "')"));
if (outletList.equals("ALL")) {
query1 = "SELECT a.OUTLET,b.CUSTOMERDESCRIPTOR,a.BILLDATE,HOUR(a.BILLTIME) AS HOURS, SUM(a.NETAMOUNT) AS AMOUNT FROM SYNCBILL a,ecustomer b WHERE a.OUTLET=b.CUSTOMERIDENTIFIER AND a.CANCELLED<>'Y' AND a.BILLDATE BETWEEN STR_TO_DATE(REPLACE('"
+ startDate + "','/','.'),GET_FORMAT(DATE,'EUR')) AND STR_TO_DATE(REPLACE('" + endDate
+ "','/','.'),GET_FORMAT(DATE,'EUR')) GROUP BY OUTLET,BILLDATE,HOUR(BILLTIME)";
System.out.println("all"+query1);
} else {
query1 = "SELECT a.OUTLET,b.CUSTOMERDESCRIPTOR,a.BILLDATE,HOUR(a.BILLTIME) AS HOURS, SUM(a.NETAMOUNT) AS AMOUNT FROM SYNCBILL a,ecustomer b WHERE a.OUTLET=b.CUSTOMERIDENTIFIER AND b.CUSTOMERDESCRIPTOR in "
+ outletStr + " AND a.CANCELLED<>'Y' AND a.BILLDATE BETWEEN STR_TO_DATE(REPLACE('" + startDate
+ "','/','.'),GET_FORMAT(DATE,'EUR')) AND STR_TO_DATE(REPLACE('" + endDate
+ "','/','.'),GET_FORMAT(DATE,'EUR')) GROUP BY OUTLET,BILLDATE,HOUR(BILLTIME)";
System.out.println("2"+query1);
}
try {
con = DBConnection.createConnection();
PreparedStatement ps = con.prepareStatement(query1);
ResultSet rs = ps.executeQuery();
Map<RecordKey, Long> mapData = getMapList(rs);
}
I am not posting the full Java code. What I want is if the user selects all then if statement should execute and the query in it should execute. If the user selects else, then other should work, and here in my code only else is working if is not executing.
How can I debug this?
I have a simple solution for your problem. When user selects all, then in that case pass the empty list and while making the query just put this condition.
if (outletList.size()==0) {
// case for all
} else {
// do regular stuff
}
As pointed out in the comments, you're not comparing comparable types. outletList is a List and it can't be equated to a String even though the list may only contain a single element that happens to be a String. So, outletList.equals("ALL") doesn't do what you think it does.
But that raises an interesting point. You have a select list which isn't multiple so why return a list of what is always a single value? And why switch to sending back an empty list when ALL is selected? That doesn't make sense; there was a single selection made as expected. This adds unnecessary confusion.
Try instead sending back the single value as a String and letting that value determine the logic so you have flexibility. If it's not possible to avoid the list then accept only a single value (list[0] for example) and call equals on that not the List.
if(outletList[0].equals("All")) {...}
If you later find yourself in a situation where you need more than a single if-else pair, you can switch to a switch like so:
switch(outletList[0]) { // or the single value...
case "ALL":
...
...
default:
...
}
<%String dest = request.getParameter("destination").toUpperCase();%>
Hello...
I got a little bit problem here. I am using the above code to get value from form. When use the code without toUpperCase(), it was a success. But, when I add toUpperCase() I got HTTP Status 500 - An exception occured processing JSP page.
When you get value null from request.getParameter("destination"), apply toUpperCase() to a null value gives an error.
Try to do like this:
<%String dest = request.getParameter("destination");
if(dest!=null){
dest = dest.toUpperCase();
}
%>
The request.getParameter() returns String value or a null value from client.
More than likely, request.getParameter("destination") is returning null in your code, which would be why it's throwing an error. If the parameter is not found, then null is returned, otherwise a String is returned.
So you'll want to verify that it's not null
<% String dest = request.getParameter("destination");
if(dest != null) {
dest = dest.toUpperCase();
}
%>
I tried with my own class MeterLimitVal and with less complex example Pager class. The bind method doesn't work correctly, because it's Map parameter is null. I am able to see that from the debug checks I put to bind method. As a result I get Bad request error message.
#Override
public F.Option<Pager> bind(String key, Map<String, String[]> data) {
//if (data.containsKey(key + ".index") && data.containsKey(key + ".size")) {
// try {
System.out.println("Pager: bind()");
System.out.println("Pager: bind() key > " + key);
System.out.println("Pager: bind() data > " + data);
index = Integer.parseInt(data.get(key + ".index")[0]);
size = Integer.parseInt(data.get(key + ".size")[0]);
System.out.println("Pager: bind() > index, size > " + index + ", " + size);
return F.Option.Some(this);
...
}
I implemented Pager class exactly in the same way as previous link, then got rid of ..data.containsKey checks in bind method, that's the reason why I get Bad requests, otherwise F.Option.None() is returned.
I create Pager object in my controller's method pipeIndex and then at the end of this method I pass that object to return value:
return ok(views.html.pipeIndex.render(pager1, ...);
Here's the important parts of pipeIndex template(pipeIndex.scala.html):
#(pager1: models.Pager, ...)
...
<div class="accordion" id="accordion2">
<form class="form-horizontal" action="#routes.Application.indexResults(0, "pipe_consequence_index", "desc", pager1)" method="GET">
...
<input type="submit" id="searchsubmit" value="#Messages("calculate.index")" class="btn btn-primary">
</form>
part of routes file:
GET /indexResults controllers.Application.indexResults(p:Int ?= 0, s ?= "pipe_consequence_index", o ?= "desc", pager1:models.Pager)
When clicking the button the application is supposed to show the indexResults page, but I get Bad request error message.
I tried to search Playframework's integration test pages for an example. From the unit test class I learned using Call class and put it to my Controller's method pipeIndex where I create Pager class:
Pager pager1 = new Pager();
Call call = routes.Application.indexResults(0, "pipe_consequence_index", "desc", pager1);
System.out.println("Call URL > " + call.url());
This shows the call URL in the expected way:
Call URL > /indexResults?pager1.index=45&pager1.size=313
When I try to hack the address line in my browser, I am able to get into indexResults page.
http://localhost:9000/indexResults?pager1.index=0&pager1.size=0
Somehow the parameters going to bind method doesn't go in the correct way (null :( ), when indexResults is called from template. Did you see that kind of problem? Can you help me?
Cheers,
Alparslan
I got some troubles with some codes. Now I try to modify/delete personal information , but I enter an invalid value try modify/delete , it's still pop a new window . I dont know how to modify those code for i enter an invalid value , it will not pop a window .
I have other question . When I enter a valid value , the value cant pass to pop window , like I enter a name to go grab id value , the value cant pass to pop window , how can I reslove it . Thank all !
HTML
<h:panelGrid columns="3" cellspacing="20">
<h:outputLabel for="name" value="Modify Name"/> <p:inputText value="#{modify.enName}"/>
<h:commandButton value="Modify System" style="height:35px" onclick="window.open('#{modify.domodify()}','modify',
'width=500,height=400,status=yes,resizable=yes,scrollbars=yes') ; return false;"/>
</h:panelGrid>
Java Code
public String domodify() {
try {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("com.mycompany_SuneCoolingSystem_war_1.0-SNAPSHOTPU");
EmployeeJpaController jpaController = new EmployeeJpaController(null, emf);
EntityManager e = jpaController.getEntityManager();
Query q = e.createNamedQuery("Employee.findByEnName");
q.setParameter("enName", getEnName());
System.out.println(getEnName());
List resultList = q.getResultList();
Employee result = (Employee) resultList.get(0);
id = result.getId();
name = result.getName();
idNumber = result.getIdNumber();
constellation = result.getConstellation();
email = result.getEmail();
enName = result.getEnName();
rego="CRUD/Modify.xhtml";
} catch (Exception ex) {
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, "No Man", ""));
rego = "index.xhtml";
}
return rego;
}
onclick="window.open('#{modify.domodify()}','modify', 'width=500,height=400,status=yes,resizable=yes,scrollbars=yes')
This code means when clicked, open a new window and perform the action to check what URL is returned. The windows is opened before any logic is executed.
You should perform an ajax call to the modify with f:ajax (or your component library equivalent, if you want) and use onevent to launch the correct javascript when the ajax calls ends in success and returning the expected value.
See JSF 2: How show different ajax status in same input? to see an example of dealing with onevent.
I have created a simple servlet in which a user will be presented with 2 questions, answering either true or false. My problem lies in retrieving the answers selected by the user.
Code:
out.println("<FORM ACTION=\"Game\" METHOD = \"POST\">" +
"<b>Question 1: Are you over the age of 25? </b><br> <br>" +
"<input type = \"radio\" name = \"Q1rad1\" onclick = \"getAnswer('a')\"> True " +
"<input type = \"radio\" name = \"Q1rad2\" onclick = \"getAnswer('b')\"> False<br>" +
"<br><br><b>Question 2: Are you from earth?</b><br> <br>" +
"<input type = \"radio\" name = \"Q2rad1\" onclick = \"getAnswer('a')\"> True " +
"<input type = \"radio\" name = \"Q2rad2\" onclick = \"getAnswer('b')\"> False<br>" +
out.println("<Center><INPUT TYPE=\"SUBMIT\"></Center>");
);
Each question has 2 radio buttons, Q1rad1 & Q2rad2, for answering True or False. How can i know the value selected by each user when the submit button is pressed.
I understand it may be more efficient when using Javascript but for the purposes of this problem I must be using servlets.
You have to define the value you want to retrieve when the radio button is selected
The value setting defines what will be submitted if checked.
The name setting tells which group of radio buttons the field belongs to. When you select one button, all other buttons in the same group are unselected.
<input type="radio" name="Q2" onclick="getAnswer('b')" value="b">
<input type="radio" name="Q2" onclick="getAnswer('a')" value="a">
In your Servlet which will recieve the request you'll have something like
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// get the value of the button group
String q2 = request.getParameter("Q2");
// compare selected value
if ("a".equals(q2)) {
...
}
...
}
You haven't named your radio buttons correctly. Each radio option for the same question need the same name attribute. Also, you should have a value attribute on each <input type="radio">. I'm not sure you need the onclick handler at all. You should also have a </form> closer tag. Your form might look like this:
out.println("<form action=\"Game\" method=\"POST\">" +
"<b>Question 1: Are you over the age of 25? </b><br> <br>" +
"<input type = \"radio\" name = \"Q1\" value=\"True\"> True " +
"<input type = \"radio\" name = \"Q1\" value=\"False\"> False<br>" +
"<br><br><b>Question 2: Are you from earth?</b><br> <br>" +
"<input type = \"radio\" name = \"Q2\" value=\"True\"> True " +
"<input type = \"radio\" name = \"Q2\" value=\"False\"> False<br>" +
"<Center><INPUT TYPE=\"SUBMIT\"></Center>" +
"</form>"
);
And then in the doPost() method of servlet that handles the form submission, you can access the values using request.getParameter(). Something like this:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String q1 = request.getParameter("Q1");
String q2 = request.getParameter("Q2");
// more processing code...
}
Give the same name to the radios of the same question, and set different values.
Look at this page.
Then in the request you will get a parameter with the name of the radio group and the value selected.
After submit the servlet the receives the post can use:
String value = request.getParameter("radioName");
For your HTML Code the below lines are enough
protected void doPost(HttpServletRequest req,HttpServletResponse res){
String q1 = request.getParameter("Q1");
String q2 = request.getParameter("Q2");`
}
For example, Considering your HTML Code.
If Q1 is pressed
"TRUE"
then it would be our "Input" in Servlet.