Submit a 'null' to a jsp from an html form - html

Forwarding an html form to a jsp page which has an
<input type="text" name="name">
for 'name' parameter to be processed in jsp page. When no name is supplied , I do want the form to be submitted to the jsp and jsp should detect 'null' to process an if-else loop to display a relevant message.
How do I achieve that?

I do want the form to be submitted to the jsp and jsp should detect
'null' to process an if-else loop to display a relevant message.
You can use this on your display.jsp page to check if value is not null and not empty:
<%
String name = request.getParameter("name");
if(name != null && !name.isEmpty()){
%>
<p>name is <%=name%></p>
<%
}else{
%>
<p>name is null or empty!</p>
<%
}
%>
But as mentioned already this is highly discouraged! You should be using a servlet. If you want to see how that can be done, let me know and i'll edit this answer with a better solution.

Related

For loops in ejs

I have a array containing some html content like this.
const articleArray=['<p>first text</p>\r\n','<p>second text></p>\r\n','<p>third text</p>\r\n']
I need to render this in an ejs file through a get request
request.render('viewArticles',{array : articleArray})
where 'viewArticles' is an ejs file. I have used the middleware to set the view engine as ejs.
This is the code in ejs
<% for(arr in array) {%>
arr
<% } %>
I am not able to render any html. How to solve this?
'<%- %>' this is help to print html code as it is.
<% 'Scriptlet' tag, for control-flow, no output
<%_ ‘Whitespace Slurping’ Scriptlet tag, strips all whitespace before it
<%= Outputs the value into the template (HTML escaped)
<%- Outputs the unescaped value into the template
<%# Comment tag, no execution, no output
<%% Outputs a literal '<%'
%> Plain ending tag
-%> Trim-mode ('newline slurp') tag, trims following newline
_%> ‘Whitespace Slurping’ ending tag, removes all whitespace after it
for refrence please click visit this site EJS
<% array.forEach(function(item) {%>
<%-item%>
<% }) %>
Try this
<% array.forEach(function(item,index){ %>
<%= item %>
<% }) %>
I'm not really sure how to do what you want exactly , but take a look at this:
First, instead of you creating an array of HTML elements, how about you create an array of objects, like so :
const articles = [{text: "first text"} , {text: "second text"}, {text: "third text"}];
this way you just have to write the HTML once, and I am fairly new to programming but I don't see a scenario where you would get a response in HTML, usually you query a database for data or from a JSON file... and assuming the array is actually getting passed to the .ejs file, lets iterate though it,
<% for(let a of articles){ %>
<p> <%= a.text %> </p>
</br>
<% } %>
If the array is NOT getting passed, check for these in your code :
// If you installed
..."dependencies" : {
"ejs": "x.x.x",
} //Check the package.json file
// If you imported correctly
import ejs = require("ejs");
// If you specified the views path
app.set("views", path.join(__dirname, "views"));
// And the views engine
app.set("view engine", "ejs");
// And your route
request.render('viewArticles',{ articles : articles }) // Check if the file name is correct, I get this wrong many times

if statement not executed in JSP scriptlet

i encountered the following problem. I have made a table in mysql named 'users' and i want to add users using JSP. The primary key is the Email and i want to check before adding another user if the email already exists. If the email already exists the users will not be added to the database and a message "email already exists" will appear.
I created ResultSet rs object and extracted the "Email" column into a String email using a while loop.Now, here comes the problem. Suppose i have a user with the "denis#yahoo.com" email. If i try to add an user with the exact same email an error will occur which means my if statement was ignored. I looked up in the debug mode for the variables email and Email and they had the exact same "denis#yahoo.com" and still the if statement was ignored.
<!-- file name: addUser.jsp -->
<%
String Email=request.getParameter("Email");
String Name = request.getParameter("Name");
String Adress = request.getParameter("Adress");
String Phone = request.getParameter("Phone");
if (Email != null)
{
jb.connect(); // connect to the database using JavaBean class
ResultSet rs;
rs=jb.seeTable("users");// rs gets first row of table
String email;
int a=1;
while(rs.next())
{
email=rs.getString("Email");
if(Email==email)
{
a=0;
jb.disconnect();
%>
<p> The email already exists</p>
<%
break;
}
}
if(a==1){
jb.addUser(Email,Name, Adress, Phone);
jb.disconnect();
%>
<p>Data has been added.</p>
<%
}
} else {
%>
<form action="addUser.jsp" >
Email: <input type="text" name="Email"><br>
Name: <input type="text" name="Name"><br>
Adress: <input type="text" name="Adress"><br>
Phone: <input type="text" name="Phone"><br>
<button type="submit" >Add User</button><br>
</form>
<%
}
%>
I use NetBeans IDE 8.2, and something that i think is odd appeared in the debug mode. One of the email i try to test appeared with bold characters meanwhile the other was not bold.
Why is my if statement ignored if i add an user with the exact same email of another? Please help me out!

Database changes in radio button in jsp

I have written a code where the admin has the access to change the general users from active to inactive and vice-versa. So I want to update the database if the radio button is changed from active to inactive.
Here is the code:
<%
while (rs.next()) {
String firstname = rs.getString("firstname");
String lastname = rs.getString("lastname");
String email = rs.getString("email");
String password = rs.getString("password");
String age = rs.getString("age");
String sex = rs.getString("sex");
String haddress = rs.getString("haddress");
String oaddress = rs.getString("oaddress");
String phonenumber = rs.getString("phonenumber");
String flag = rs.getString("flag");
Statement stmt1 = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
%>
<tr>
<td>
Name: <% out.println(firstname); %> <% out.println(lastname); %>
</td>
<td>
<% if (flag.equals("A")){ %>
Active: <input type="radio" value="A" name="<% out.println(email); %>" onclick="<% stmt1.executeUpdate("update assignment set flag='A' where email='"+email+"'");
System.err.println("A"+email); %>
alert('changed to active');" checked>
Inactive: <input type="radio" value="I" name="<% out.println(email); %>" onclick="<% stmt1.executeUpdate("update assignment set flag='I' where email='"+email+"'");
System.err.println("I"+email); %>
alert('changed to inactive');">
<%
}else if(flag.equals("I")){%>
Active: <input type="radio" value="A" name="<% out.println(email); %>" onclick="<% stmt1.executeUpdate("update assignment set flag='A' where email='"+email+"'");
System.err.println("A"+email); %>
alert('changed to active');">
Inactive: <input type="radio" value="I" name="<% out.println(email); %>" onclick="<% stmt1.executeUpdate("update assignment set flag='I' where email='"+email+"'");
System.err.println("I"+email); %>
alert('changed to inactive');" checked>
But in output, when I change one radio button, all the queries run automatically, updating the database to I for all the data in the DB.
Using onclick, you need to invoke a ajax call and update the response . You should not use like onclick="<%SOME SQL Query%>". That is why it's updating all the rows.
Step 1:
" onclick="updatestatus(this.value, '<% out.println(email); %>')"/>
Step 2 :
Add Jquery lib and add a JS function
function updatestatus(statuschg, email) {
/*ajax call to some update-status.jsp with email and current value needs to be passed */
//ajax code goes here ...
$.ajax({
type: "post",
url: "update-status.jsp", //this is my servlet
data: "email=" +email"&status="+statuschg,
success: function(msg){
alert(msg);
}
});
}
Ref: How to invoke ajax call How to pass parameters in GET requests with jQuery
step 3:
i) In update-status.jsp,Establish db connection
ii) receive parameters of the email address and current status.
iii) Execute the Query
stmt1.executeUpdate("update assignment set flag='+status+' where email='"+email+"'")
iv) out.println("Updated");
You are mixing two different codes. The key is to realize, where and when each code is executed - JSP on the server when the page is requested and rendered (i.e. before the response is send to the browser) and Javascript in the browser, after the browser receives the already generated response.
I.e. in your
onclick="<% stmt1.executeUpdate("update assignment set flag='I' where email='"+email+"'"); System.err.println("I"+email); %> alert('changed to inactive');"
the <% stmt1.executeUpdate("update assignment set flag='I' where email='"+email+"'"); System.err.println("I"+email); %> part is executed on the server when the page is generated, and only the alert('changed to inactive'); waits in browser until the input field is clicked.
What you need is AJAX.
Side note: Do not put Java code into JSP, use MVC pattern, or at least put the code into an "util" class and call the class from JSP.

How can I save each item in a "select multiple" field in its own MySQL record (using Rails)?

Thanks for any help you can provide! I have a Ruby on Rails application where I am trying to save maps with driving directions and waypoints. The data needs to come straight out of the entry form instead of the Google Maps javascript. I've solved the starting and ending points, but the waypoints are giving me a problem.
My questions:
How can I save each waypoint in its own record in the Waypoint table? I'm able to get the first waypoint into the table, but the rest of the "select multiple" options are ignored.
How can I make each waypoint.newsavedmap_id field the same as its corresponding newsavedmaps id so that I can call these up later?
HTML
<p>Enter a street address, city, and state:
<input id="startinput" type="text" name="starthere" size="56"></p>
<p>Or, select a location from the list:
<select id="startdrop" name="startthere">
<option value="">
<% for masterlocation in #masterlocation %>
<option value="<%= masterlocation.street_address %> <%= masterlocation.city %>, <%= masterlocation.state %>, <%= masterlocation.zip %>"><%= masterlocation.place_name %></option>
<% end %>
</select></p>
<div><b>Stops</b></div>
<div id="multiselectdiv1">
<select multiple id="waypoints" name="waypointsselected">
<% for masterlocation in #masterlocation %>
<option value="<%= masterlocation.street_address %> <%= masterlocation.city %>, <%= masterlocation.state %>, <%= masterlocation.zip %>"><%= masterlocation.place_name %></option>
<% end %>
</select>
</div>
<b>End</b>
<p>Enter a street address, city, and state:
<input id="endinput" type="text" name="endhere" size="56"></p>
<p>Or, select a location from the list:
<select id="enddrop" name="endthere">
<option value="">
<% for masterlocation in #masterlocation %>
<option value="<%= masterlocation.street_address %> <%= masterlocation.city %>, <%= masterlocation.state %>, <%= masterlocation.zip %>"><%= masterlocation.place_name %></option>
<% end %>
</select></p>
</div>
<div>
<input type="submit" onclick="calcRoute();" id="showmapview" value="Show Map">
</div>
I have two MySQL tables. The first is newsavedmaps:
id
itinerary_id
start
start_lat
start_long
start_masterlocation_id
end
end_lat
end_long
end_masterlocation_id
name
The second is waypoints:
id
newsavedmap_id
waypoint
waypoint_lat
waypoint_long
waypoint_masterlocation_id
The two are meant to be connected by newsavedmaps.id and waypoint.newsavedmap_id .
My newsavedmap_controller.rb includes:
def create
#newsavedmap = Newsavedmap.new(params[:newsavedmap])
#newsavedmap.name = params[:newsavedmapname]
if !params[:starthere].blank?
#newsavedmap.start = params[:starthere]
else
#newsavedmap.start = params[:startthere]
end
if !params[:endhere].blank?
#newsavedmap.end = params[:endhere]
else
#newsavedmap.end = params[:endthere]
end
if !params[:waypointsselected].blank?
#waypoint = Waypoint.new(params[:waypoint])
#waypoint.waypoint = params[:waypointsselected]
end
Edit 1
In response to Colinm's suggestion to wrap the controller in an iterator to get separate records for each address, I tried this, but I'm pretty sure I'm doing the wrong thing:
if !params[:waypointsselected].blank?
for waypoint in #waypoint
#waypoint = Waypoint.new(params[:waypoint])
#waypoint.waypoint = params[:waypointsselected]
#waypoint.newsavedmap = #newsavedmap
end
end
How can I save each waypoint in its own record in the Waypoint table? I'm able to get the first waypoint into the table, but the rest of the "select multiple" options are ignored.
Unless you have a really good reason not to, use Rails' form helpers instead of rolling your own form fields. They will take care of this automatically, as well as handle edge cases you may not even know about. (Like the gotcha that sending a multiple select back with no selections will leave the record unchanged. That doesn't sound like it's an issue in your use case, but Rails still has your back if you use the form helpers.)
In your case, you'd simply pass multiple: true in the html_options hash, like so:
<%= f.select :waypointsselected,
MasterLocation.waypoints_for_select,
{},
{ multiple: true }
%>
Note that this does assume you implement a waypoints_for_select method. Without seeing all the code, it looks like you have way too much logic in your view right now. It's brittle and verbose to construct the options array in the view; offloading that to the model or a helper keeps your view code cleaner and helps eliminate potential future bugs.
If you absolutely can't/absolutely don't want to use form helpers in this application, the key you're looking for is []. Rails sensibly assumes a form field represents a single value unless you explicitly denote it as an array. Just tack an empty array on the end of the field name:
<select multiple id="waypoints" name="waypointsselected[]">
...and that field's key in the params hash will instead contain an array of values representing the selected items:
{ waypointsselected: ["3", "6", "9"] }
As for associating the waypoints with the newsavedmaps, just set it explicitly during creation. You're almost there:
if !params[:waypointsselected].blank?
#waypoint = Waypoint.new(params[:waypoint])
#waypoint.waypoint = params[:waypointsselected]
# You can do it like this...
#waypoint.newsavedmap = #newsavedmap
# Or using the ID...
#waypoint.newsavedmap_id = #newsavedmap.id
end
(I haven't adapted this code to deal with the fact you now have an array of values in waypointsselected; I just plugged the relationship definitions into your existing code. Remember to adjust your code to expect an array and iterate over it.)

Retrieving the value of select option in Servlets

I have a select tag in my form which is to be send to Servlet. I have made the contents of the select tag dynamic(it gets values from a table column in DB).
Select Branch:-<select>
<%
while(r.next()){
%>
<option><%=r.getString("code")%></option>
<%
}
r.close();
s.close();
con.close();
%>
</select>
('r' is ResultSet)
My problem is how can i send the value the user has selected from select tag to servlet. For using Request.getparameter("name") I must know the value of option tag.
I my confused.Please help..
Thanks.
Assign a unique name to select tag. <select name="codeSelect">
However, this isn't the right way to approach this, perform all the database interaction in Servlet and set appropriate request parameter and forward it to jsp.
<select id="codes">
<%
while(r.next()){
%>
<option value="<%=r.getString("code")%>"><%=r.getString("code")%></option>
<%
}
r.close();
s.close();
con.close();
%>
</select>
Now, you can get the value of 'codes'