Server client communication using Javaservlets and JSP - ajax

I am trying to understand the aspects to build dynamic web application by referring many resources. I am facing issue while I am trying to communicate and pass the parameter from AJAX to java servlets and to JSP.
Please find the code below:
**HTML Code**:
<button onclick="viewcart()">ViewMyCart</button>
<script>
function viewcart(){
$.ajax({
type:"POST",
url:'./ShowCart',
});
}
</script>
**Servlet (ShowCart):**
try {
System.out.println("In ShowCart code");
LoginDB log=new LoginDB();
Connection con=log.connect();
String SQL="select * from bookname";
PreparedStatement prep=con.prepareStatement(SQL);
ResultSet rs=prep.executeQuery(SQL);
ArrayList<String> bookname=new ArrayList<String>();
while(rs.next()) {
bookname.add(rs.getString("name"));
}
System.out.println("bookname is"+bookname);
request.setAttribute("MyBookNames", bookname);
request.getRequestDispatcher("Display.jsp").forward(request, response);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
**Display.JSP:**
<h1> Your cart </h1>
<%
ArrayList<String> booknames_list= (ArrayList)request.getAttribute("MyBookNames");
System.out.println("In JSP class Display");
System.out.println(booknames_list);
%>
</body>
</html>
Values are actually in booknames_list . But I wanted to display the values in a separate page. Can you all please guide me in achieving the same?
Thank you

Related

Spring Controller does nothing

Greeting my dear fellows
I would appreciate some help since I've been 2 days googling to find out why my code is not working. My webapp is Spring running in a Weblogic Server under Eclipse. Btw, apologies for my spelling (I am not native English speaker)
Straight from my webapp, the following controller works flawless
#RequestMapping(value = "/sendFile")
public ModelAndView vistaEnvioFicheros() throws myCustomException {
ModelAndView model = null;
try {
getLog().debug("Setting model for sending a file");
model = new ModelAndView("/content/sendFileWeb");
} catch (Exception ex) {
getLog().error("Shxx happens: ", ex);
throw new myCustomException(ex.getMessage(), ex);
}
return model;
}
This controller loads a jsp file with a file browser button and a file upload button which works great too.
So when I click on the upload button the following controller triggers:
#RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public Object subirFichero(#RequestParam(value = "file") MultipartFile file) throws myCustomException {
ModelAndView model = null;
if (file.isEmpty()){
try {
getLog().debug("File is empty");
model = new ModelAndView("/content/errorWeb");
} catch (Exception ex) {
getLog().error("Shxx happens again ", ex);
throw new myCustomException(ex.getMessage(), ex);
}
return model;
}
...
}
Problem is: when I upload empty file, errorWeb jsp file should be shown in my web browser, however nothing happens. If I debbug the controlles I can see the code runs propperly until return model sentence nonetheless errorWeb jsp file is not loaded
Could anyone give me a hint about why first controller loads it jsp view but second controller doesn't. Also I don't get a single error message in any console or whatever
Thank you very much
Ok, I got it solved! This was just a newbie thing (I am a newbie web developper).
The problem was in the client side, where my webapp was sending the request thay triggers the second controller, not by an standard href o after a submit (or whatever), but by a custom javascript function.
This custom javascript function firstly validates the file and then uploads it to the server. After that client side code stops listening the response from the server. That's why the new ModelAndView is ignored.
Thank you for your time to all of you who read the post

calling a spring controller from xhrPost doesnot redirect

I am calling a spring controller method from dojo xhrPost and I need to redirect to a new html from the controller method. But controller returns back to the dojo in javascript instead of moving to a new page.
my javascript:
var xhrArgs={
url:"/tradeIn/submitTradeIn",
postData:dojo.toJson(tradeInDetails),
handleAs:"text",
headers:{"Content-Type":"application/json"}
/*load:function(data){
console.log(data);
label=data;
if(data =="fail"){
location.reload(true);
window.location="/Fail";
}
else{
window.location="/success";
}
}*/
}
var deferred=dojo.xhrPost(xhrArgs);
my spring controller:
#RequestMapping(value="/tradeIn/submitTradeIn", method = {RequestMethod.POST})
public String submitTradeIn(#RequestBody TradeInDetails tradeDetails) throws UnsupportedEncodingException{
List<byte[]> labelList=new ArrayList<byte[]>();
ShippingInfo shippingInfo=new ShippingInfo();
shippingInfo.setAddress1(tradeDetails.getCustomerDetails().get(0).getAddress1());
shippingInfo.setAddress2(tradeDetails.getCustomerDetails().get(0).getAddress1());
shippingInfo.setCity(tradeDetails.getCustomerDetails().get(0).getCity());
shippingInfo.setCompany(tradeDetails.getCustomerDetails().get(0).getCompany());
shippingInfo.setDayPhone(tradeDetails.getCustomerDetails().get(0).getDayPhone());
shippingInfo.setEmail(tradeDetails.getCustomerDetails().get(0).getEmail());
shippingInfo.setEvePhone(tradeDetails.getCustomerDetails().get(0).getEvePhone());
shippingInfo.setFirstName(tradeDetails.getCustomerDetails().get(0).getFirstName());
shippingInfo.setLastName(tradeDetails.getCustomerDetails().get(0).getLastName());
shippingInfo.setState(tradeDetails.getCustomerDetails().get(0).getState());
shippingInfo.setZip(tradeDetails.getCustomerDetails().get(0).getZip());
shippingInfo.setCountry(tradeDetails.getCustomerDetails().get(0).getCountry());
List<ReturnRequestLabel> label;
List<TradeInClubs> tradeInList1= new ArrayList<TradeInClubs>();
for(ClubDetails cl: tradeDetails.getClubDetails()){
TradeInClubs tradeInclubs1=new TradeInClubs();
tradeInclubs1.setClubMaterial(cl.getShaftType());
tradeInclubs1.setClubType(cl.getClubType());
tradeInclubs1.setManufacturer(cl.getClubManufacturer());
tradeInclubs1.setModel(cl.getClubModel());
tradeInclubs1.setTradeInValue(cl.getTradeInPrice());
tradeInList1.add(tradeInclubs1);
}
try{
ReturnFedexLabel returnFedexLabel = new ReturnFedexLabel();
label=returnFedexLabel.fetchFedexLabel(tradeInList1, shippingInfo);
byte[] labelImageData;
String fedexLabelNumber=null;
for(ReturnRequestLabel rl: label){
labelImageData=rl.fedexReturnLabel.imageData;
labelList.add(labelImageData);
fedexLabelNumber=rl.trackingNumber;
}
File f=new File("label.jpg");
BufferedImage img=ImageIO.read(new ByteArrayInputStream(labelList.get(0)));
ImageIO.write(img,"JPEG",f);
int id=tradeInDao.insertQuery(shippingInfo,tradeInList1,fedexLabelNumber);
byte[] pdfData=fedexLabelToPdf.printFedexLabel(labelList);
emailTradeIn.emailTradeInDetails(pdfData,tradeDetails.getCustomerDetails().get(0).getEmail(),tradeInList1,id);
System.out.println("here");
} catch (Exception e){
logger.error(e.getMessage());
return "fail";
}
return "success";//Base64.encodeBase64String(labelList.get(0));
}
it is not moving to success page. it just stays in the current page
Check and see what deferred is, it is probably "success".
From http://dojotoolkit.org/reference-guide/1.7/quickstart/ajax.html:
dojo.xhrPost xhrPost will create an Ajax request using the HTTP POST
method and is usually used to submit data to a service. It returns
data to a callback. The callback is defined as a member of the object
used to create the request (the property-bag), or by using the
dojo.Deferred.then() method.
For complete details and examples, see the dojo.xhrPost documentation.
if you need to change the page from the controller it shouldn't be an ajax request. If you can change it from the client side then you can continue with the ajax request and respond accordingly.

Web api not bringing back data

I am currently using python requests to consume a web api written in c# within my MVC application. This is the error I get
<body>
<div id="header"><h1>Server Error</h1></div>
<div id="content">
<div class="content-container"><fieldset>
<h2>405 - HTTP verb used to access this page is not allowed.</h2>
<h3>The page you are looking for cannot be displayed because an invalid method (HTTP verb) was used to attempt access.</h3>
</fieldset></div>
</div>
</body>
and here is the python code I am using
constURLString = "http://10.1.30.15/test/api/DevicesAPI"
send = requests.put(constURLString + "/" + str(deviceID), data = urlParam)
urlParam is the model I am passing back to the webapi in order to edit that specific entry. I tried typing the actual url into my browser trying to get that single entry by typing http://10.1.30.15/test/api/DevicesAPI/16 and got
<Error><Message>An error has occurred.</Message></Error>
Which isn't very helpful. This seems to work perfectly when I am running it locally but doesn't seem to like it when I publish it to the server. My put method within my web api goes as is:
// PUT: api/DevicesAPI/5
[ResponseType(typeof(void))]
public IHttpActionResult PutDevices(long id, Devices devices)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != devices.deviceID)
{
return BadRequest();
}
db.Entry(devices).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!DevicesExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}

open pdf in new window using spring controlle and ajax

I want to show the pdf file in new window.
Here is my code.
<c:if test="${noOfOwners>0 && empty isOwner && licenseBean.businessBean.ownershipType==1}">
<c:url value="/auth/newlicense/ownercertification?retailerId=${licenseBean.outletID}" var="ownerCertificationUrl"/>
<p class="label4">Owner Eligibility Certification</p>
<p>For your license application to be approved, you must provide the lottery with a signed Owner Eligibility Certification form. Each owner/officer included on the license application must sign the form, accepting the license eligibility standards, terms and conditions. Instructions on returning the form to the Texas Lottery via mail, fax and email are included on the form. To open a PDF version of the Owner Eligibility form, click on this link /link to form/. A PDF version of the form has also been sent to the email address you provided</p>
</c:if>
<script>
$(document).ready(function() {
$("#ownereligibilityForm").click(function(){
var retailerid = <c:out value='${licenseBean.outletID}'/>;
$.ajax({
url : "ownercertification",
type : "GET",
data : {
"retailerId" : retailerid
},success : function(link){
window.open(link,"_blank");
return false;
},error: function(){
}
});
});
});
</script>
my server side code
#RequestMapping(value = "/ownercertification", method = RequestMethod.GET)
public #ResponseBody String openOwnerEligibilityCertificationForm(HttpServletRequest request,HttpServletResponse response){
File file = new File("/var/lsp/licensing/21/output/"+request.getParameter("retailerId")+"/ownerEligibilityCertificationForm_"+request.getParameter("retailerId")+".pdf");
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename="+file);
OutputStream out = null;
try{
byte[] b = new byte[(int)file.length()];
out = response.getOutputStream();
out.write(b);
out.flush();
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return out.toString();
}
But it is not opening the pdf file. I am getting the below error
HTTP Status 404 - /lsp/auth/newlicense/org.springframework.security.web.context.SaveContextOnUpdateOrErrorResponseWrapper$SaveContextServletOutputStream[delegate=org.apache.catalina.connector.CoyoteOutputStream#266f266f]
Could anyone help me?

Making Ajax request in portlets for liferay 6

I want to make an ajax call inside my jsp file which calls processAction method of a portlet, based on the success message from processAction method i need to make another call to serveResource method of portlet,please provide some examples..
In portlets, processAction() methods are automatically followed by render method and hence ajax response will get embedded with HTML fragment generated by render method. So writing ajax in portlets is a bit tricky.
Have a look at this blog of mine.
http://ajax-and-portlets.blogspot.com/2011/09/ajax-best-practice-in-portlets.html
It gives an insight view of what's the best practice to implement ajax in portlets (for both JSR-168 and JSR-286 portlets).
In case you want sample portlets, you can contact me through the contact details from the blog. I'll be happy to help you.
Thanks
Jignesh
This question worked for me.
Basically, the Controller
#Controller
#RequestMapping("VIEW") // VIEW mapping (as opposed to EDIT)
public class MyPortlet {
#RenderMapping
public String handleRenderRequest(RenderRequest request, RenderResponse response) {
return "defaultRender";
}
#ResourceMapping("myURL")
public void handleMyResource(ResourceRequest request, ResourceResponse response) {
OutputStream outStream;
try {
outStream = response.getPortletOutputStream();
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(outStream, "Hello world!");
} catch (IOException ex) {
// TODO : Do something with errors.
}
}
}
And the JSP:
<portlet:resourceURL id="myURL" var="myURL"/>
<script type="text/javascript">
var urlink = "<%= myURL %>";
$.ajax({
url: urlink,
cache: false,
type: "POST",
success: function(jsondata) {
console.log(jsondata);
}
});
</script>
based on the success message from processAction method
That's not the right way to do it.
On calling portlet action URL in response you get usual render response, so you'll get page with all the portlets.
Instead you should use Portlet 2.0 resource serving feature, and return your response as a resource.
You can check out my portlet which has examples for both serveResource and processAction methods calling.
Ajax Jquery Portlet

Resources