Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Simple HTML - Linking to a Servlet

Status
Not open for further replies.

timesign

Programmer
May 7, 2002
53
US
I have a load of text files that users can download from my site. I Wrote a short servlet to send them to the user with a "open, save as" dialog box.

On the HTML side I Currently have a link
Code:
 <A HREF=&quot;/servlet/FileServer&quot;>text.txt</A>

BTW I had to change the servlet to a doGet instead of a doPost to work.

The Question: Using a link, not a form, I would like to call the servlet with the name of the file I want to download. This will mean I do not need a new servlet for each file. How do send from the HTML page the name of the file to my HttpServletRequest ?

Thanks

 
I don't understand your aversion to forms ...

So your html page will look like this
Code:
<html>
	<head>
		<script language=&quot;javascript&quot;>
			function sub(cmd) {
				document.forms[0].file.value = cmd;
				document.forms[0].submit();
			}
		</script>
	</head>
	<body>
		<table>	
		<tr>
			<td><a href=&quot;#&quot;onClick=&quot;sub('test.txt')&quot;> test.txt</a>&nbsp;</td>
			<td><a href=&quot;#&quot;onClick=&quot;sub('file.txt')&quot;> file.txt</a>&nbsp;</td>

		</tr>
		</table>	
		<form method=&quot;post&quot; action=&quot;/servlet/FileServlet&quot;>
			<input type=&quot;hidden&quot; name=&quot;file&quot;>
		</form>

	</body>
</html>

and in your servlet's doGet() or doPost() method the code to retrieve the file name will look like :

Code:
 // request is the HttpServletRequest object
 String file = request.getParameter(&quot;file&quot;);

PS, its generally accepted/good practice for a servlet to manage both doGet() and doPost() methods (unless you have a very good reason for not supporting one HTTP method).

So if you do all your work in doPost(), then your doGet() should &quot;forward&quot; control to the the doPost() - like :

Code:
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException {
		doPost(request, response);
	}

This way, your servlet will service both HTTP GET and POST methods ...
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top