简体   繁体   中英

passing parameter from jsp to servlet through url pattern of servlet

I got a requirement to send one parameter through url pattern of servlet (like we send through <a href="example.jsp?id=1">send</a> ) in the same way I need it through url pattern.

I do this with other possibilities like

  1. I can send that parameter as hidden type
  2. i can put in a request and session objects

these methods are working fine no problem

but through url it's not taking? I want to know whether it is possible or not?

the code I have tried

jsp page

<a href="download?filename=<%=filename%>" target="_blank"> <font color="black"><%=filename%> </font></a>

servlet code

 String  filename=request.getParameter("filename");

and i need one answer can we pass parameter through url pattern if yes how? ie like same as through <a href="example?id=1">send</a> or differently?

I am just trying to give you an example

.jsp FILE

<% String filename ="nameofFile.txt"; %>
<a href="download?filename=<%= filename %>" ></a>

SERVLET CODE

String filename = (String)request.getParameter("filename");
BufferedReader fir= new BufferedReader(new FileReader(new FileInputStream(filename))); 
PrintWriter out = response.getWriter();
while(fir.ready())
out.println(fir.readLine())

I think you are getting blank page because you are not sending any response back to the client, here out.println will actually send response back to the client

Always encode the URL. In JSP try with <c:url> JSTL Tag.

For example

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
...
<a href='<c:url value="/jsp/index.htm"/>'>TEST</a>

Read more..

Note: Use JSTL and EL instead of Scriplets.

It is possible but it looks like your browser clears parameters after ?... in action="..." attribute. In that case try passing it via <input type="hidden" .../> like

<form action="sendFileToServlet" method="get">
    <input type="hidden" name="filename" value="<%=filename%>"/>
    <input type="submit" value="Send" />
</form> 

This way form should add them to URL as ?filename= value of <%=filename%> .

Yes you can send as like trough jsp.

i just tested now it's working fine the blank page is coming because of other statements written in your servlet code so make sure servlet code is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM