I have one jsp where below ajax call is made to get some data from servlet which will return html table in response :
function searchStudent() {
var lname = document.getElementsByName("lname");
var fname = document.getElementsByName("fname");
var email = document.getElementsByName("email");
var submit = document.getElementById("search");
xmlhttp.onreadystatechange=useResponse;
xmlhttp.open("GET", "SearchUser?
submit="+submit+"&fname="+fname+"&lname="+lname+"&email"+email,
true);
xmlhttp.send(null);
}
function useResponse() {
alert(xmlhttp.status+" "+xmlhttp.readyState);
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
alert("hi"+xmlHttp.responseText);
document.getElementById("demo").innerHTML=xmlhttp.responseText;
alert("hi"+xmlHttp.responseText);
}
}
Function 'searchStudent()' is called on a button click.
Below is the servlet doGet() method :
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String fname="";
String lname="";
String email="";
String button="";
button = request.getParameter("submit");
db = new DbOperation();
HttpSession session = request.getSession();
session.removeAttribute("msg");
if(button!=null && button.equalsIgnoreCase("Search")){
fname=request.getParameter("fname")==null?"":request.getParameter("fname");
lname=request.getParameter("lname")==null?"":request.getParameter("lname");
email=request.getParameter("email")==null?"":request.getParameter("email");
Admin admin =(Admin) session.getAttribute("Admin");
int adminId=0;
if(admin!=null)
adminId=admin.getId();
ArrayList<Student> student = new ArrayList<Student>();
student= db.searchStudent(fname,lname,email,adminId);
PrintWriter pw = response.getWriter();
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-cache");
if(student!=null && student.size()>0){
session.setAttribute("student", student);
StringBuilder std= new StringBuilder();
std.append("<table border='1'><th>Id</th><th>First_name</th><th>Last_Name</th><th>Email</th><th>State</th><th>City</th>");
for(Student st :student ){
std.append("<tr><td>"+st.getId()+"</td><td>"+st.getFname()+"</td><td>"+st.getLname()+"</td><td>"+st.getEmail()+"</td><td>"+st.getState()+"</td><td>"+st.getCity()+"</td></tr>");
}
std.append("<table>");
//pw.write(std.toString());
pw.write(std.toString());
//pw.write("<h3>here</h3>");
}else{
pw.write("<h3>Student doesn't exists</h3>");
/*RequestDispatcher rd = request.getRequestDispatcher("AdminServlet?msg1=Student doesn't exists");
rd.forward(request, response);*/
}
}
}
The html returned by servlet is directly displayed in console and not coming to the jsp from where ajax call is made.
alert("hi"+xmlHttp.responseText); is also not getting populates
Related
i use Wicket.Ajax.ajax in pair with AbstractDefaultAjaxBehavior to sent some javascript calculated data to the java. But after event has fired from javascript and comes to Java, browser has been redirected to callback url.
...web/product/1?7&6-1.IBehaviorListener.0-idsPanelPlace%3Floggged_id=332797
logggedidAjax = new AbstractDefaultAjaxBehavior() {
#Override
protected void respond(AjaxRequestTarget target) {
StringValue loggged_vkid = getRequest().getQueryParameters().getParameterValue("loggged_id");
String loggedId = (loggged_id != null) ? loggged_id.toString() : "null";
logger.info("ajax has comming with logged ID " + loggedId);
}
#Override
public void renderHead(final Component component, IHeaderResponse response) {
super.renderHead(component, response);
String componentMarkupId = getMarkupId();
Map<String, Object> map = new HashMap<>();
map.put("callbackUrl", logggedidAjax.getCallbackUrl());
PackageTextTemplate ptt = new PackageTextTemplate(VKIDsPanel.class, "id_callback.js");
OnDomReadyHeaderItem onDomReadyHeaderItem = OnDomReadyHeaderItem.forScript(ptt.asString(map));
response.render(onDomReadyHeaderItem);
}
};
add(logggedidAjax);
As for js code -
var wcall = Wicket.Ajax.ajax({ u: '${callbackUrl}' + '?loggged_id='+ response.session.mid });
Why browser redirected to the url, since it is Ajax? How to prevent redirection?
I'm not sure what's going wrong in your code, but the following should be easier:
logggedidAjax = new AjaxEventBehavior("domready") {
#Override
protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
super.updateAjaxAttributes(attributes);
String loggedId = "return {'logged_id': response.session.mid}";
attributes.getDynamicExtraParameters().add(loggedId);
}
#Override
protected void onEvent(AjaxRequestTarget target) {
StringValue loggged_vkid = getRequest().getQueryParameters().getParameterValue("loggged_id");
String loggedId = (loggged_id != null) ? loggged_id.toString() : "null";
logger.info("ajax has comming with logged ID " + loggedId);
}
};
add(logggedidAjax);
I use spring mvc I want to uplaod image to jsp form so I add enctype="multipart/form-data" to the form tag but when i add this, modelAttribute values equals null in the controller
This is my form in jsp page:
<form:form action="saveContact" method="post" modelAttribute="Contacting" id="container" enctype="multipart/form-data">
This is the header of the function in controller:
#RequestMapping(value = "/saveContact", method = RequestMethod.POST)
public ModelAndView saveContact(#ModelAttribute ("Contacting") Contacting Contacting,ModelAndView modelndView,HttpServletRequest request ,HttpServletResponse response
) throws Exception {............}
#ModelAttribute ("Contacting") Contacting Contacting all values are null. and When I erease the enctype="multipart/form-data" from form tag its work well but I cant upload the image
this is the uplaud function:
public void uplaodImages(String url,HttpServletRequest request) {
// configures upload settings
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(THRESHOLD_SIZE);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setFileSizeMax(MAX_FILE_SIZE);
upload.setSizeMax(MAX_REQUEST_SIZE);
String uuidValue = "";
FileItem itemFile = null;
try {
// parses the request's content to extract file data
List formItems = upload.parseRequest(request);
Iterator iter = formItems.iterator();
// iterates over form's fields to get UUID Value
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
if (item.getFieldName().equalsIgnoreCase(UUID_STRING)) {
uuidValue = item.getString();
}
}
// processes only fields that are not form fields
if (!item.isFormField()) {
itemFile = item;
}
}
if (itemFile != null) {
// get item inputstream to upload file into s3 aws
BasicAWSCredentials awsCredentials = new BasicAWSCredentials(AMAZON_ACCESS_KEY, AMAZON_SECRET_KEY);
AmazonS3 s3client = new AmazonS3Client(awsCredentials);
try {
ObjectMetadata om = new ObjectMetadata();
om.setContentLength(itemFile.getSize());
om.setContentType("image/png");
String ext = FilenameUtils.getExtension(itemFile.getName());
String keyName = uuidValue + '.' + ext;
// s3client.putObject(new PutObjectRequest(S3_BUCKET_NAME,"99/after/img", itemFile,st om));
// s3client.setObjectAcl(S3_BUCKET_NAME, "99/after/img", CannedAccessControlList.PublicRead);
TransferManager tm = new TransferManager(new ProfileCredentialsProvider());
System.out.println("Hello");
// TransferManager processes all transfers asynchronously,
// so this call will return immediately.
Upload upload1 = tm.upload(
S3_BUCKET_NAME, url, itemFile.getInputStream(),om);
System.out.println("Hello2");
try {
// Or you can block and wait for the upload to finish
upload1.waitForCompletion();
System.out.println("Upload complete.");
} catch (AmazonClientException amazonClientException) {
System.out.println("Unable to upload file, upload was aborted.");
amazonClientException.printStackTrace();
}
} catch (AmazonServiceException ase) {
// LOGGER.error(uuidValue + ":error:" + ase.getMessage());
} catch (AmazonClientException ace) {
//LOGGER.error(uuidValue + ":error:" + ace.getMessage());
}
} else {
//LOGGER.error(uuidValue + ":error:" + "No Upload file");
System.out.println("No Upload file");
}
} catch (Exception ex) {
//LOGGER.error(uuidValue + ":" + ":error: " + ex.getMessage());
System.out.println(ex.getMessage());
}
//LOGGER.info(uuidValue + ":Upload done");
System.out.println("Upload done");
}
#RequestMapping(value = "/form.html", method = RequestMethod.POST)
public String handleFormUpload(#RequestParam("name") String name,
#RequestParam("file") MultipartFile file) throws Exception {
}
I am getting dynamic data for Company name select box. Based on those values I need to populate data for Business area select box. For that I am calling a servlet through AJAX.
In the servlet I am getting list of business areas based on company name, but I can't understand how I can pass this list to my JSP code.
I am getting dynamic data for select box like below:
Company Name:
<select id="company_id" onchange="getBusinessArea()">
<option selected="selected">--Select One--</option>
<% for (String txt : new ExtractDao().getCompanies()) {%>
<option><%=txt%></option>
<%}%>
</select>
By using the above company name i need to populate data for below select box:
Business Area :
<select>
<option><option>
</select>
I am calling my servlet using AJAX:
function getBusinessArea() {
var elem = document.getElementById("company_id");
var selectedNode = elem.options[elem.selectedIndex].value;
window.alert(selectedNode);
var xmlhttp;
var companyData = "${pageContext.request.contextPath}/ExtractController?companyName="
+ selectedNode;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
window.alert(companyData);
xmlhttp.open("GET", companyData, true);
xmlhttp.send();
if (http_request.readyState == 4) {
if (http_request.status == 200) {
alert(http_request.responseText);
} else {
alert('There was a problem with the request.');
}
}
}
My Servlet code:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ExtractService extService = null;
PrintWriter out = response.getWriter();
response.setContentType("text/html");
String companyName = request.getParameter("companyName");
extService = new ExtractService();
List<String> bList = extService.getBusinessAreas(companyName);
}
}
Can anyone help me show how I can populate data for business area select box?
I m trying to use http request webservice issue is that when we post wrong username and password the login service generate exception and it can't return any value in async calls.
A code snippet would help assist with the problem ...
However using a try catch should help you catch your exception and prevent application from crashing and handling the exceptions accordingly.
As seen in my sample code below I cater for the incorrect details entered / connectivity problems. I peform the http async request then parse the xml to my model handling the exceptions accordingly
var response = await WebRequestHelper.MakeAsyncRequest(url, content);
if (response.IsSuccessStatusCode == true)
{
Debug.WriteLine("Login Successfull" + "result.IsSuccessStatusCode" + response.IsSuccessStatusCode);
var result = response.Content.ReadAsStringAsync().Result;
result = result.Replace("<xml>", "<LoginResult>").Replace("</xml>", "</LoginResult>");
loginResult = XMLHelper.FromXml<LoginResult>(result);
if (loginResult != null)
{
login.Type = ResultType.OK;
login.Result = loginResult;
}
else
{
login.Type = ResultType.WrongDetails;
}
}
else
{
Debug.WriteLine("Login Failed" + "result.IsSuccessStatusCode" + response.IsSuccessStatusCode);
login.Type = ResultType.WrongDetails;
}
}
catch (Exception ex)
{
login.Type = ResultType.ConnectivityProblem;
}
Web Request
public static async Task<HttpResponseMessage> MakeAsyncRequest(string url, Dictionary<string, string> content)
{
var httpClient = new HttpClient();
httpClient.Timeout = new TimeSpan(0, 5, 0);
httpClient.BaseAddress = new Uri(url);
httpClient.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type: application/x-www-form-urlencoded", "application/json");
if (content == null)
{
content = new Dictionary<string, string>();
}
var encodedContent = new FormUrlEncodedContent(content);
var result = await httpClient.PostAsync(httpClient.BaseAddress, encodedContent);
return result;
I would recommend wrapping the response in a generic ServiceResponse where you can store the exceptions. await methods can be included in try/catch blocks so the standard process can be followed.
E.G.
public async Task<ServiceResponse<T>> PostAsync<T>(String address, object dto){
var content = Serializer.SerializeObject (dto);
var response = await client.PostAsync (
address,
new StringContent (content));
if (response.IsSuccessStatusCode) {
try {
var responseString = await response.Content.ReadAsStringAsync ();
return new ServiceResponse<T> (Serializer.DeserializeObject<T> (responseString),
response.StatusCode);
} catch (Exception ex) {
return new ServiceResponse<T> (response.StatusCode, ex);
}
} else {
return new ServiceResponse<T> (response.StatusCode);
}
}
With the ServiceResponse defined as :
public class ServiceResponse<T>
{
public HttpStatusCode StatusCode { get; set;}
public T Value { get; set;}
public String Content { get; set;}
public Exception Error {get;set;}
public ServiceResponse(T value, HttpStatusCode httpStatusCode){
this.Value = value;
this.StatusCode = httpStatusCode;
}
public ServiceResponse(HttpStatusCode httpStatusCode, Exception error = null){
this.StatusCode = httpStatusCode;
this.Error = error;
}
}
This will give you a clean way of managing all your HTTP responses and any errors that may occur.
Hello guys
I am sending my form values to controller and controller to rptdesign file my it is generating the report in temp folder with proper value but my requirement is that it should user to save or open dialog so that user can save the report or open
i think ajax request will not allow to download any file so if some one know to better solution plz reply
my controller is below
#RequestMapping("/leave/generateEmpLeaveReport.json")
public void generateEmployeeLeaveReport(HttpServletRequest request,
HttpServletResponse response) throws Exception {
String reportName = "D:/git-repositories/cougar_leave/src/java/com//report/myLeaveSummary.rptdesign";
File designTemplateFile = new File(reportName);
if (!designTemplateFile.exists()) {
throw new FileNotFoundException(reportName);
}
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("empId", NumberUtils.toInt(request.getParameter("id")));
parameters.put("reportTitle", "EMPLOYEE LEAVE");
parameters.put("fromDate", request.getParameter("fromDate"));
parameters.put("toDate", request.getParameter("toDate"));
parameters.put("leaveType",
NumberUtils.toInt(request.getParameter("leaveType")));
parameters.put("transactionType",
NumberUtils.toInt(request.getParameter("transactionType")));
reportManager.addSystemParams(parameters, null,
RequestUtils.getUser(request));
File file = null;
try {
ReportType reportType = ReportType.PDF;
OfflineReportContext reportContext = new OfflineReportContext(
reportName, reportType, parameters, null,
"EMPLOYEE LEAVE SUMMARY");
StringBuffer buffer = new StringBuffer();
file = offlineReportGenerator.generateReportFile(reportContext,
buffer);
ControllerUtils
.openFile(file.getParent(), response, file.getName());
} catch (Exception e) {
log.error(e, e);
} finally {
if (file != null && file.exists()) {
file.canExecute();
}
}
}
my ajax request is below
generateReport : function() {
if (this.form.valid()) {
fromDate = new Date($("input[name='fromDate']").val())
toDate = new Date($("input[name='toDate']").val())
if (fromDate > toDate) {
GtsJQuery
.showError("To date should be greater or equals than From date !")
} else {
var request = GtsJQuery.ajax3(GtsJQuery.getContextPath()
+ '/leave/generateEmpLeaveReport.json', {
data : {
id : $("input[name='employeeId']").val(),
fromDate : $("input[name='fromDate']")
.val(),
toDate : $("input[name='toDate']").val(),
leaveType : $("select[name='leaveType']")
.val(),
transactionType : $("select[name='transactionType']")
.val(),
orderBy : $("select[name='orderBy']").val()
}
});
request.success(this.callback("onSubscribeSuccess"))
}
}
},
The controller response should be the temp file itself, just adjust the content-type.