Java JSP Check if Parameter = 0 and copy it to variable - java

I have to write a small message board as a homework and struggle with a, as I believe, really easy task:
The user is clicking on "Answer" below an article, which is bringing him to the answer.jsp?id=123. There is an input form for his text which submits his entry to a saveanswer.jsp.
The answer.jsp does a mySQL query do retrieve some data, and here do I need to make a "if-then-else" and (I believe) store the result in a variable to use it for the submit-form.
answer.jsp?id=123
<sql:query dataSource="${snapshot}" var="result">
SELECT * from forum where id=<%= request.getParameter("id") %>;
</sql:query>
<c:forEach var="row" items="${result.rows}">
<input type="text" name="title" value="RE: <c:out value="${row.title}"/>"/> <br/>
<textarea name="answertext" cols="50" rows="5"></textarea> <br/>
<input type="hidden" name="answer_id" value="<%= request.getParameter("Id")%>">
There is a field answer_id in the database, and I need to check:
if answer_id == 0;
then
answer_id=id;
else
answer_id_answer_id //do nothing
The result should then be the value of the hidden "answer_id" field.
Unfortunatly, I was not able to get an if-else with the db data or a variable declaration working :/
I tried for 2 days now, you're my last hope.
Thanks for reading, I really would appreciate your help!
Best regards,
DataSlayer

If I understand your question, you are looking to set the value of the hidden input depending on some values, not sure where answer_id is coming from but you want to use a simple condition, even better a ternary condition
${empty value? other:value}
In this simple line, value and other are both variable, if value is empty, this insert other. Update this to your case, since I don't really know where answer_id come from (the DB but from which table)
SQL INJECTION
As RC point it out, you are open to SQL injection with your query since you add directly the parameter into a query.
Someone could set the parameter as
0; drop table forum
This will result in a query like :
SELECT * from forum where id=0; drop table forum;
Dropping your table.
Never concat parameter receive from the client to you query, you never know what it can be. If this is from you, you should be able to trust yourself but the client, NEVER!
To prevent it, use the parameters system provided (never used it but should work)
<sql:query dataSource="${snapshot}" var="count">
SELECT * from forum where id=?
<sql:param value="${ request.getParameter("id") }" />
</sql:update>
This will prevent the injection to happened.

Related

Nested Loop Binding in Thymeleaf

I am making web app using Java/Spring/Thymeleaf and don't seem to be able to get past this problem!
So, here's my thymeleaf template code:
<form th:action="#{/holiday/create}" th:object="${holiday}" method="post">
<select name="user_scroll">
<option th:each="user : ${allUsers}" th:value="${user.id}"
th:text="${user.email}" th:field="${holiday.user_id}" />
</select>
<button type="submit">
Create
</button>
</form>
I have read the related questions on here but am still stumped.
I did read that you can't bind an object directly that's why I am trying to bind to the user_id property of the holiday object. I did suspect the holiday object my be out of scope but that doesn't seem to be the case. Perhaps I am accessing the user_id property incorrectly?
When I click submit and follow debug through to my controller user_id is just sent through as null.
I hope that's enough info - let me know if I need to provide more.
Thanks!
Frankie, try adding the th:field attribute to the select object instead of putting it in the option. Like this:
<select name="user_scroll" th:field="*{user_id}">
Notice the SPel syntax. Starts with an asterisk instead of $ and says user_id instead of holiday.user_id. You can access the field directly this way, since you already have defined it as your selected object in the form definition using
th:object="${holiday}"
This will also bind the selected value to the user_id property of your backing object and should solve the problem.

JSP send data to Java class

I'm looking to send information after each link click to my java class to help increment a counter and to change an object which is held in my bean (myGame) which holds an array of 'cases'. I understand that I can increment a counter using JS, but i'd like to keep all game logic within the bean if possible.
I have considered using forms and changing the anchor to a submit button, however, I'd like to keep that the player can no longer click the link after it the case is eliminated.
The printCase(int) function works by finding the corresponding case in the array, checking the value of a boolean (is the case is eliminated from the game [deal or no deal]) and then prints the amount of money held in the case if eliminated; the case number if it is not.
I have about a dozen cases.
<jsp:useBean id="myGame" scope="session" class="dealOrNoDeal.GameLogic"/>
<table border="1" id="dndTable">
<form action="/../doStuff.jsp" method="post">
<tr>
<td> <%= myGame.printCase(0) %> </td>
</tr>
</form>
</table>
I've also considered changing my bean to a servlet. Does that work? Can you have a bean in a servlet?
Thanks all.
Update: I've made printCase now print the tag that it's within now, as well. Prints as a submit button if the case is not opened, prints as a <p> if it is (I need it to use the class). Attempted putting the <td>s in there as well, but it somehow messes up the formatting.
I'm now looking to get the name of the one button that was clicked, any ideas?
I'm not sure about understand completely your qestion. But i'll try:
U have 2 ways:
You have to build a jquery where on each button click u call a servlet where u send information to your java class;
Using DWR: http://directwebremoting.org/dwr/index.html

Netbeans populating a dropdown list based on another dropdownlist html netbeans

i have an interface where i have two dropdownlists in html,one is mark(marque) of a phone and another is model.so the one of mark works fine(callin data from database(sql)) but i want that each time i choose the dropdown list of model it should not show the whole list of data concerning models from the database but just specific for the marque chosen without refreshin the page.like if i choose the mark Nokia it will automatically show just models of nokia not samsung or any other phone mark! i dont know if mayb its sql on model as in the table model i have (model_tel,marque_tel(which is a foreign key from marque_tel)) so i tryed to use the where command for sql but its not workin because i want to say where marquel_tel='//the marque chosen in the marque dropdownist//' but i dnt know how to do that
in java (html)
the problem is i dont no much about javacsript or ajax.......so if any of u can help it would really mean alot
heres how the example of the code looks like so far(i just wwent straight to the main point here):
<label>Marque:
<span class="small">selectionner la marque</span></label>
<%ResultSet rst = in.executeQuery("select distinct(Marque_Tel) from Marque_Tel");%>
<table id="d"><tr><td id="k">
<select name="marque" id="marque" onchange="displayDate(this)">
<% while (rst.next()) {%>
<option></option>
<option><%=rst.getString(1)%></option> //showin marksfrom data of sql//
<% }%>`
</td></tr></table><br><br><br>
<label>Modele:
span class="small">selectionner le modele</span></label>
//callin phone models from sql database down here//
<%ResultSet rs = in.executeQuery("select * from Modéle_Tel where
marque_tel='"+rst.getString(1).toString()//but this in not workin//"' ");%>
<select name="modele" id="modele" >
<% while (rs.next()) {%>
<option></option>
<option><%=rs.getString(1)%></option>//callin phones models
</select>
<button type="submit">VALIDER</button> </html>
You have to use Ajax for this problem. You cant get populated dropdown list based on another dropdown list without refreshing the page. So, the only option is to use Ajax.

Retrieving inputvalue from JSF-repeat

I have recently come across a question involving JSF and Javabeans.
To get a value from an input you need a declared property with getter and setter in the bean. Now I am trying to generate a list of entities to edit a value (in this code example called number), but how can i retrieve these values (as the ID of h:inputText is empty at this point)?
I have tried to name this ID "name_#{bean.id}", but there is no way to set this value in the bean.
Any help would be appreciated!
index.xhtml
<ui:repeat var="entity" value="#{bean.getEntities()}">
<p>
Value:
<h:inputText id="" value="#{entity.number}" />
</p>
</ui:repeat>
Bean.java
public List<Entity> getEntities() {
return entities;
}
You don't need the client id of the inputText to get the values to the server. As stated in Daniel's comment changes are saved if you submit the surrounding form.
You don't even need to set the id parameter. JSF does it for you.
But your value attribute is not correct. It needs to be
value="#{bean.entities}"

dijit.form.Select re-appears unpopulated?

This is a continuation of an issue I was having yesterday so if it looks familiar, thats why :) It IS a different question tho!
So I have another dijit.form.Select initially created on the page like so;
<c:set var="clazzId" value="${verification.clazz.id}" />
<div id="clazzOptions">
<select id="clazz" name="clazz" style="width:22em" dojoType="dijit.form.Select" maxHeight="140">
<option value="-1" label=" " />
<c:forEach items="${requestScope.clazzes}" var="clazzItem">
<c:choose>
<c:when test="${clazzId eq clazzItem.id}">
<option value="${clazzItem.id}" selected = "true">${clazzItem.name}</option>
</c:when>
<c:otherwise>
<option value="${clazzItem.id}">${clazzItem.name}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
</div>
I then have some javascript that I'm trying to use to swap the contents of the div "clazzOptions" depending on the value chosen from a different drop down (not seen here). If its a certain value, replace the div with a text message, if its any other value, re-show the original dijit.form.Select;
<script type="text/javascript">
var classDropDown;
var classPhDMessage = "PhD's do not require a Class or Grade";
dojo.addOnLoad(function() {
classDropDown = dojo.byId('clazzOptions').innerHTML;
});
function checkForPHD() {
var awardOption = dijit.byId('qualification').attr('displayedValue');
if(awardOption == "PhD"){
dojo.byId('clazzOptions').innerHTML = classPhDMessage;
} else {
dojo.byId('clazzOptions').innerHTML = classDropDown;
}
}
</script>
As you can see I'm trying to capture the innerHTMLof the div as it is when the page loads and then depending on the value chosen in the other drop down (not seen) change between a predefine message and the captured div contents.
The issue is that after the original div contents have been replaced with the message and then the selection changes again away from "PhD" and the original div innerHTML is placed back into the div, the dijit.form.Select re-appears but is completely empty and in fact doesn't appear usable at all? If I remove the dijit.form.Select dojoType and just leave it as a normal select this whole operation works perfectly but I kinda need it to be a dijit.form.Select.
Why won't dijit.form.Select work in this case whereas a normal select does?
You shouldn't use innerHTML to add/remove dijits, especially if you're trying to re-use them.
A dijit is a combination of HTML and Javascript and can be thought of as 'more complex' than simply the contents of a specific node.
You have a number of options:
Disable your dijit.form.Select and add a small note under it (or set it's value) explaining why it's disabled (this is generally a better UI paradigm than removing controls). Depending on your UI this is what I'd try and do
Create a <span> as a sibling of your dijit.form.Select and use CSS to show/hide one of them at a time.
Obviously you'll still get the value of the dijit.form.Select when you submit your form, but because you do server side validation as well as client side validation (I hope :) this won't be a problem
Use the dojo.data API to create a datastore from your "${requestScope.clazzes}" iterator. Use this store when you (programatically) create the dijit.form.Select. Keep track of the current value of said Select somewhere. When you don't need it, call yourSelect.destroy() to properly destroy it, then when you need it again create a new one and set it's value to the saved value from before.
This seems unnecessarily expensive to me tho.

Categories