Parameter to servlet
Hi, somebody can tell me how a generic servlet can get a parameter from a JSP/JSF/ADF page?
Thanks
Thanks Shay. But I´m work with login and psw. If I use servlet url, I show psw in the url. I would like a sample code kind:
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {response.setContentType(CONTENT_TYPE);
FacesContext fc = FacesContext.getCurrentInstance();
ExternalContext ec = fc.getExternalContext();
HttpServletRequest request1 = (HttpServletRequest)fc.getExternalContext().getRequest();
String nome = request1.getParameter("username");
String psw = request.getParameter("password");
etc, etc, etc...
Is it exist? When I try use that code, I receive a nullPointException...
Any idea?
Similar Messages
-
Unable to access form parameter in servlet
What could be the possible reasons, If a server side program say a servlet, cannot access the request parameters.
I mean, i have a form and it uses get method. Now on submitting the form, I can see the query string in url but unable to access the same in servlet.
thank you all
RaviThe most obvious reason might be that the servlet's
programmer wrote crappy code.
Show the code where you try to read the parameters,
please.Code is simple. To retrieve the form parameter I used the same
request.getParameter("paramname")
And in the form method used is get. After submission of form, I can see the form parameter appended to url
something like this:
http://localhost/servlets/Test?paramname=somevalue
But for somereason in servlet i.e at request.getParameter("paramname"), is hanging here.
I checked the paramname, no spelling mistakes as well :)
But i am not able to find out the reason why I am not able to get the paramname in servlet.
thanks
Ravi -
How can i pass parameter from a JSP form (depends on what user chooses from a select box to a Servlet.
I need to call multiple query based on what parameter choosen and display the result in table view.
Example :
1. User select choice1 from JSP form -> Servlet : call query Select * from Table1 where cond = choice1;
2. User select choice2 from JSP form -> Servlet : call query Select * from Table1 where cond = choice2;
Any sample code?
Thanks for any help.Thanks melondck.
I have this Servlet which i want it to run queries and display results in table format. I know there's something wrong with the code. But i am new to Servlet/Java. Thanks for anyone who point me the mistakes. Thanks.
<code>
package mypackage;
import java.sql.*;
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.*;
public class DisplayServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse rsp)
throws ServletException, IOException {
rsp.setContentType("text/html");
String url="jdbc:mysql://localhost/smdb";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
String query;
ServletOutputStream out = rsp.getOutputStream();
PrintWriter out1 = rsp.getWriter();
String answer = req.getParameter("answer");
out1.println("<html>");
out1.println("<head><title> Inventory: </title></head>");
out1.println("<body>");
if (answer == null) {
StringBuffer action = HttpUtils.getRequestURL(req);
out1.println("<form action=\"" + action + "\" method=\"POST\">\n");
out1.println("<p><b>Please select:</b></p>");
out1.println("<p><input type=\"radio\" name=\"answer\" " +
"value=\"A\" /> Display All <br />");
out1.println(" <input type=\"radio\" name=\"answer\" " +
"value=\"B\" /> Device <br />");
out1.println(" <input type=\"radio\" name=\"answer\" " +
"value=\"C\" /> Manufacturer <br />");
out1.println(" <input type=\"radio\" name=\"answer\" " +
"value=\"D\" /> Location <br />");
out1.println(" <input type=\"submit\" value=\"Submit\" /></p>");
out1.println("</form>");
} else {
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection (url, "user", "mypass");
stmt = con.createStatement();
if (answer.equals("A")) {
query = "SELECT Device, LocFloor FROM Inventory";
esleif (answer.equals("B)) {
query = "SELECT Device, LocFloor FROM Inventory where ....";
ResultSet result = stmt.executeQuery(query);
//Display the result set in a HTML table
out.println("<HTML><HEAD><TITLE>List</TITLE></HEAD>");
out.println("<BODY>");
out.println("<FORM NAME='form' ");
out.println("METHOD='GET'><TABLE BORDER='1' CELLSPACING='2' CELLPADDING='2'>");
out.println("<TR><TH></TH><TH>Device Type</TH><TH>Floor</TH></TR>");
while(result.next()) {
String type = result.getString("Device");
String flr = result.getString("LocFloor");
out.println("<TD>" + type + "</TD>");
out.println("<TD>" + flr + "</TD>");
catch(ClassNotFoundException e) {
out.println("Could not load database driver: " + e.getMessage());
catch(SQLException e) {
out.println("SQLException caught: " + e.getMessage());
finally {
//close the database connection.
try {
if (con != null) con.close();
catch (SQLException e) {}
out.println("</body></html>");
</code> -
Cannot pass parameter to servlet
dear all,
I am writing a MIDlet to post some data to a servlet.At the MIDlet, i set as below:
String url = getAppProperty("Login.URL");
conn = (HttpConnection)Connector.open(url);
conn.setRequestMethod(HttpConnection.POST);
conn.setRequestProperty("User-Agent", "Profile/MIDP-1.0 Configuration/CLDC-1.0");
conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
conn.setRequestProperty("Accept", "application/octet-stream" );
conn.setRequestProperty("Connection", "close" );
os = conn.openOutputStream();
byte data [] = ("userid="+userid.getString()).getBytes();
os.write(data);
data = ("&password="+password.getString()).getBytes();
os.write(data);
os.flush();
At the servlet, I coded:
String id = request.getParameter("userid"),
pass = request.getParameter("password");
When i posted "userid=123&password=123" to the servlet, the servlet directed me to 'LoginFail.jsp' with below output:
Login fail!
null //should be print out userid and password value
can anyone please give me some suggestions, why the servlet cannot locate parameter and how to solve it?
thanx a lot!<p>wongyuenmei</p>
<p>I've done some similar program. I'm not sure why request.getParameter() won't return the value we past. However, I managed to resolve the problem with the following way:</p>
<p>Remain your MIDlet code. But change your servlets to use the following rather request.getParameter()</p>
<pre>
ServletInputStream sis = request.getInputStream();
DataInputStream din = new DataInputStream(sis);
String id = din.getUTF();
String pass = din.getUTF();
</pre>
<p>Good luck!</p> -
I can get a parameter with the ServletRequest.getAttribute(...) right?
But how can I give the parameter to the servlet?
Is it something like http://.../servlet/framePack.frameBase?table=env ?Yer confusing parameters with attributes.
Parameters are something that are submitted by a html form.
you should be using request.getParameter() to get those parameters.
can get a parameter with the ServletRequest.getAttribute(...) right?refer to above.
But how can I give the parameter to the servlet?There's nothing as setParameter(); It has to be given via form submission or by building an url of the form
http://host:8080/yourapp/yourservlet?param1=val1¶m2=val2.... and in the servlet you can get the values by doing a getParameter( on the request.
Is it something like http://.../servlet/framePack.frameBase?table=env ?
refer to above. -
Passing parameter from servlet to Javascript url
Hi all,
I want to pass the value of a selected option box in servlet as a parameter to a url in JavaScript.
my java script code is :
out.println("function reloadform() { ");
out.println("alert('aacat');");
out.println("location.href = 'http://localhost:8080/examples/servlet/frec1?aacatt=aacat';");
out.println("}");
and servlet code is :
out.println("<td bgcolor=#F2F9FF> <select name=aacat size=1 style=font-size: 8pt; color: #666666; font-family: Verdana; border: 1 solid #666666 onChange= 'reloadform();'>");
while (ra.next()==true) {
String mycat=ra.getString("acat");
String myasc=ra.getString("ascode");
out.println(mycat+"<br>");
out.println("<option value='"+mycat+"'><font face=verdana size=1>"+mycat+"</font></option>");
Can anyone suggest me something on this ? Any Code reference will be highly appreciated.
Thanks for any help in advance.
savdeep.Please take care post the code in proper format...
regarding the solution.. try something like..
<select name=aacat size=1 style=font-size: 8pt; color: #666666; font-family: Verdana; border: 1 solid #666666 onChange= 'reloadform(this.options[this.selectedIndex].value);'>");also change the javascript code suitably -
How should i send parameter to servlet
i want to sent parameter to the servlet
i am using servlet applet cumunication
and when i am coling the servlet i want
send one or more parameter to the servelt
depend on that servlet perform action
how should i sent the parameter please
tell me,
Rahulhow should i sent the parameter pleaseHow should we know that ? It's your decision
Your applet may open a (Http)URLConnection to the Servlet
there you write your parameters in URLEncoded form to the output stream
of the URLConnection setting the RequestMethod to POST.
After that you read the response from the input stream.
andi -
Add parameter to servlet request
Can anyone tell me how should I add a parameter to the httprequest sent drom the MIDlet to the servlet , so that I can retreive the same in the servlet using getParameter()?
I'm not 100% sure which value the getPara returns, so
if it is part of the header, i.e.
accept: text/html, ...
then use
setRequestProperty()
Otherwise, just tag it on to the end of the URL:
http://www/file.jsp?param=p1¶m2=p2... -
Accesing a html parameter from servlet is not producing in a new file
Hi,...
I have passed two values from html and accessed thru a servlet file.
In servlet, parameters are verified and result must passed to a new jsp file.
Wen i run the file i can view only a blank page.I think the problem will be in servlet mapping.
verify my coding and give me a result.
I wer using net bean 6 with glassfish v2 server.
public class Logverifier extends HttpServlet {
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Logverifier</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Logverifier at " + request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
ServletConfig config=getServletConfig();
String user=config.getInitParameter("user");
String pass=config.getInitParameter("pass");
ServletContext context=getServletContext();
RequestDispatcher reqdis=context.getRequestDispatcher("menu.jsp");
RequestDispatcher reqdis1=context.getRequestDispatcher("login.jsp");
if((user.equals(request.getParameter("user")))&&(pass.equals(request.getParameter("pass"))))
reqdis.forward(request, response);
else
reqdis1.forward(request, response);
} finally {
out.close();
<servlet>
<servlet-name>Logverifier</servlet-name>
<servlet-class>com.Logverifier</servlet-class>
<init-param>
<description> </description>
<param-name>user</param-name>
<param-value>admin</param-value>
</init-param>
<init-param>
<param-name>pass</param-name>
<param-value>media</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Logverifier</servlet-name>
<url-pattern>/com/Logverifier</url-pattern>
</servlet-mapping>
</servlet>
regards,
satheeshHi,...
I have passed two values from html and accessed thru a servlet file.
In servlet, parameters are verified and result must passed to a new jsp file.
Wen i run the file i can view only a blank page.I think the problem will be in servlet mapping.
verify my coding and give me a result.
I wer using net bean 6 with glassfish v2 server.
public class Logverifier extends HttpServlet {
* Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
/* TODO output your page here
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Logverifier</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Logverifier at " + request.getContextPath () + "</h1>");
out.println("</body>");
out.println("</html>");
ServletConfig config=getServletConfig();
String user=config.getInitParameter("user");
String pass=config.getInitParameter("pass");
ServletContext context=getServletContext();
RequestDispatcher reqdis=context.getRequestDispatcher("menu.jsp");
RequestDispatcher reqdis1=context.getRequestDispatcher("login.jsp");
if((user.equals(request.getParameter("user")))&&(pass.equals(request.getParameter("pass"))))
reqdis.forward(request, response);
else
reqdis1.forward(request, response);
} finally {
out.close();
<servlet>
<servlet-name>Logverifier</servlet-name>
<servlet-class>com.Logverifier</servlet-class>
<init-param>
<description> </description>
<param-name>user</param-name>
<param-value>admin</param-value>
</init-param>
<init-param>
<param-name>pass</param-name>
<param-value>media</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Logverifier</servlet-name>
<url-pattern>/com/Logverifier</url-pattern>
</servlet-mapping>
</servlet>
regards,
satheesh -
Hi,
I have one servlet HTML page which gets the input from the user andon submittingthe form one mroe servlet is called which validates and dependig user value it will form the SQL select.
Then I need to call Servlet which will generate an HTML page with the result set of the SQL.
My problem is that from the processing form I need to send parameters and I am calling the final servlet usign forwardRequest. I formed the query string in teh form name=value and send the final string.
I want to know whether they is any better way to achieve this.
Please help me out!!!u can get parameters from the processing form using the HttpServletRequest.getParameter(String ..) method. once got into the first servlet on processing if u need to pass them onto the second servlet using the forward mechanism then u store these values into the HttpServletRequest.setAttribute(...) and using the getAttribute() methos can retrieve them in the other...
-
Passing parameter from Servlet to javascript in JSP. Very Urgent - 5 jukes!
Well my servlet will retrieve questions from database.
Then the player will answer the question in the JSP and submit the answer to the servlet to process.
Each time an answer is submitted, or a "Next Question" button is clicked, the countdown time will restart.
And will reload the page with a new question.
So how can i do that?
This is my servlet, JSP, javascript
=====================================================================
* Interacts with the player depending on his types of selection and output them
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class GameQuestionServlet extends HttpServlet
String sSQL = null;
String sCategory = null;
String paramName = null;
User userObject = null;
Questions gameQsObj = new Questions();
HttpSession session;
int cnt = -1;
int score = 0;
boolean connected = false;
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
session = request.getSession(false);
//System.out.println("Testing Score:" + score);
if(connected == true)
Questions object = (Questions)gameQsObj.getQsList().elementAt(cnt);
System.out.println("\n" + object.sAns1);
System.out.println(object.sAns2);
System.out.println(object.sAns3 + "\n");
Enumeration enum = request.getParameterNames();
while(enum.hasMoreElements())
paramName = (String)enum.nextElement();
if(paramName.equals("mcq"))
System.out.println(request.getParameter("mcq"));
score = Integer.parseInt(userObject.score.trim());
System.out.println("Player old score: " + score);
//Check to see if the selected answer matches the correct answer
if((object.sCorrect).equals(request.getParameter("mcq")))
score = score + 10;
else
if((object.sCorrect).equals(request.getParameter("mcq")))
score = score + 10;
else
if((object.sCorrect).equals(request.getParameter("mcq")))
score = score + 10;
else
score = score - 10;
System.out.println("Player current score: " + score);
else //will only go into this once
userObject = (User)session.getAttribute("user");
System.out.println("\n"+userObject.nric);
System.out.println(userObject.name);
System.out.println(userObject.password);
System.out.println(userObject.email);
System.out.println(userObject.score+"\n");
//depending on user selection
sCategory = request.getParameter("qsCategory");
sSQL = "SELECT * FROM " + sCategory;
gameQsObj.getQuestions(sSQL, sCategory);
score = Integer.parseInt(userObject.score);
connected = true;
System.out.println("Connected:" + connected);
System.out.println("Before:" + userObject.score);
cnt = cnt + 1; //increment to retrieve next question
userObject.score = Integer.toString(score);
System.out.println("After:" + userObject.score);
if(cnt < 3) //setting for the number of questions per game.
//request.setAttribute("qsCnt", cnt); //count of the question number
request.setAttribute("aQs", gameQsObj.getQsList().elementAt(cnt));
System.out.println(request.getAttribute("aQs"));
System.out.println("This is question number: "+ cnt);
getServletConfig().getServletContext().getRequestDispatcher("/JSP/PlayGame.jsp").forward(request, response);
else
//forward to the result page
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
doPost(request, response);
<%@ page import="Questions" %>
<HTML>
<HEAD>
<TITLE>Play Game</TITLE>
<SCRIPT LANGUAGE="JavaScript">
var refreshinterval=10
var displaycountdown="yes"
var starttime
var nowtime
var reloadseconds=0
var secondssinceloaded=0
function starttime() {
starttime=new Date()
starttime=starttime.getTime()
countdown()
function countdown() {
nowtime= new Date()
nowtime=nowtime.getTime()
secondssinceloaded=(nowtime-starttime)/1000
reloadseconds=Math.round(refreshinterval-secondssinceloaded)
if (refreshinterval>=secondssinceloaded) {
var timer=setTimeout("countdown()",1000)
if (displaycountdown=="yes") {
window.status="You have "+reloadseconds+ " second before timeout"
else {
hide();
clearTimeout(timer)
//window.location.reload(true)
function hide() {
//hidelayer
if(gameLayers.style.visibility == "visible"){
gameLayers.style.visibility = "hidden"
oops.style.visibility = "show"
window.onload=starttime
</SCRIPT>
</HEAD>
<BODY>
<FORM METHOD="post" ACTION="http://localhost:8080/Java_Assignment2/servlet/GameQuestionServlet">
<DIV ID="oops" STYLE="position:absolute; left:300px; top:30px; width:120px; height:150px; z-index:2; visibility:hidden">
Oops! 30 seconds time up!!! <BR><BR>
<INPUT TYPE="submit" VALUE="Next Question">
<INPUT TYPE="hidden" NAME="nextQs" VALUE="Next Question">
</DIV>
<DIV ID="gameLayers" STYLE="position:absolute; left:300px; top:30px; width:120px; height:150px; z-index:3; visibility:show">
<TABLE BORDER="0">
<TR>
<TH><BIG>Questions:</BIG></TH>
</TR>
<%
Questions aQsObj = (Questions)request.getAttribute("aQs");
String aQsBody = aQsObj.sQs;
String aQsAns1 = aQsObj.sAns1;
String aQsAns2 = aQsObj.sAns2;
String aQsAns3 = aQsObj.sAns3;
%>
<TR>
<TD><B><%= aQsBody%></B></TD>
</TR>
<TR>
<TD>
<SELECT SIZE="3" NAME="mcq">
<OPTION SELECTED><%= aQsAns1 %></OPTION>
<OPTION><%= aQsAns2 %></OPTION>
<OPTION><%= aQsAns3 %></OPTION>
</SELECT><BR><BR>
</TD>
</TR>
<TR>
<TD>
<INPUT TYPE="submit" VALUE="Submit Your Answer">
<INPUT TYPE="hidden" NAME="submitAns" VALUE="Submit Your Answer">
</TD>
</TR>
</TABLE>
</DIV>
</FORM>
</BODY>
</HTML>
This must be answered before 28th of september.
Please help. It is indeed very urgent.this is just a skeleton code.. alot of stuff is not here..
<FORM name = "form1" action="../servlet/wateverSevlet>
<input type="text" name="searchStr" size="40">
<INPUT type="hidden" id=answer name=answer size=7>
<input type="button" name="button" value="Submit Answer" onClick="javascript:submitCheck(document.form1.searchStr.value);">
<input type="button" name="button" value="Skip Question" onClick="javascript:submitCheck('skip');">
</form>
<SCRIPT LANGUAGE="JavaScript">
function submitCheck(str)
form1.answer.value = str
form1.submit()
</script>i assuming you are submitting it to the same servlet regardless of whether the user clicks the skip question or the submit question button. -
Servlet to pass parameter to another servlet
Hi, I have a question. I have two servlets, servler A and servlet B. I wanna do this:
1)servlet A to pass a parameter to servlet B. No redirect is required.
2)servlet B to accept the parameter.
How do I do that?
Thanks1)servlet A to pass a parameter to servlet B. No redirect is required.
2)servlet B to accept the parameter.I completely agree with what capitao suggested.
As U said tht u need not require a redirect functionality
U actually need to implement a proxy kind of mechanism in this case
You may also go by using HttpURLConnection Object to retrive the info by passing few parameters.
checkout an eq code down below
HttpURLConnection server = (HttpURLConnection)(new URL("http://<hostname>:<port>/servletC")).openConnection();
server.setRequestProperty("testParam","testParam");
InputStreamReader isr = new InputStreamReader( server.getInputStream() );
BufferedReader in = new BufferedReader( isr );
response.setContentType( "text/html" );
PrintWriter outStr = response.getWriter();
String line = "";
while((line = in.readLine()) != null) {
outStr.println( line );
} -
Open Jasper Report in new page using servlet
Guys,
Looks very simple but i am having problem making this process work. I am using 11.1.1.4
This is my use case:
- From a employee page, user clicks on a menu item to open report for current employee. I need to pass appropriate report parameters to servlet and open report into new page.
I can successfully call servlet using commandmenuitem and set request parameters and call servlet from backing bean.... but that doesn't open report in a new page.... any way i can do this?
Another option i tried was that using gomenuitem and setting target=blank but in that case i need to pass the parameter using servlet url which i like to avoid.(in case i need to pass many parameters in future) (also values will be set on page so i need to generate url when then click the menuitem...... so there are some hoops and loops i need to go through) I don't know a way to pass the request parameter using backing bean to servlet... i don't think it is possible.
Those are the two approaches i tried.
If you have any better approach...I would appreciate if you can let me know. (i have searched on internet for two days now.... for the solution)
-R
Edited by: polo on Dec 13, 2011 7:22 AMHi,
Hope following will useful
http://sameh-nassar.blogspot.com/2009/10/using-jasper-reports-with-jdeveloper.html
http://www.gebs.ro/blog/oracle/jasper-reports-in-adf/ -
Create Image from Stream in Applet via Servlet
First of all, I apologize if this isn't posted to the proper forum, as I am dealing with several topics here. I think this is more of an Image and I/O problem than Applet/Servlet problem, so I thought this forum would be most appropriate. It's funny...I've been developing Java for over 4 years and this is my first post to the forums! :D
The problem is I need to retrieve a map image (JPEG, GIF, etc) from an Open GIS Consortium (OGC) Web Map Server (WMS) and display that image in an OpenMap Applet as a layer. Due to the security constraints on Applets (e.g., can't connect to a server other than that from which it originated), I obviously just can't have the Applet create an ImageIcon from a URL. The OpenMap applet will need to connect to many remote WMS compliant servers.
The first solution I devised is for the applet to pass the String URL to a servlet as a parameter, the servlet will then instantiate the URL and also create the ImageIcon. Then, I pass the ImageIcon back to the Applet as a serialized object. That works fine...no problems there.
The second solution that I wanted to try was to come up with a more generic and reusable approach, in which I could pass a URL to a servlet, and simply return a stream, and allow the applet to process that stream as it needs, assuming it would know what it was getting from that URL. This would be more usable than the specific approach of only allowing ImageIcon retrieval. I suppose this is actually more of a proxy. The problem is that the first few "lines" of the image are fine (the first array of buffered bytes, it seems) but the rest is garbled and pixelated, and I don't know why. Moreover, the corruption of the image differs every time I query the server.
Here are the relevant code snippets:
=====================Servlet====================
/* Get the URL String from the request parameters; This is a WMS
* HTTP request such as follows:
* http://www.geographynetwork.com/servlet/com.esri.wms.Esrimap?
* VERSION=1.1.0&REQUEST=GetMap&SRS=EPSG:4326&
* BBOX=-111.11361,3.5885315,-48.345818,71.141304&
* HEIGHT=480&...more params...
* It returns an image (JPEG, JPG, GIF, etc.)
String urlString =
URLDecoder.decode(request.getParameter("wmsServer"),
"UTF-8");
URL url = new URL(urlString);
log("Request parameter: wmsServer = " + urlString);
//Open and instantiate the streams
InputStream urlInputStream = url.openStream();
BufferedInputStream bis = new
BufferedInputStream(urlInputStream);
BufferedOutputStream bos = new
BufferedOutputStream(response.getOutputStream());
//Read the bytes from the in-stream, and immediately write them
//out to the out-stream
int read = 0;
byte[] buffer = new byte[1024];
while((read = bis.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, buffer.length);
//Flush and close
bos.flush();
urlInputStream.close();
bis.close();
bos.close();
.=====================Applet=====================
//Connect to the Servlet
URLConnection conn = url.openConnection();
conn.setUseCaches(false);
conn.setRequestProperty("header", "value");
conn.setDoOutput(true);
//Write the encoded WMS HTTP request
BufferedWriter out =
new BufferedWriter( new OutputStreamWriter(
conn.getOutputStream() ) );
out.write("wmsServer=" + URLEncoder.encode(urlString, "UTF-8"));
out.flush();
out.close();
//Setup the streams to process the servlet response
BufferedInputStream bis = new
BufferedInputStream(conn.getInputStream());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//Read the bytes and immediately write to the out-stream
int read = 0;
byte[] buffer = new byte[1024];
while((read = bis.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, buffer.length);
//Flush and close
bis.close();</code>
bos.flush();</code>
byte[] imageBytes = bos.toByteArray();
//Create the Image/ImageIcon
Toolkit tk = Toolkit.getDefaultToolkit();
Image image = tk.createImage(imageBytes);
imageIcon = new ImageIcon(image);
Could this be an offset problem in my buffers? Is there some sort of encoding/decoding I am missing somewhere?
Thanks!
BenWithout having a probing look, I was wondering why you do the following...
while((read = bis.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, buffer.length);
while((read = bis.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, buffer.length);
}Your int 'read' holds the number of bytes read in but you then specify buffer.length in your write methods?!? why not use read? otherwise you will be writing the end of the buffer to your stream which contains random memory addresses. I think thats right anyway...
Rob. -
Help needed to call a servlet from an applet
Hi,
can someone help me with the way to call a servlet from an applet.
actually on click of a button i wanna call my servlet and save some data in DB.
i am not able to call my servlet. see the sample code which i am trying..
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Upload")) {
try {
System.out.println("Upload button has been clicked -----------");
URL url = new URL("http://localhost:8084/uploadApp/TestServlet");
URLConnection urlConnection = url.openConnection();
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.setUseCaches(false);
ObjectOutputStream objOut = new ObjectOutputStream (urlConnection.getOutputStream());
objOut.writeBytes(userId); // pass parameter to servlet
objOut.flush();
objOut.close();
} catch (MalformedURLException ex) {
Logger.getLogger(ButtonListener.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ButtonListener.class.getName()).log(Level.SEVERE, null, ex);
is there any problem with the code? please suggest.hii,
checkout my add from, HTH
[http://forums.sun.com/thread.jspa?threadID=5419921&messageID=10885709#10885709]
... kopik
Maybe you are looking for
-
There is double quantity in the sales item report?
Hi all, I have created an infoset with sales order item and delivery The issue is there is one sales order item with qty 10 but because it was delivered on different dates with different quantity like 5,5 the report show likes sales order item
-
I have a landline with Verizon. I live in Saratoga N.Y. and have had the same landline here for 14 years, without a problem...before today (Approx.). Even when the powers' been out, at least the phone would work (which is why I have a land line). Tod
-
G/L account in cash and bank statement
Dear All, How to fill the field GL account in the cash and bank statement ? I have press tab but still can't open the list of G/L account. Thanks Rgds, Mark
-
OracleCommand + multiple query
I'm making some backup scripts using dbms_metadata.get_dll and and let's say i have a result like that ([...] - i've cut some info, cause it's long): CREATE TABLESPACE "TEST" DATAFILE 'E:\ORACLEXE\ORADATA\TEST.DBF' SIZE [...] CREATE TABLE "SYSTEM"."O
-
Administration link not displaying on webcenter
Hi, I have recently installed Oracle UCM and webcenter. Everything is up and running. Webcenter was installed by administrator (default user name - weblogic3) rights. After that no other user was created. Earlier the user (weblogic3) was able to see