I'm quite new to JSP/Liferay portlet development and I'm trying to add a progress bar using jQuery, I found this question but wasn't very specific to how it will be done using AJAX.
I was wondering if anyone can point me in the right direction to help me get started.
thanks.
EDIT:
I used JSON simple, and manage to make some changes but I am getting a bad request(error code 400 when using fire bug) and a 404 not found on my JS
below is my code:
public void processAction(
ActionRequest actionRequest, ActionResponse actionResponse)
throws IOException, PortletException {
//some code here
this.generateJSON(actionRequest, actionResponse);//manual call the method?
public void generateJSON(ActionRequest actionRequest, ActionResponse actionResponse)
throws IOException, PortletException {
try{
//just want to see a progress bar so do static for now...
JSONObject obj=new JSONObject();
obj.put("percent",new Integer(30));
StringWriter out = new StringWriter();
obj.writeJSONString(out);
String jsonText = out.toString();
}catch(Exception ex){
System.out.print(ex);
}
}
}//end of class
JS here
function checkStatus(){
$.ajax({
type: 'POST',
//url: '<%=request.getContextPath()%>/checkStatusServlet',
url: '<%=request.getContextPath()%>/generateJSON',
dataType: 'json',
success: function( data )
{
alert(data.statusPercent);
var statusPercent = data.percent;
//Update your jQuery progress bar
$( "#progressbar" ).progressbar({value: statusPercent});
}
});
//below works and alert is being called...
/*for (i=0;i<=5;i++)
{
$( "#progressbar" ).progressbar({value: i+10});
}
alert('got here');
*/
}
HTML/JSP
<%# page import="javax.portlet.PortletPreferences" %>
<portlet:defineObjects/>
<portlet:renderURL var="resourceUrl"></portlet:renderURL>
<!-- Javascript files -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/main.js"></script>
<!-- end of Java script files -->
<script type="text/javascript">
setTimeout('checkStatus()',1000);
</script>
<div id="progressbar"></div>
You can't generate JSON in processAction. This method is meant to change the portlet state, but not generate output. The portal-way to accomplish what you need it to use the serveResource method/lifecycle-phase: you get the URL for this from the portal ( < portlet:resourceURL / >). Specifically you shouldn't create them yourself.
An alternative (but not the portal way) is to use a servlet - but in this you don't have the portlet state that you might need.
And you might want to use < portlet:namespace / > to disambiguate your global names - or use proper namespacing - because you can never say how many times your portlet will be placed on a page.
(added spaces to jsp-tags so that they don't get eaten by markup)
Short: Read about resource-serving for portlets, this will most likely solve your underlying problem: With the code you give above you won't be able to access your JSON at all - no matter what you do on the JS side.
The answer really depends on your specific needs. Are you trying to display how much time is actually left for some task, or how much time till a page loads or what?
You could poll from the client and update the progress bar in the browser depending on how much is left to process. A simple jQuery ajax example:
function checkStatus
{
$.ajax({
type: 'POST',
url: '<%=request.getContextPath()%>/checkStatusServlet',
dataType: 'json',
success: function( data )
{
var statusPercent = data.statusPercent;
//Update your jQuery progress bar
$( "#progressbar" ).progressbar({value: statusPercent });
}
});
}
Then you can simply poll this function till its done
setTimeout('checkStatus()' 1000);
Of course you will also need to construct a servlet or struts action or portlet to handle the processing on the server, and return the appropriate status for the task.
EDIT:
Use the JSON library
From your servlet or action. (code below is from struts2 action)
public String checkStatus()
{
try
{
Integer percentDone = 50; //Calculate how much time is left
JSONObject statusResult = new JSONObject();
statusResult.put("statusPercent", percentDone);
//Obtain HttpServletResponse..
//implementation depends on your framework.
//PortletResponse should work too.
PrintWriter out = this.response.getWriter();
out.write( statusResult.toString(4) );
out.flush();
out.close();
}
catch (IOException e) {}
catch (JSONException e) {}
return null;
}
Related
i'm working on create a java web app using servlet in controller side and the angular in front-end.. this app uses javamail api to get emails from an email account (like gmail) then return them as a json format .. i did all of that .. i can bring the emails messages and i return them in json format using servlet but my problem here is that i can't display them using angular.. i tried to test my code with this website "http://jsonplaceholder.typicode.com/users" to test my angular with json and it bring all data but when i modify it and try it with my app it doesn't bring any thing..
here is an example of json data from my app..
and that's the servlet code who print this data:
// TODO Auto-generated method stub
doGet(request, response);
EmailAccount emailaccount= new EmailAccount("myemail#gmail.com","HardPas$$word!#");
EmailServices read = new EmailServices();
ArrayList<Email> emails = new ArrayList<Email>();
emails = read.readEmail(emailaccount);
String json = new Gson().toJson(emails.get(2));
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
and this this the codes in angular to get the json data and display it:
html
<form action="http://127.0.0.1:8080/oneBox/ReadEmail" method="POST" (submit)="onSubmit()">
<input type="submit" value="submit">
</form>
<ul >
<li>
{{users.id}}
</li>
<li>
{{users.title}} ---- {{users.from}}
</li>
<li>
{{users.to}}
</li>
</ul>
component:
import { Component, OnInit } from '#angular/core';
import { MyServiceService } from '../../services/my-service.service';
import {EmailModel} from '../../models/user.model'
#Component({
selector: 'app-my-compo',
templateUrl: './my-compo.component.html',
styleUrls: ['./my-compo.component.css']
})
export class MyCompoComponent implements OnInit {
users:EmailModel;
constructor(public service:MyServiceService) {
}
onSubmit(){
this.service.getUsers().subscribe(
users => {this.users=users;});
}
ngOnInit(): void {
}
}
and my service code:
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import {map, catchError} from "rxjs/operators";
import { Observable, throwError } from 'rxjs';
#Injectable({
providedIn: 'root'
})
export class MyServiceService {
url="http://127.0.0.1:8080/oneBox/ReadEmail";
getUsers():Observable<any>{
return this.http.get(this.url)
.pipe(map(res => res.json()));
}
constructor(public http: Http) { }
}
so my question here is how can i bring these json data from my local server and print it using angular ?
Your backend seems to be working fine, as you get a proper JSON response from the Java side of things.
Try the following in your service class:
getUsers(): Observable<any>{
return this.http.get<any>(this.url);
}
Add the error callback inside your component controller and log the result of both fields, provide us with the result afterwards in the comments:
onSubmit(){
this.service.getUsers().subscribe(
users => {
console.log(users);
this.users=users;
},
error => {
console.log(error);
});
}
Further more, I think that there is a misconception between POST and GET requests, as I saw this in your form. Remove the method and action attribute in your form, since in Angular this will have no effects. You submit your forms with the (submit) event, so that is enough.
Last but not least, have you considered CORS policy in your backend? This is an issue with frontend/backend separation, since the backend will only allow request coming from the same IP and Port, thus not your Angular frontend. Probably this could help you: https://howtodoinjava.com/servlets/java-cors-filter-example/
I'm making a post method using $.ajax which is this
$(function(){
$("#postMembers").click(function(){
let member ={
firstName: "khookina",
lastName : "khooak",
age:1,
sex:"female",
duty:"undefined",
dailyJeton:2
}
$.ajax({
type: "post",
url: "http://localhost:8080/RCP2/members",
data: member,
dataType: "application/json",
success: function (response) {
alert("success");
},
error: function(error){
alert("error");
}
});
});
and my rest controller is this
#PostMapping(consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE}, produces = {MediaType.APPLICATION_JSON_UTF8_VALUE})
public String createMembers(Member member) {
if (member.hasError()) {
throw new CreatePersonException("All the fields must be filled properly in order to create a new member.");
}
if (personDao.createMember(member)) {
return "Member: " + member.getFirstName() + " " + member.getLastName() + " successfully created.";
}
return "couldn't create member, please try again later.";
}
I have a create member button in the webpage that executes this ajax post method, when I press it, everything works fine, the member information gets sent to the rest controller, It gets created (100% working) and returns {"readyState":4 status":200, "statusText":"parsererror"} and error: function(error) of ajax post method gets called
What's the problem?
it's the first day I'm working with ajax and javascript, I don't really understand what's happening.
Thanks in advance
P.S I've tried changing data-type text json, json and some others that been suggested in similar questions, but they didn't work for me, so i decided to make a question myself.
Try changing
data: JSON.stringify(member) and you will have your response in your success in the result/
Remove data type from ajax request and it works.
Remove this.
dataType: "application/json"
For details refer this
I want to extend an existing application with a drag and drop file upload feature. The application is built upon Jetty + Wicket. DropzoneJS seems a good way to go. Dropzone provides all front-end work, I just have to wire it up to the back-end.
More easily said than done, as it turns out. First, I created a test application with the Wicket quickstart. I added dropzone to the HomePage:
<!DOCTYPE html>
<html>
<head>
<script src="https://rawgit.com/enyo/dropzone/master/dist/dropzone.js"></script>
<link rel="stylesheet" href="https://rawgit.com/enyo/dropzone/master/dist/dropzone.css">
</head>
<body>
<form action="/upload" class="dropzone"></form>
</body>
</html>
Dropzone is simply included from its repository. On the server, I mounted a resource reference at /upload:
public class FileUploadResourceReference extends ResourceReference
{
public FileUploadResourceReference(String name)
{
super(FileUploadResourceReference.class, name);
}
#Override
public IResource getResource()
{
return new FileUploadResource();
}
}
FileUploadResource will handle processing of uploaded files:
public class FileUploadResource extends AbstractResource
{
#Override
protected ResourceResponse newResourceResponse(Attributes attributes)
{
ServletWebRequest request = (ServletWebRequest) attributes.getRequest();
try
{
MultipartServletWebRequest multipartRequest = request
.newMultipartWebRequest(Bytes.megabytes(100), "ignored");
Map<String, List<FileItem>> files = multipartRequest.getFiles();
List<FileItem> fileItems = files.get("file");
for (FileItem fileItem : fileItems)
{
saveFile(fileItem);
}
}
catch (FileUploadException e)
{
e.printStackTrace();
}
return null;
}
private void saveFile(FileItem fileItem)
{
// not implemented
}
}
Now here's the problem, when uploading files, Dropzone sends a POST-request to my http://localhost:8080/upload. The request is recognized as a multipart request, but the file parameter is absent. A null pointer exception is thrown entering the for-loop:
java.lang.NullPointerException
at com.test.FileUploadResource.newResourceResponse(FileUploadResource.java:31) ~[classes/:?]
at org.apache.wicket.request.resource.AbstractResource.respond(AbstractResource.java:629) ~[wicket-core-7.4.0.jar:7.4.0]
at org.apache.wicket.request.handler.resource.ResourceRequestHandler.respond(ResourceRequestHandler.java:105) ~[wicket-core-7.4.0.jar:7.4.0]
at org.apache.wicket.request.handler.resource.ResourceReferenceRequestHandler.respond(ResourceReferenceRequestHandler.java:108) ~[wicket-core-7.4.0.jar:7.4.0]
I can't figure out what's going on here. According to the Dropzone website, the form declaration should be fine. A bug in Dropzone perhaps? Seems unlikely. Some Jetty configuration parameter that is denying multipart form requests? Seems highly unlikely, at least I've never heard of it.
You can find full source code of my test app on GitHub.
You miss one method call - multipartRequest.parseFileNames().
You need to do it before #getFiles().
See http://wicketinaction.com/2012/11/uploading-files-to-wicket-iresource/
I have the above js and JSP code, I want to invoke procedureCall() while clicking on ok button on confirm window poopup (inside "if" statement). Is it possible and if yes, how it can be done?
<script type="text/javascript">
function confirmDelete() {
var answer = confirm("Are you sure you want to delete");
if (answer == true) {
return true;
} else {
return false;
}
}
</script>
JSP piece:
<%! public void procedureCall(int cId) {
String procedureCall = "{call NEW_PORTING_PRC.delete_album_metadata(cId)}";
try (CallableStatement cal = conn.prepareCall(procedureCall);) {
} catch (Exception e) {
e.printStackTrace();
}
%>
javascript runs in your browser, your java code is deployed in your container(Tomcat).
So only way to invoke this is via a Web call. Your javascript should invoke an ajax call to one servlet(configured in web.xml) and this servlet should invoke your java method.
like from JS you write as
$.get('URLofServlet');
OR
what you can try is submit the JSp with some parameters and reloading the JSP..
if (answer == true)
{
document.getElementById("param1").value='paramvalue';
document.getElementById("myForm").action='yourJspPath.jsp';
document.getElementById("myForm").submit();
}
Also I assume id and name will both be 'param1' for simplicity..
and in scriptlet you can do like
<%
if(request.getParamter("param1")=='paramvalue'){procedureCall();}
%>
Just to add I will recommend to remove scriplets and use ajax as in first approach.
Use form submission or ajax request or framework action to go back end and process the things needed for you.In your approach its not possible I think.
And please dont use scriplets in jsp,its not a good practice.
I am creating a jsp application in Netbeans Ide. I am having problems in calling a java class method in ajax.Is it possible to do so
My java class is something like this:
public class Hello
{
public String execute(String s)
{
return "success";
}
}
I am not able to figure out how to call the execute method using ajax :
My current ajax code is:
var val="test string";
$.ajax({
type: "GET",
url: "http://localhost:8084/Shade/src/java/mail/Main.execute",
data: val,
async: true,
cache: false,
success: function (msg) {
alert("hi");
$(".col-1").html(msg);
});
Thanx in advance :)
AJAX is an acronym for Asynchronous JavaScript And XML. It provides an ability to communicate with the server asynchronously.
To explain that in simple terms, you can send a request to server and continue user interaction with the user. You need not wait for response from the server. Once the response arrives, a designated area in UI will update itself and reflect the response information. Whole page need not be reloaded.
So, you can not access Java Class directly as url to make your Ajax request. It should any mapped url like JSP, Servlets, PHP etc.
Create a JSP (e.g. hello.jsp)
<%
String strResponse;
mail.Main objMain = new mail.Main();
strResponse = objMain.execute();
%>
<%=strResponse %>
In Ajax request
url: "hello.jsp",
EDIT: Added Example:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
function getData() {
var dataToBeSent = {
uName : $("#userName").val() , //
passwd: $("#password").val()
}; // you can change parameter name
$.ajax({
url : 'getDataServlet', // Your Servlet mapping or JSP(not suggested)
data :dataToBeSent,
type : 'POST',
dataType : 'html', // Returns HTML as plain text; included script tags are evaluated when inserted in the DOM.
success : function(response) {
$('#outputDiv').html(response); // create an empty div in your page with some id
},
error : function(request, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
});
In Servlet/JSP access your parameters request.getParameter("uName");
You cannot call the method directly. You should map an URL to the method you want to call.
This can be done in a servlet. If you're already serving pages through your Java code, you just add a new method to serve a page with the content you want.