I am trying to add parameter and redirect to a page that only accepts request in post method. I am using this code in my servlet and it is not forwarding me to the url.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String url = "http://www.thisone.com";
InputStream in = null;
try {
HttpClient client = new HttpClient();
PostMethod method = new PostMethod(url);
//Add any parameter if u want to send it with Post req.
method.addParameter("User", "xyz");
method.addParameter("Name", "abc");
int statusCode = client.executeMethod(method);
System.out.println(statusCode);
if (statusCode != -1) {
response.sendRedirect(response.encodeRedirectURL(url));
in = method.getResponseBodyAsStream();
}
} catch (Exception e) {
e.printStackTrace();
}
}
I don't think it's possible to redirect with post method using this approach. what you can do is get the response to the client and therefore set the location header in response. Implementation for the same is given below:
Once your condition is satisfied:
response.setStatus(307);
response.addHeader("Location", "<url>");
also check out the significance of 307 status code.
Here is the javascript code, which starts with an ajax request and hit a servlet to fetch the desired URL, once it receives the URL, creates a HTML form object, sets values and submits the form...
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callURL(this.responseText);
}
};
xhttp.open("GET", "TestServlet", true);
xhttp.send();
function callURL(url){
var form = document.createElement("form");
form.setAttribute('method', 'POST');
form.setAttribute('action', url);
form.setAttribute('id', 'frmProduct');
form.style.display = 'none';
var i = document.createElement('input');
i.setAttribute('type', 'text');
i.setAttribute('name', 'name');
i.setAttribute('value', 'Neeraj');
form.appendChild(i);
document.getElementsByTagName('body')[0].appendChild(form);
form.submit();
}
</script>
Below is the implementation of my Testservlet
#WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TestServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String url = "http://www.thisone.com";
PrintWriter out = response.getWriter();
out.print(url);
}
}
You can make use of automatic form submit using POST method to do the same.
Please find below sample code:
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
sendPOSTRedirect(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
sendPOSTRedirect(request, response);
}
private void sendPOSTRedirect(HttpServletRequest request, HttpServletResponse response) throws IOException {
response.setContentType("text/html");
String postURL = "url to send data";
String value1 = "value for name1";
String value2 = "value for name2";
String content = "<html><body onload='document.forms[0].submit()'><form action=\"" + postURL + "\" method=\"POST\">"
+ "<INPUT TYPE=\"hidden\" NAME=\"name1\" VALUE=\"" + value1 + "\"/>"
+ "<INPUT TYPE=\"hidden\" NAME=\"name2\" VALUE=\"" + value2 + "\"/>"
+ "</form></body></html>";
response.setStatus(HttpServletResponse.SC_OK);
PrintWriter out = response.getWriter();
out.write(content);
}
Related
I am trying to send a canvas PNG to a java servlet using ajax.
Here is my javascript code:
function sendToServer(image){
$.ajax({
type: "POST",
url: "SaveAnnotation",
data: {
annotationImage: image
},
success: function(msg)
{
alert(msg);
},
error: function()
{
alert("Error connecting to server!");
}
});
}
function save() {
var dataURL = canvas.toDataURL();
sendToServer(dataURL);
}
And the java servlet doPost():
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/plain");
try{
String img64 = request.getParameter("annotationImage");
byte[] decodedBytes = DatatypeConverter.parseBase64Binary(img64);
BufferedImage bfi = ImageIO.read(new ByteArrayInputStream(decodedBytes));
File outputfile = new File("saved_annotations/saved.png");
ImageIO.write(bfi , "png", outputfile);
bfi.flush();
out.print("Success!");
}catch(IOException e){
out.print(e.getMessage());
}
}
The problem is that getParameter("annotationImage") returns null, and I can't understand why: using browser debugger I can see annotationImageand its value between the request parameters, so I am sure it is not null, but for some reason the parameter is not received by the Java Servlet.
I found out the reasons why it didn't work.
To avoid parsing JSON I send the data to the server without setting any parameter, writing data: image instead of JSON formatted data: {annotationImage: image} to avoid JSON parsing in the servlet.
In the java servlet I get the entire request body, remove the content-type declaration and finally decode and save the image. Here is the code:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
StringBuffer jb = new StringBuffer();
String line = null;
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
String img64 = jb.toString();
//check if the image is really a base64 png, maybe a bit hard-coded
if(img64 != null && img64.startsWith("data:image/png;base64,")){
//Remove Content-type declaration
img64 = img64.substring(img64.indexOf(',') + 1);
}else{
response.setStatus(403);
out.print("Formato immagine non corretto!");
return;
}
try{
InputStream stream = new ByteArrayInputStream(Base64.getDecoder().decode(img64.getBytes()));
BufferedImage bfi = ImageIO.read(stream);
String path = getServletConfig().getServletContext().getRealPath("saved_annotations/saved.png");
File outputfile = new File(path);
outputfile.createNewFile();
ImageIO.write(bfi , "png", outputfile);
bfi.flush();
response.setStatus(200);
out.print("L'immagine e' stata salvata con successo!");
}catch(IOException e){
e.printStackTrace();
response.setStatus(500);
out.print("Errore durante il salvataggio dell'immagine: " + e.getMessage());
}
}
I have a jsp file with google map, place autocomplete and few buttons. The submit Button click calls a method in Javascript which inturn passes the jsp page 'input' data to callServlet() method as 'params'. I want to call a servlet page MyServlet and pass the params to it. However my callServlet() executes perfectly but doesn't pass on the control/params to MyServlet.
Also How to read params in MyServlet?
Please help me solve it.
JS code:
function callServlet(params) {
var xmlhttp = new XMLHttpRequest();
var url = "./mapServlet";
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else
{// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
console.log(url);
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
console.log("Its perfect");
} else {
alert(xmlhttp.status);
}
}
xmlhttp.open("POST", url, true);
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-Length", params.length); // POST request MUST have a Content-Length header (as per HTTP/1.1)
// params is of json format with key value pairs
xmlhttp.send(params);
}
Servlet code: (Made no changes to this page. Its a simple servlet template)
public class MyServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { ... }
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.print("aaas");
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
web.xml
<servlet>
<servlet-name>mapServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mapServlet</servlet-name>
<url-pattern>/mapServlet</url-pattern>
</servlet-mapping>
Is there a specific reason you're not using jQuery for that?
Basically, xmlhttp.send(params) expects to receive key=value string, not a Json. If you intend to use bare XMLHttpRequest, you'll need to create this string on your own.
Also, this mapping: var url = "./mapServlet"; may be wrong, as usually you serve code from root, and your JS files are served from resource directory such as /js. Using `var url = "/mapServlet" would be better.
Finally, after you reach your servlet, you can read your parameters using request.getParameter("parameter_name")
To call your server using jQuery start with using jQuery.post() method:
https://api.jquery.com/jquery.post/
$.post( "./mapServlet", params)
.done(function( data ) {
console.log("Got ", data);
});
I'm new to Java and Android development and try to create a simple app which should contact a web server A and send,add some data to text using a http get.
I have simple HTML code with some javascript (server A)
<html>
<head>
<title>This is my Webpage</title>`enter code here`
<h1>My Example</h1>
<script>
function myFunction(){
document.getElementById("myid").value=$ab;
}
</script
</head>
<body onload="myFunction()">
<input id="myid" type="text" />
</body>
</html>
and i have Android code to send http request to a local (server A)
public class MainActivity extends Activity {
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button=(Button) findViewById(R.id.click);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String url = "http://www.localhost/tuan/example.html";
MyCommandTask task = new MyCommandTask();
task.execute(url);
}
});
}
public class MyCommandTask extends AsyncTask<String,Void,Document>
{
#Override
protected Document doInBackground(String... params) {
String url=params[0];
try {
HttpGet httpGet = new HttpGet(url);
}
catch (Exception ex)
{
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Document document) {
super.onPostExecute(document);
}
}
}``
Now i want send text data and show result in text on (server A).
Please anyone help me.
Check this out dude. http://developer.android.com/training/basics/network-ops/connecting.html#download . Since you already got url string in doInBackground() method , use below code
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 500;
try {
URL url = new URL(myurl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
// Starts the query
conn.connect();
int response = conn.getResponseCode();
Log.d(DEBUG_TAG, "The response is: " + response);
is = conn.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
return contentAsString;
// Makes sure that the InputStream is closed after the app is
// finished using it.
} finally {
if (is != null) {
is.close();
}
}
Don't forget to change return type of doInBackground() to String as well. If you wanna go further , try grab volley which is one of the awesome network library https://developer.android.com/training/volley/index.html
Here is how you can post data to server. Put these line inside doInBackground()
private static final String POST_PARAMS = "userName=Pankaj";
URL obj = new URL(POST_URL);
HttpURLConnection con = (HttpURLConnection) obj.openConnection();
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
// For POST only - START
con.setDoOutput(true);
OutputStream os = con.getOutputStream();
os.write(POST_PARAMS.getBytes());
os.flush();
os.close();
// For POST only - END
int responseCode = con.getResponseCode();
System.out.println("POST Response Code :: " + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) { //success
BufferedReader in = new BufferedReader(new InputStreamReader(
con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
// print result
System.out.println(response.toString());
} else {
System.out.println("POST request not worked");
}
Here is the source
I am sending a json object via ajax call.
When I try to print the json's values I am getting nulls.
What am I doing wrong?
Servlet:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write("[{\"PARENT\":\"2\",\"VAL\":\"X7280\"},{\"PARENT\":\"2\",\"VAL\":\"X8338\"}]");
}
javascript:
function handleIt() {
var url = "myservlet";
var parameters = "method=method";
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", parameters.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4) {
var ddl3 = http.responseText;
for(var key in ddl3){
var id = ddl3[key].PARENT;
var lbl = ddl3[key].VAL;
alert (lbl);
}
}
}
http.send(parameters);
}
When I try to call Jena using AJAX in my servlet I get this error:
java.lang.ClassNotFoundException: com.hp.hpl.jena.sparql.core.Prologue
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1516)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1361)
at fr.objective.blogomatic.semantic.web.ServletAjax.doGet(ServletAjax.java:40)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Unknown Source)
This is my Jena code:
class classUsingJena {
public void execute(){
String queryString = PREFIXES
+ " Select ?label "
+ " where {"
+ " ?description j.5:entity-label ?label ." + " } ";
Query query = QueryFactory.create(queryString);
QueryExecution qe = QueryExecutionFactory.create(query, model);
ResultSet results = qe.execSelect();
ResultSetFormatter.out(System.out,results, query);
qe.close();}
}
It's running fine, but when I call this function using servlet I get the error described previously.
This is my servlet code:
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String service = req.getParameter("service");
classUsingJena jena= new classUsingJena() //bug
return;}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
#Override
public void init() throws ServletException {
ServletConfig config = getServletConfig();
urlAjax = config.getInitParameter("urlAjax");
}
My java script code that runs fine:
$("#Analyser").click(function(){
var article = $("#TxtArea").val();
ajaxFunction("acteur",article);
console.log(article);
});
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(valeur,txt) {
if(xmlhttp) {
xmlhttp.open("GET","ajax?service=ajax&valeur="+valeur+"&text="+txt,true);
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) {
$("#J").text("");
parseXml(xmlhttp.responseXML);
}
else {
//alert("Error during AJAX call. Please try again");
}
}
}
function parseXml(xml)
{
$(xml).find("nom").each(function()
{
$("#J").append($(this).text() + "<br />");
});
}
In the pom I had declared the old version of Arq 1.8.7 instead of 2.8.7. Now it's running fine.