Form submit and HttpServletRequest - java

I'm facing this problem with regards to Forms and Requests. I'm using sencha and javascript to create a webpage that POSTs a form to a java web application which pulls data from a database and formats it before returning a html page to the client.
The problem I'm facing is that for some reason, while the form does get filled(checked using the debugger in chrome), the java program does not recognise the parameter within the form, and instead reads it as null.
I'm following the method of setting the form from an old java program, which works, however it fails for mine. Does anyone know how I can solve this or where I might be doing wrong?
I've included the javascript and java codes where I decide which page to return below.
Javascript handler for function call to submit form:
var MenuA = function() {
simple.getComponent('flag').setValue('MenuA');
simple.getEl().dom.action = './Soap';
simple.getEl().dom.method = 'POST';
simple.submit();}
Java code to decide choice of page:
if (request.getParameter("flag").matches("MenuA")) {
choice = 2;
} else if (request.getParameter("flag").matches("MenuB")) {
choice = 3;}
FormPanel Code:
var simple = new Ext.form.FormPanel({hidden:true,standardSubmit:true,
items:[
{xtype: 'textfield', hidden: true, name : 'password', label: 'Password', id:'password'}
,{xtype: 'textfield', hidden: true, name : 'user', label: 'user', id:'user'}
,{xtype: 'textfield', hidden: true, name: 'flag', label: 'flag', id: 'flag'}]})

Your
request.getParameter("flag").matches("MenuA");
method is looking for a form element whose name is "flag".
Since your form may not contain the flag field so it assumes it to be null.
So, to overcome you can add an input field to the form with name "flag" and put put your desired value in it.
I think this should work for you.

Nevermind. Found the problem. I didn't realise the form was not being sent properly. Sorry for the trouble!

Related

How to pass javascript variable in jsp page to another java file?

Good Evening, I try to do a checkbox which embedded in a JSP page. I use document.getElementByID("checkbox") in the JSP javascript function. How to pass the variables in the javascript function to another java file without passing it through url for security concern?
This is Checkbox Function:
var checkbox = document.getElementById("chbx");
function foo(){
if(checkbox.checked=true){
//passThisVariableToAnotherJavaFile-isChecked
}
else {
//passThisVariableToAnotherJavaFile-isNotChecked
}
};
This is Java File:
public class CheckBoxEvent{
if(isChecked) {
//then whatever
} else if (isNotChecked) {
//then no whatever
}
}
I am a newbie is this jsp stuff, I used to be doing this in PHP but everything mixed-up in my mind when there is a HashMap appear in the java file. Well, need some hints and help.
Thank You
How to pass the variables in the javascript function to another java file without passing it through url for security concern?
You have two options here and in both the cases you need to send the value to the server for processing :
An AJAX POST or GET request. This looks more appropriate to your requirement. You can get an example here.
Submit the form using POST.
Read here When do you use POST and when do you use GET?
In both the cases , there will be a Servlet/JSP/Controller handling the request in the server. You can call the methods in your Custom Java class with the request parameters.
when you do var checkbox = document.getElementById("chbx"); you are doing it at client side. Now if you want to propagate this value to server side i.e to some java class(most of the cases it will be servlets) then you have two options:-
1)Make an AJAX call. (You can also use jquery here to make AJAX call).Here is
the small example, you can find ample on google
$.ajax({
type: 'GET',
dataType: 'json',
url: servlerURL,
success: function(reply) {
},
error: function (xhr, textStatus, errorThrown) {
}
});
or
2)Submit the form

Is it possible to pass a JavaScript Variable to Java code inside a Scriptlet

I have a Scriptlet inside a function , which gets data from a Session and checks for a value inside the Map
Can i pass the User Selected Option which is a javascript variable to a Map ??
function checker()
{
var selObj = document.getElementById('selSeaShells');
var optionselectedvalue = selObj.options[selObj.selectedIndex].value.split(':')[0];
if(optionselectedvalue==''||optionselectedvalue==null)
{
alert('Select a Book');
return false;
}
if (!text_form.quan.value)
{
alert('Enter Quantity');
return false;
}
var selectedbook = optionselectedvalue;
var selectedquantity = text_form.quan.value;
<%
Map cart = (Map) session.getAttribute("cart");
if(cart.containsKey(selectedbook))
{
String quant = (String) cart.get(str);
}
%>
return true;
}
javascript plays on client side and JSP plays on server side.
What you need is you have to make a server request. And send that string a query parameter.
You might misunderstand that jsp and javascript existed on same document. Yes but JSP part compiles on server side itself and JSP output is sent to the client.
So solutions are: either go for html form submit or go for Ajax request.
java processing is done at server side and javacript executes on client side. If you do view source on html page you wont find any map.So you can not pass the javascript value to java code (as java code has already been processed by server and its no more).
If you are really want to pass the javascript value to server side you can take help help of ajax or form submission as Baadshah pointed above

Ext.Store Send multiple data at once

I am creating a one to many form in one transaction. I really need the record to be created entirely, or not at all. I have implemented a back code using java to rollback all operation should one of the data does not meet the requirement. Interface is using extjs, and I have REST interface with Jackson.
The problem is, how is the best way for ExtJS 4 to send everything in a particular form along with all detail records to a URL? Despite anything I have done, Ext.Store seems to send the data one by one.
Well, in short, I need the Ext.Store to POST something like this as raw with application/json content:
{
id: '',
party: 3,
machine: 'x1',
product: 'pr001',
runtime: 12,
materials: [{
item: 'rm001',
qty: '39.01',
align: '9.930'
}, {
item: 'rm002',
qty: '20.03',
align: '9.0234'
}]
}
The problem is, the child store always send the data as it is entered, and when I set autoSync to false, it still sends them one by one not everything at once through parent store.
Any example code?
Thank you
the way that I do it is through xml but the Idea should be the same
I have the parent store contain a serialize function
and it looks something like this
serialize: function(){
var store = this;
var xml = [];
store.each(function(record){
xml.push('id:'+record.get(id))
xml.push('party:'+record.get(party))
record.materials().each(function(materials_rec){
xml.push('item:'+materials_rec.get(item));
...
});
});
return xml.join('');
}
so I call this function from the controller and I submit an ajax request that will contain all the records of the parent and child stores

Ruby on Rails, How to Update Div with Ajax on like/unlike

So the problem I am having is getting my like/unlike button to refresh with ajax in my Ruby on Rails app, here is my code:
app/views/_comment.html.haml
- likes = comment.likes
%div.comment{id: "comment-#{comment.id}"}
.comment-avatar
.medium-user-avatar.avatar-canvas
- if comment.user.avatar_url
= image_tag comment.user.avatar_url(:medium)
- else
%span.medium-user-initials.initials-decoration
= comment.user.avatar_initials
%span.comment-username= link_to(comment.user_name, "#")
%span.comment-body~ markdown(comment.body)
.comment-time
= time_ago_in_words(comment.created_at) + " ago"
- if can? :like, comment
= " · "
- if likes.find_by_user_id(current_user.id).nil?
= link_to "Like", like_comment_path(comment), method: :post, remote: true
- else
= link_to "Unlike", unlike_comment_path(comment), method: :post, remote: true
- if comment.user == current_user
= " · "
= link_to "Delete", comment_path(comment), method: :delete, remote: true,
:data => { :confirm => "Are you sure you want to delete this comment?" }
- if likes.count > 0
.comment-likes
- likers = likes.map { |like| link_to(like.user_name, "#") }
- if likers.length > 1
- likers = likers.slice(0, likers.length - 1).join(", ").concat(" and " + likers.slice(-1))
- else
- likers = likers[0]
= "Liked by #{likers}".html_safe
app/controllers/comments_controller.rb
class CommentsController < BaseController
load_and_authorize_resource
def destroy
destroy!{ discussion_url(resource.discussion ) }
end
def like
comment_vote = resource.like current_user
Event.comment_liked!(comment_vote)
#redirect_to discussion_url(resource.discussion )
render :partial => "like"
comment_likes
end
def unlike
resource.unlike current_user
#redirect_to discussion_url(resource.discussion)
render :partial => "unlike"
comment_likes
end
def comment_likes
render :partial => "comment_likes"
end
end
and then the .js.erb files for like, unlike and comment_likes:
app/views/_like.js.erb
$(".comment-time a#like").html("<%= escape_javascript(render('.comment-time a#like'")
app/views/_unlike.js.erb
$(".comment-time a#unlike").html("<%= escape_javascript(render('.comment-time a#unlike'")
app/views/_comment_likes.js.erb
$(".comment-likes a##").html("<%= escape_javascript(render('.comment-likes a##'")
Currently clicking like will update the database but will not show the changes until a page refresh, I just want to refresh the individual div's with ajax. A little more information about the div's could help so the ruby creates the html and contained in that as an example is or when already liked I just need to refresh these divs to show the latest from the database aswell as which contains http://localhost:3000/comments/7/unlike 500 (Internal Server Error)"
The rest of the scripting has been done in coffeescript if that matters? I read that the controller functions should use .js.erb so hope this isn't affecting it all. (Im sure my js.erb's are wrong)
I'm not sure if this is the main problem but one thing to fix would be the render statement in your .js.erb files.
The Rails render method requires as its argument the erb template or action to render. When you call:
render('.comment-time a#unlike')
Rails will try to find a template with the name ".comment-time a#unlike" somewhere in your view path which will probably raise some kind of error. Make sure you pay attention to the difference between what's happening in your javascript (in the client) in your application (on the server.)
So one way to fix this would be as follows. First check what part of the view you want to update, for simplicity's sake because you already have the _comment partial let's use that. Second figure out which part in the dom it should replace, in your case the div with the current comment's ID. We can then do the following:
$("#comment-<%= #comment.id %>").replace_html(
"<%= escape_javascript render('comments/comment', :comment => #comment) %>"
);
This will render the _comment.html.erb partial in app/views/comments, insert the result (escaped) into the javascript in your (dis-)like.js.erb and send that back to the browser to execute. The browser will then replace_html on the comment's div (indicated by the ID.)
Because we're replacing the whole comment div you can use the same method for both like and dislike. If you need to save bandwidth you could fine tune it to only re-render the like button itself, but for now this will work.
The problem is your Controller does not know how to respond to the ajax request. By default the render method will render html.erb or in your case html.haml templates.
Unless you do something like:
respond_to do |format|
format.js { comment_likes }
end
Now if an ajax requests comes in the _comments_likes.js.erb template will be rendered.
If you have more of these ajaxy type questions there are efforts being put into rewriting the ajax guides for rails.
And by the by, please consider cleaning up your view.

Duplicate Validation Errors in Struts2

I am using validate() in my Action and here is how my validate() method looks.
public void validate() {
logger.info(".validate() : userName=["+userName+"] & password=["+password+"]");
clearActionErrors();
if(userName==null || userName.length()==0){
addFieldError( "userName", "User Name is required." );
}
if(password==null || password.length()==0){
addFieldError( "password", "Password is required." );
}
}
And in the jsp i added in the section.
The errors are showing up as expected. How ever when i refresh the page i see errors twice. Also if i keep refreshing it the no.of times the error message gets displayed is incremented by 1.
Not sure what's wrong with this.
I tried even calling clearActionErrors(); in my execute() method and that doesn't seem to resolve the Issue.
thanks
If you are using a table on ur jsp to display the form, then make sure that the table is a parent of the form tag. If the table is a child of form tag, the validation messages wont get cleared each time. Making the form tag as a child of table tag would solve your problem.

Categories

Resources