I have an web application with an Ajax request to a Servlet. When an user clicks a button it sends an ajax request to the servlet which will have to add a list of records to the DB.
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String username = session.getAttribute("username").toString();
response.setContentType("text/html");
response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma","no-cache");
String parameter = request.getParameter("items");
out = response.getWriter();
out.println(testVariable);
try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
}catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
insertRecords(parameter, username);
}
private void insertRecords(String records, String user){
ArrayList<String> items = new ArrayList<>(); //This is the list of records i want to add into DB
if(records.contains("-")){
String[] split = records.split("-");
for(String item : split){
items.add(item);
}
}
else{
items.add(records);
}
try {
out.println("LIST: " + items); //This is just for test
PreparedStatement stmt = conn.prepareStatement("INSERT INTO records(productName, productCategory, user) VALUES (?, ?, ?)");
for(String record : items) {
String parent = getParentForSubproduct(record);// This method does two selects into DB without closing the connection afterwards.
stmt.setString(1, record);
if(parent.equals(""))
stmt.setString(2, record);
else
stmt.setString(2, parent);
stmt.setString(3, user);
out.println("RECORD: " + record);//This is just for test
testVariable++;
stmt.executeUpdate();
}
if(stmt != null)
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace(out);
}
out.println("TIMES EXECUTED LOOP: " + testVariable);
}
The problem is that after doing more than one insert (after calling "insertRecords" more than one time) it inserts ALL of the already inserted values + the new one . Every time. I have no idea how to resolve this. I wasted one day on this.
//EDIT: I just tested out and the loop is execute more times. After the first button(first servlet call) the output would be ""TIMES EXECUTED LOOP: 1". After the second one, the output would be: "TIMES EXECUTED LOOP: 3".
As #JacekCz mentions HTTP GET has some problems.
Here I guess that on the page something like the following (not the following) is used
<a href="#" onclick="...">
This could do a page reload twice (the href and in javascript). Other variants are possible. Also an HTML element could do a GET of almost the same URL and effect the same servlet.
With Ajax something similar could happen. The usage of a dash-separated list points to JavaScript. A bit of logging will find the cause - I hope.
Thanks to #JoopEggen tips i managed to solve the problem. There was a coding error with my Ajax. Here is the code i used:
The action on the button was to call a method where it had the ajax code for the servlet too inside:
$(function(){
var list = translateArrayToString(array);
$('#finish').on('click', function (event) {
alert("test");
$.ajax({
url : 'myServlet',
async: false,
data : {
items : list
},
success : function(responseText) {
$('#ajaxGetUserServletResponse').text(responseText);
}
});
});
});
So as you can see it had another on click event so that is why it was called more than one time. Here is the working Ajax code:
$(function(){
var list = translateArrayToString(array);
alert("test");
$.ajax({
url : 'MyServlet',
async: false,
data : {
items : list
},
success : function(responseText) {
$('#ajaxGetUserServletResponse').text(responseText);
}
});
});
Related
This question already has answers here:
Passing parameter without use of HTML forms in JSP
(3 answers)
Closed 3 years ago.
I have been trying to pass the data from a JSP page to a Java Servlet without using form. The JSP form returns to itself (action="") and I validate the form element. Then I want to pass the inputs of the user to Java Servlet. Couldn't find a good solution. Is there any easy way?
I understand what you are looking for, if you want to pass parameters to Servlet without using form you can simple try this, but you need to add your parameters on the link
this is an example.
<a href="ServletName?theNameOfParameterToSend=TheValueOfTheParameter&anotherNameOfParameterToSend=TheAotherValueOfTheParameter>
this is real example
<a href="MyApp?currancy=usd&country=usa>Send</a>
By using this way you can't send data by String query in post, it will be always visible in the link.
Wish I was helpful.
Maybe you can try Ajax.
I use Ajax Asynchronous Verify that the account exists.
If the account does not exist, you will be prompted below.
It can pass data without refreshing the page.
Here is my related code.
public User getUserByName(String name) {
User user = null;
try {
conn = DBUtils.getConnection();
String sql = "select id,name,pwd from user_info where `name`=?";
statement = conn.prepareStatement(sql);
statement.setString(1, name);
resultSet = statement.executeQuery();
while (resultSet.next()) {
user = new User();
user.setName(resultSet.getString("name"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
DBUtils.close(conn, statement, resultSet);
}
return user;
}
public class CheckNameServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String name = req.getParameter("name");
UserDao userDao = new UserDaoImpl();
User user = userDao.getUserByName(name);
PrintWriter pw = resp.getWriter();
if (user == null) {
pw.print(1);
} else {
pw.print(0);
}
}
}
<script type="text/javascript">
function checkName() {
var name = $("#name").val();
$.ajax({
type: "post",
url: "check",
data: {"name": name},
success: function (data) {
if (data == "0") {
$("#msg").html("");
} else {
$("#msg").html("The account does not exist, please re-enter!")
}
}
});
}
</script>
then put msg in your HTML.
Hope it can help you.
This question already has answers here:
How should I use servlets and Ajax?
(7 answers)
Closed 5 years ago.
I am totally confused about this strange bug that I am facing in my code. So, I am trying to send data from my jQuery script to a servlet with AJAX. Now, here is the strange part that I have noticed, when I set the contentType to application/json, I notice that all the values in server side are null but the moment I remove it, I get the right data in my servlet. Now, I would like to know why am I facing such a bug?
Here is my jsp -
<script type="text/javascript">
$(document).on("click", "#check", function() { // When HTML DOM "click" event is invoked on element with ID "somebutton", execute the following function...
event.preventDefault();
var apiname=$("#apiname").val();
var apiendpoint=$("#apiendpoint").val();
var apiversion=$("#apiversion").val();
var source=$("#source").val();
$.ajax({
type: "POST",
url: "HomeServlet",
contentType: "application/json",
dataType:'json',
data:{"apiname":apiname,"apiendpoint":apiendpoint,"apiversion":apiversion,"source":source},
success: function(status){
console.log("Entered",status);
},
error:function(error){
console.log("error",error);
},
});
});
</script>
Servlet code -
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
Map<String, String> job = new LinkedHashMap<>();
//doGet(request, response);
JSONArray jArray = new JSONArray();
// response.setContentType("text/html");
PrintWriter out= response.getWriter();
String n = request.getParameter("apiname");
String p = request.getParameter("apiendpoint");
String e = request.getParameter("apiversion");
String c = request.getParameter("source");
String status ="091";
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("driver loaded");
System.out.println("Driver is loaded");
Connection con= (Connection) DriverManager.getConnection("jdbc:mysql://localhost/apiprovider","root","");
System.out.println("Connection created");
PreparedStatement ps= ((java.sql.Connection) con).prepareStatement("insert into apiinfo(apiname,apiendpoint,apiversion,accessibility) values (?,?,?,?)");
ps.setString(1,n);
ps.setString(2,p);
ps.setString(3, e);
ps.setString(4,c);
ps.execute();
out.close();
status ="000";
con.close();
System.out.println("Inserted");
}
catch(Exception e1)
{
System.out.println(e1);
}
job.put("status",status);
jArray.put(job);
System.out.println(jArray.toString());
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jArray.toString());
}
That is because when you sent the ajax request as this:
$.ajax({
type: "POST",
url: "HomeServlet",
contentType: "application/json",
dataType:'json',
data:{"apiname":apiname,"apiendpoint":apiendpoint,"apiversion":apiversion,"source":source},
success: function(status){
console.log("Entered",status);
},
error:function(error){
console.log("error",error);
}
});
you send the data as normal POST parameters (not Stringnyfied) and you tell your servlet that this is a JSON string (Which is not!!!)
So to actually get this to work you have to either Stringnify the data you send to the servlet or to remove the contentType: "application/json" and 'dataType:'json' so you can treat the data as normal POST data.
**=========================== MY JAVA FUNCTION RETURNS AN ARRAYLIST============
public ArrayList<Class1> getDetails(String id, String year) {
ArrayList<Class1> arraylist1 = new ArrayList<Class1>();
return arraylist1;
}
============================== SERVLET CODE =================================
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
String operation=request.getParameter("operation");
log.debug("Operation : "+operation);
Class1 obj1 = new Class1();
response.setContentType("text/plain");
PrintWriter out = response.getWriter();
if(operation.equals("getDetails")){
ArrayList<Class1> record1 = new ArrayList<Class1>();
String id = request.getParameter("id_code");
String year = request.getParameter("fin_yr");
if(id != null) {
record1 = obj.geDetails(id, year);
}
out.print(record1);
}
} catch(Exception e){
log.error("Exception : "+ e.toString());
}
}
======================JSP CODE=====================================
if($('idCode').val() != ""){
$('#IdCode').focus(function(){
var fYear = $('#txtYear :selected').attr('label');
htmlObj = $.ajax({
type: "GET",
url: "Servlet1",
data: "operation=getDetails&id_code="+ $('#IdCode').val() + "&fin_yr="+ fYear,
async: false,
contentType:"text/html; charset=utf-8",
dataType:"html",
success: function(result){
}
}
});
});
}**
In this above code i added dummy function that will return an arrayList after servlet calls that function. Now my question is how do i get arraylist into may jsp page.
I got arraylist properly upto servlet i have no idea how do i get it into my jsp page and designs controls as per the size of servlet returned by sevlet.
You did not add elements to your list. So even if you iterate over the list, there will be no elements inside. Basically you can iterate over the list on the jsp using java code between these: <% ... %>
But this is not best practice.
You can include your list to the response:
request.setAttribute("list", categoryList);
And at the jsp you can get it, and iterate over it:
<%
// retrieve your list from the request, with casting
ArrayList<Category> list = (ArrayList<Category>) request.getAttribute("list");
// print the information about every category of the list
for(Category category : list) {
out.println(category.getId());
out.println(category.getName());
out.println(category.getMainCategoryId());
}
%>
Please look at this answer: Passing ArrayList from servlet to JSP
I need to refresh my data at certain points in my application (after a pop up form is closed). The application in essence allows users to submit forms, save data, and reopen the forms and view/edit the data.
I'm calling an ajax request from a javascript function. The ajax then calls the java function, which in debugging appears to execute without issue, but right after that's performed, I got an ajax error with status 200. I read some things online, and instead of using a POST type, changed it to a GET, but now I get a 500 status, and can't access the data anymore; my belief is that I'm being logged out.
This is the javascript/ajax function:
function refreshData(){
$.ajax({
url: "./profileEntriesAction.do",
data: "toMethod=refreshData",
type: "GET",
success: function(data){
alert('success :: ' + data);
}
});
}
On the java side (profileEntriesAction), I have:
#SuppressWarnings("unchecked")
public ActionForward refreshProfile(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception{
HttpSession objSession = request.getSession();
User user = (User) objSession.getAttribute(Constants.USER_KEY);
ActionErrors errors = new ActionErrors();
ActionMessages messages = new ActionMessages();
ProfileBean pBean = (ProfileBean)objSession.getAttribute("pBean");
ProfileForm pForm = (ProfileForm)objSession.getAttribute("ProfileForm");
if (user == null)
return (mapping.findForward("logon"));
//get connection to db from the pool using a static method
Connection objConn = StartUpServlet.getPoolConnection();
try{
System.out.println("refreshProfile 2");
/////////////////////////////
/////////////////////////////
IntDAO iDAO = new IntDAO();
// get lists data
if (!pForm.isNoInts()) {
Object[] arr = iDAO.getLists(objConn, pBean.getProfileId());
pForm.setList((ArrayList<Ints>) arr[0]);
}
/////////////////////////////
/////////////////////////////
}catch(SQLException ex){
if(ex.getErrorCode() == Constants.SQL_ERROR_CODE_UNACCESSIBLE_RESOURCE && ex.getSQLState().equalsIgnoreCase(Constants.SQL_SQL_STATE_UNACCESSIBLE_RESOURCE)){
objLogger.error("DB maintenance :\n" + ex.getMessage());
errors.add(Globals.ERROR_KEY, new ActionMessage("error.db.maintenance"));
} else {
objLogger.error("Error while refreshing the profile - Profile Id "+ pBean.getProfileId()+" :\n" + ex.getMessage());
errors.add(Globals.ERROR_KEY, new ActionMessage("error.entry.refresh.profile", "Profile"));
}
if(objConn != null)
objConn.rollback();
}catch(Exception e){
objLogger.error("Error while refreshing the profile - Profile Id "+ pBean.getProfileId()+" :\n" + e.getMessage());
errors.add(Globals.ERROR_KEY, new ActionMessage("error.entry.refresh.profile", "Profile"));
if(objConn != null)
objConn.rollback();
}finally {
if(objConn!= null && !objConn.getAutoCommit())
objConn.setAutoCommit(true);
// return the connection to the pool using a static method
StartUpServlet.rtnPoolConnection(objConn);
}
if (!errors.isEmpty()) {
saveErrors(objSession, errors);
}
if(!messages.isEmpty()){
saveMessages(objSession, messages);
}
return mapping.findForward("success");
//return null;
}
I've tried commenting out the entire contents of the java function and just returning the mapping.findForward("success"); but I still get the same errors.
I am busy quite with my new project where I working on jPlayer, completely based on jQuery.
I am very new in jQuery so I am facing lots of problems but now I am little comfortable with jQuery.
My requirement is to access a absolute url if the given url is relative, for that I used some java code. Each and every thing is working well but to fetch the absolute url I used java code for that I used jsp page and execute that using ajax call. Problem is the value returning from jsp is having lots of extra datas, generally all the html tags. I saw this question is already asked by some person and the reply
"use servlet instead of jsp because jsp for presentation and this will output some html".
and my codes are:
function funAJAX(songURL){
var path=document.getElementById("url").value,
ext=songURL.split('.').pop(), // trying to pull extension of link
xmlhttp, absUrl;
//alert(path);
if(window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
// code for IE6, IE5
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
//$("#tempUrl").html(xmlhttp.responseText);
//storing val in div of id="tempUrl"
// absUrl=$("#tempUrl").find("info").text();
//fetching the link only
var v=xmlhttp.responseText;
alert("value from ajax: " + v);
if(ext == "mp3" || ext == "Mp3") { // if absolute url then songUrl val will not change
// alert("extension: "+ext);
ext=ext;
}
else { // if relative link then storing the val returned from ajax as absolute link
// alert("in else part");
songURL=absUrl;
}
alert("i2: song url: " + songURL); // this will execute after returning val from jsp because of ajax call
}
};
// alert("2: song url: "+songURL); //this will execute before sending req to jsp page
xmlhttp.open("GET", "" + path + "/html/player/songURLManipulation.jsp?songURL=" + songURL, true); //calling songURLManipulation.jsp with argument songUrl
xmlhttp.send(); //sending the req
}
above is my jsp page and having lots of tag
"/>
this liferay problems but main thing is to implement jplayer
and my another jsp that one I am calling through ajax is
<%
String songURL=request.getParameter("songURL");
String location=null;
if(songURL!=null) {
HttpURLConnection con = (HttpURLConnection)(new URL(songURL).openConnection());
con.setInstanceFollowRedirects( false );
con.connect();
location = con.getHeaderField("Location");
response.getWriter().print(location);
out1.print(location);
}
//return location;
System.out.println("from song manipulation.jsp: "+songURL);
%>
I achieved this one by using serveResource method and calling that method by ajax by using json object but my question is, is it really not achievable through jsp page return value if I call through above describe way.
It is really good to be part of this forum.
my ajax code
function funAJAXServlet(songURL,servletURL)
{
alert("from ajax fun");
jQuery.ajax({
url :servletURL,
data: {"songURL":songURL},
type: "GET",
dataType: "json", //describe the type of value returned from serveResource class
success: function(data) {
//to put data data into div part of html and data is coming from serveResource class.
var jsonobj=data.songUrlServlet;
alert("from servlet ajax: "+jsonobj);
}
});
}
and my serveResource method
public void serveResource(ResourceRequest request, ResourceResponse response)
{
String songURL=request.getParameter("songURL");
JSONObject jsobj=null;
String location=null;
HttpURLConnection con;
System.out.println("songURL from serveResourceUrl servlet method: "+songURL);
if(songURL!=null)
{
try
{
con = (HttpURLConnection)(new URL(songURL).openConnection());
con.setInstanceFollowRedirects( false );
con.connect();
location = con.getHeaderField("Location");
System.out.println("$$$$$$$$$$$4 location val: "+location);
jsobj = JSONFactoryUtil.getJSONFactory().createJSONObject();
if(location!=null)
jsobj.put("songUrlServlet",location);
else
jsobj.put("songUrlServlet","null");
PrintWriter writer = response.getWriter(); //writing to the client page
writer.write(jsobj.toString());
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
//return location;
else
System.out.println("from song serveResource method: "+songURL);
}
This is working fine.