Spring how to refresh the page when I received a transaction? - java

I work with Spring Mvc app to develop a bitcoin wallet and I have the controller definition,
#RequestMapping(value = "/")
public String showBitcoinWallet() {
return "index";
}
This returns the index.jsp page provides the relevant infos,
Till the moment the app is not synchronized to the blockchain, it will refresh in every 3000 ms from the script,
<html>
<body>
<!- some code ->
<!- some code ->
</body>
<script>
<% if(!model.isSyncFinished()) {%>
setTimeout(function () {
window.location.reload(1);
}, 3000);
<% }%>
</script>
</html>
For the sending operation, a pop-up opens and the user execute the submission. This operation refresh the page and updates the info(e.g balance, address etc). In the instance of receiving, the page is not refreshed and only updates if I manually refresh.
I need to refresh the page after the user received the money.
I have a method that returns boolean of the receive execution operation,
public static boolean isMoneyReceived() {
try {
WalletMain.bitcoin.wallet().addEventListener(new AbstractWalletEventListener() {
#Override
public void onCoinsReceived(Wallet w, Transaction tx, Coin prevBalance, Coin newBalance) {
// Runs in the dedicated "user thread".
//
// The transaction "tx" can either be pending, or included into a block (we didn't see the broadcast).
Coin value = tx.getValueSentToMe(w);
// System.out.println("Received tx for " + value.toFriendlyString() + ": " + tx);
// System.out.println("Transaction will be forwarded after it confirms.");
}
});
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
return false;
}
}
So, the intension will be to write code the in the <script> that if the isMoneyReceived returns true, then, I would need to refresh the page. In that case, I may need to put the method in an iteration say, while and keep on calling with an if condition.
There might be 2nd option to have done it completely in the controller. I have tried to do it in the index.jsp page inside the <script> tag with no success,
<% while(true) {%>
<% boolean moneyReceived = BitcoinWalletController.isMoneyReceived(); %>
<% if(moneyReceived) {%>
// tried to print something ..
<% System.out.println("-----------------------"); %>
<% System.out.println("Hello, Money Received"); %>
<% System.out.println("-----------------------"); %>
<% moneyReceived = false; %>
<% }%>
<%}%>
I ended up getting the error,
HTTP Status [500] – [Internal Server Error]
Type Exception Report
Message java.lang.ClassNotFoundException: org.apache.jsp.WEB_002dINF.jsps.index_jsp
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
Exception
org.apache.jasper.JasperException: java.lang.ClassNotFoundException: org.apache.jsp.WEB_002dINF.jsps.index_jsp
org.apache.jasper.servlet.JspServletWrapper.getServlet(JspServletWrapper.java:176)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:380)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
javax.servlet.http.HttpServlet.service(HttpServlet.java:742)
How to solve the problem? As mentioned earlier, if i can redirect the page from the Spring controller, that would be fine as well.

The problem with your code is that jsp pages are rendered on the server. So, putting a while loop will pretty much prevent the page from ever getting to the clients browser (and being displayed).
Therefore, the way I suggest is to use an AJAX call to the isMoneyReceived() method and then check the return value using a script.
This is a code sample with jQuery ajax get request:
$("button").click(function(){
$.get("yourTargetInterface", function(data, status){
//your processing code here, with the variable "data" being the response to your request; in this case true or false
});
});
yourTargetInterface should be the interface to your method (e.g. through a servlet, web service, etc.).
You can replace $("button").click with a timeout (e.g. every 3 secs).
Then you can process it with a script and setup the application logic accordingly.

Related

Rails Edit Form

I keep getting this error when i want to enter the edit page "NO ROUTE MATCHES" ,but the weird thing is that when i change the order = #order to #order.listing it goes fine but there is no info to be edited, and i been scratching my head with this error for a while.
This is my Orders Controller:
class OrdersController < ApplicationController
before_action :set_order, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!
# GET /orders
# GET /orders.json
def index
#orders = Order.all
end
# GET /orders/1
# GET /orders/1.json
def show
end
# GET /orders/new
def new
#order = Order.new
#listing = Listing.find(params[:listing_id])
end
# GET /orders/1/edit
def edit
end
# POST /orders
# POST /orders.json
def create
#order = Order.new(order_params)
#listing = Listing.find(params[:listing_id])
#seller = #listing.user
#order.listing_id = #listing.id
#order.buyer_id = current_user.id
#order.seller_id = #seller.id
respond_to do |format|
if #order.save
format.html { redirect_to root_url, notice: 'Pedido creado' }
format.json { render :show, status: :created, location: #order }
else
format.html { render :new }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /orders/1
# PATCH/PUT /orders/1.json
def update
respond_to do |format|
if #order.update(order_params)
format.html { redirect_to #order, notice: 'El pedido fue actualizado' }
format.json { render :show, status: :ok, location: #order }
else
format.html { render :edit }
format.json { render json: #order.errors, status: :unprocessable_entity }
end
end
end
# DELETE /orders/1
# DELETE /orders/1.json
def destroy
#order.destroy
respond_to do |format|
format.html { redirect_to orders_url, notice: 'El pedido fue eliminado con exito' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_order
#order = Order.find(params[:id])
end
# Only allow a list of trusted parameters through.
def order_params
params.require(:order).permit(:address, :city, :state)
end
end
My Edit Page:
<h1>Editing Order</h1>
<%= render 'form', order: #order %>
<%= link_to 'Atras', listing_orders_path %>
Form:
<%= form_for(model: [#listing, order], local: true) do |form| %>
<% if order.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(order.errors.count, "error") %> prohibited this order from being saved:</h2>
<ul>
<% order.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= form.label :address %>
<%= form.text_field :address %>
</div>
<div class="field">
<%= form.label :city %>
<%= form.text_field :city %>
</div>
<div class="field">
<%= form.label :state %>
<%= form.text_field :state %>
</div>
<div class="actions">
<%= form.submit %>
</div>
<% end %>
ADDITIONAL INFO:
Routes.rb:
Rails.application.routes.draw do
devise_for :users
resources :listings do
resources :orders
end
end
Rake routes:
Prefix Verb URI Pattern Controller#Action
new_user_session GET /users/sign_in(.:format) devise/sessions#new
user_session POST /users/sign_in(.:format) devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format) devise/sessions#destroy
new_user_password GET /users/password/new(.:format) devise/passwords#new
edit_user_password GET /users/password/edit(.:format) devise/passwords#edit
user_password PATCH /users/password(.:format) devise/passwords#update
PUT /users/password(.:format) devise/passwords#update
POST /users/password(.:format) devise/passwords#create
cancel_user_registration GET /users/cancel(.:format) devise/registrations#cancel
new_user_registration GET /users/sign_up(.:format) devise/registrations#new
edit_user_registration GET /users/edit(.:format) devise/registrations#edit
user_registration PATCH /users(.:format) devise/registrations#update
PUT /users(.:format) devise/registrations#update
DELETE /users(.:format) devise/registrations#destroy
POST /users(.:format) devise/registrations#create
listing_orders GET /listings/:listing_id/orders(.:format) orders#index
POST /listings/:listing_id/orders(.:format) orders#create
new_listing_order GET /listings/:listing_id/orders/new(.:format) orders#new
edit_listing_order GET /listings/:listing_id/orders/:id/edit(.:format) orders#edit
listing_order GET /listings/:listing_id/orders/:id(.:format) orders#show
PATCH /listings/:listing_id/orders/:id(.:format) orders#update
PUT /listings/:listing_id/orders/:id(.:format) orders#update
DELETE /listings/:listing_id/orders/:id(.:format) orders#destroy
listings GET /listings(.:format) listings#index
POST /listings(.:format) listings#create
new_listing GET /listings/new(.:format) listings#new
edit_listing GET /listings/:id/edit(.:format) listings#edit
listing GET /listings/:id(.:format) listings#show
PATCH /listings/:id(.:format) listings#update
PUT /listings/:id(.:format) listings#update
DELETE /listings/:id(.:format) listings#destroy
pages_about GET /pages/about(.:format) pages#about
pages_contact GET /pages/contact(.:format) pages#contact
seller GET /seller(.:format) listings#seller
root GET / listings#index
rails_postmark_inbound_emails POST /rails/action_mailbox/postmark/inbound_emails(.:format) action_mailbox/ingresses/postmark/inbound_emails#create
rails_relay_inbound_emails POST /rails/action_mailbox/relay/inbound_emails(.:format) action_mailbox/ingresses/relay/inbound_emails#create
rails_sendgrid_inbound_emails POST /rails/action_mailbox/sendgrid/inbound_emails(.:format) action_mailbox/ingresses/sendgrid/inbound_emails#create
rails_mandrill_inbound_health_check GET /rails/action_mailbox/mandrill/inbound_emails(.:format) action_mailbox/ingresses/mandrill/inbound_emails#health_check
rails_mandrill_inbound_emails POST /rails/action_mailbox/mandrill/inbound_emails(.:format) action_mailbox/ingresses/mandrill/inbound_emails#create
rails_mailgun_inbound_emails POST /rails/action_mailbox/mailgun/inbound_emails/mime(.:format) action_mailbox/ingresses/mailgun/inbound_emails#create
rails_conductor_inbound_emails GET /rails/conductor/action_mailbox/inbound_emails(.:format) rails/conductor/action_mailbox/inbound_emails#index
POST /rails/conductor/action_mailbox/inbound_emails(.:format) rails/conductor/action_mailbox/inbound_emails#create
new_rails_conductor_inbound_email GET /rails/conductor/action_mailbox/inbound_emails/new(.:format) rails/conductor/action_mailbox/inbound_emails#new
edit_rails_conductor_inbound_email GET /rails/conductor/action_mailbox/inbound_emails/:id/edit(.:format) rails/conductor/action_mailbox/inbound_emails#edit
rails_conductor_inbound_email GET /rails/conductor/action_mailbox/inbound_emails/:id(.:format) rails/conductor/action_mailbox/inbound_emails#show
PATCH /rails/conductor/action_mailbox/inbound_emails/:id(.:format) rails/conductor/action_mailbox/inbound_emails#update
PUT /rails/conductor/action_mailbox/inbound_emails/:id(.:format) rails/conductor/action_mailbox/inbound_emails#update
DELETE /rails/conductor/action_mailbox/inbound_emails/:id(.:format) rails/conductor/action_mailbox/inbound_emails#destroy
rails_conductor_inbound_email_reroute POST /rails/conductor/action_mailbox/:inbound_email_id/reroute(.:format) rails/conductor/action_mailbox/reroutes#create
rails_service_blob GET /rails/active_storage/blobs/:signed_id/*filename(.:format) active_storage/blobs#show
rails_blob_representation GET /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show
rails_disk_service GET /rails/active_storage/disk/:encoded_key/*filename(.:format) active_storage/disk#show
update_rails_disk_service PUT /rails/active_storage/disk/:encoded_token(.:format) active_storage/disk#update
rails_direct_uploads POST /rails/active_storage/direct_uploads(.:format) active_storage/direct_uploads#create
You have orders set up as a nested resource under listings:
resources :listings do
resources :orders
end
That means -- as you can see from your routes output -- that the URL path for editing an order is:
/listings/:listing_id/orders/:id/edit
I don't think you included the code for the link to the edit page, but my guess is you are using the Rails-generated URL helper, edit_listing_order_path, which takes two parameters: a listing_id and an order ID. If you check that link my guess is you aren't specifying both IDs. The reason I say that is that if you look at the link_to on the edit page:
<%= link_to 'Atras', listing_orders_path %>
It is missing the ID of the appropriate listing record:
<%= link_to 'Atras', listing_orders_path(#listing) %>
I suspect you need to check all the orders paths to ensure you are also specifying the parent listing.
The other thing you likely need to do is load the listing instance in your OrdersController:
def set_order
#order = Order.find(params[:id])
#listing = #order.listing # or from parameters: Listing.find(params([:listing_id])
end

Why do I get an error when running a method from a jsp page, but not from a main method?

I'm making a Java web project in IntelliJ IDEA Ultimate. I have a class with a method that takes two Strings as input, queries a database, and returns an int value. (It's a login method - takes in username and password - if they are valid, it should return the int of the userid, otherwise 0).
I tested this method by calling it from a "Tester" class with a main method, and it returned the expected value. However, when calling this method from a jsp page, it gives get a ClassNotFound Exception for my SQL driver (com.sql.jdbc.Driver). (I know it's this method giving me the error, since I added a System.out.println to debug it)
Why do I only get this error when calling the method from my jsp page? How can I fix this?
The exact error I get in the console:
LogIn method error java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
The LogIn method that's giving me pain:
public static int logIn(String username, String password) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/my_database", "root",
"password12345");
Statement stmt = con.createStatement();
ResultSet users = stmt.executeQuery("SELECT * FROM users");
ArrayList<User> userList = new ArrayList<User>();
while (users.next()) {
userList.add(
new User(users.getInt("id"), users.getString("username"), users.getString("password"),
users.getString("full_name"),
users.getString("email"), users.getInt("admin") == 1));
}
for (int i = userList.size() - 1; i >= 0; i--) {
if (username.equals(userList.get(i).getUserName()) && userList.get(i).testPassword(password)) {
System.out.println(userList.get(i).getId());
return userList.get(i).getId();
}
}
return 0;
} catch (Exception e) {
System.out.println("LogIn method error " + e);
return 0;
}
}
The JSP page :
<%# page import="com.neilbanerjee.SupportMeLogic,java.sql.*" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%
int loggedInID = MyOtherClass.logIn(request.getParameter("username"), request.getParameter("password"));
com.neilbanerjee.User loggedIn;
if (loggedInID == 0) {
loggedIn = null; %>
<%--<jsp:forward page="index.jsp"></jsp:forward>--%>
<%
} else {
loggedIn = MyOtherClass.loggedInUser(loggedInID);
}
%>
<html>
<head>
<title>SupportMeDevices</title>
</head>
<body>
Welcome, <% out.print(loggedIn.getFullName());%>!
</body>
</html>
When your web app is deployed on server it uses jars of server's lib folder and jars of your WEB-INF/lib folder.
It is recomended that you put javax.servlet.jsp.jstl-1.2.4.jar and javax.servlet.jsp.jstl-api-1.2.1.jar inside WEB-INF/lib to be able to use jstl on jsp pages.
When you call it from main method, The JDBC Driver classes are there in the classpath and Java can run the application without an error.
But when you try to access these classes from JSP, The deployed war should contain the JDBC Driver classes inside it. For deployed war file to have all the necessary classes, You need to include all the libraries your app needs into 'WEB-INF/lib'. Try adding them and re-deploy the war file and see.

Is it possible to forward 2 requests from 2 different servlets to 1 jsp?

I was trying to do this in my servlet:
Date date = new Date();
request.setAttribute("status", status);
request.setAttribute("date", date);
if (status.equalsIgnoreCase("Incorrect password")|| status.equalsIgnoreCase("Username not found")) {
request.getRequestDispatcher("error.jsp").forward(request,response);
}
else {
request.getRequestDispatcher("success.jsp").forward(request,response);
}
and this inside my success.jsp:
<%
String stat = (String) request.getAttribute("status");
String timestamp = (String) request.getAttribute("date");
%>
<p>Welcome, <%= stat %>! </p>
<p>TimeStamp : <%= timestamp %> </p>
I got a 500 internal server error from the code above then I decided to use a separate servlet for my date object and forwarded the request to the same jsp but the I got a null value after this.
Why is it that my first implementation got a 500 internal server error and how come I got a null value on my second implementation? How can I solve this?

Servlet not Redirected to Page, Showing Non Styled Page

I have problem using servlet in jsp. Let say I want to get value from dropdown list and process it to servlet.
The method for process the code from the dropdown list is called ListDetailPesanan(Pesanan p);
I have successfully get the list from the function ListDetailPesanan which return Array List. Then the function is placed in my servlet called submitAppPesanan which executed from a form then redirected to page called apesanan.jsp
This is the servlet submitAppPesanan.java (I had place this servlet to web.xml)
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
/* GETTING VALUE FROM FORM. */
int kode = Integer.parseInt(request.getParameter("kode_pesanan_tmp"));
/* Initialize value to object */
Pesanan p = new Pesanan(kode);
/* execute the object to gain result set */
MasterPesanan mp = new MasterPesanan();
List<Pesanan> psn = mp.ListDetailPesanan(p);
java.lang.System.out.println("Pesanan " + psn);
/* sending result set to apesanan.jsp again */
if(psn != null){
request.setAttribute("listpesanan", psn);
request.getRequestDispatcher("system/apesanan.jsp").forward(request, response);
}
} catch(Exception e) {
java.lang.System.out.println("Exception on Submit App Pesanan " + e.getMessage() + "\n" + e.getCause());
} finally {
java.lang.System.out.println("Submit Kode Pesanan Successfully Executed");
}
}
but the servlet is not redirect again to apesanan.jsp, but the servlet stays in the page and showing non-styled page of apesanan.jsp.
What's wrong with this code? because i see the output result from my
Glassfish Server nothing error.
How properly consume the list from servlet to apesanan.jsp page?
thanks in advance.
UPDATE
Screenshot from my apesanan.jsp page then executed the servlet.
then the redirection then stacked here.
UPDATE
The result list is working properly and shown as i want, but still no clue what's going on.
The problem is your css are not loaded because i guess that you are using relative path like
<link rel="stylesheet" type="text/css" href="../css/theme.css"> in your jsp.
When you forward the request to a jsp page the page URL won't change because of this the relative path wont resolve to the css files.
Use <link rel="stylesheet" type="text/css" href="<%=request.getcontextpath()%>/css/theme.css"> or JSTL's c:url tag.
Please Check your path In RequestDispatcher.
try something Like ("/system/apesanan.jsp");

How to show value from database to jsp without refreshing the page using ajax

I am an Ajax fresher
Ajax
function ajaxFunction() {
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","Namelist",true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("txtname=" + txtname.value);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
jsp
<form name="fname" action="Namellist" method="post">
Select Category :
<select name="txtname" id="txtname">
<option value="Hindu">Hindu</option>
<option value="Muslim">Muslim</option>
<option value="Christian">Christian</option>
</select>
<input type="button" value="Show" id="sh" onclick="ajaxFunction();">
<div id="message">here i want to display name</div><div id="message1">here i want to display meaning</div>
</form>
servlet
String ct=null;
ct=request.getParameter("txtname");
Connection con=null;
ResultSet rs=null;
Statement st=null;
try{
con=Dbconnection.getConnection();
PreparedStatement ps=con.prepareStatement("select name meaning from (select * from namelist order by dbms_random.value)where rownum<=20 and category='+ct+'" );
rs=ps.executeQuery();
out.println("name" + rs);
**Here I have confusion,**
}
catch(Exception e)
{
System.out.println(e);
}
How can i diaplay servlet value to jsp.
Please help me? or please provide some good tutorial links.
You have to make below changes :-
In Servlet :-
Set the response content type as:- response.setContentType("text/xml"); in top section of the servlet. By setting this we can send the response in XML format and while retrieving it on JSP we will get it based on tag name of the XML.
Do whatever operation you want in servlet...
Save the value for ex-
String uname=";
uname="hello"; //some operation
//create one XML string
String sendThis="<?xml version='1.0'?>"
+"<Maintag>"
+"<Subtag>"
+"<unameVal>"+uname+"</unameVal>"
+"</Subtag>"
+"</Maintag>"
out.print(sendThis);
Now we'll go to JSP page where we've to display data.
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
if(xmlhttp) {
xmlhttp.open("GET","NameList",true); //NameList will be the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
getVal();
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
function getVal()
{
var xmlResp=xmlhttp.responseText;
try{
if(xmlResp.search("Maintag")>0 )
{
var x=xmlhttp.responseXML.documentElement.getElementsByTagName("Subtag");
var xx=x[0].getElementsByTagName("unameVal");
var recievedUname=xx[0].firstChild.nodeValue;
document.getElementById("message").innerText=recievedUname;//here
}
}catch(err2){
alert("Error in getting data"+err2);
}
}
And here you are done. :)
1.In servlet code
PrintWriter output = response.getWriter();
String result = "value";
writer.write(result);
writer.close()
2. Why you don't use jquery ?
You can replace your code on -
$.post('url', function(data) {
$('#message1').html(data);
});
query post example
Probably off the hook but might be useful, rather than putting up all the javascript for Ajax call use some javascript library preferably jQuery for making the Ajax call.
Any javascript library you use will help you make the code compact and concise and will also help you maintain cross browser compatibility.
If you planning to write all the XHTTP code yourself, you might end up spending a lot of time for fixing cross browser issues and your code will have a lots of hacks rather than the actual business logic.
Also, using library like jQuery will also achieve the same stuff with less number of lines of code.
Hope that helps.

Categories

Resources