简体   繁体   中英

Pass model from servlet to JSP page

I am uploading documents to the server by using servlet. After successfully uploading i need to show additional information to the user like which document uploaded with which id. For this i am putting ID and File name in modelMap i trying to send it on JSP page.

For this i am using this code:-

 ModelMap model = new ModelMap();
 for(FileItem item : files) {
        model.put(id, fileName);
 }
 req.setAttribute("message", model);
 RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/success.do");
 dispatcher.forward(req, resp);

On JSP page

<%
    if(request.getAttribute("message")!=null){
    String value = request.getAttribute("message").toString();
    if(value!=null)
  {
    value = value.substring(1, value.length()-1);           //remove curly brackets
    String[] keyValuePairs = value.split(",");              //split the string to creat key-value pairs
    for(String pair : keyValuePairs)                        //iterate over the pairs
        {
        String[] entry = pair.split("=");                   //split the pairs to get key and value 
            out.println("<font color='red'>"+entry[1].trim()+"</font> indexed with id <font color='red'>"+entry[0].trim()+"</font><br/>");
       }
  }

     System.out.println(request.getAttribute("message"));
    }
%>

My problem is in this scene all the things are working except one. When i upload the document message is showing but my URL remains the uploaded servlet URL. So when a user hits on it( GET Request) servlet throw an exception for uploading file.

If i use

resp.sendRedirect("../success.do");

Then i cant pass parameters in it. So how i can achieve this task?

My file upload servlet is

mySite/upload/servlet

and success page is

mySite/success.do 

Can't really post this a comment hence adding it as an answer.

If your main motive is to be able to upload file and hide the servlet url, then how about using AJAX for file upload ?

Here is sample snippet

JSP :


<script type="text/javascript">
function performAjaxSubmit() {
    var sampleText = document.getElementById("sampleText").value;
    var sampleFile = document.getElementById("sampleFile").files[0];
    var formdata = new FormData();
    formdata.append("sampleText", sampleText);
    formdata.append("sampleFile", sampleFile);
    var xhr = new XMLHttpRequest();       
    xhr.open("POST","/fileUploadTester/FileUploader", true);
    xhr.send(formdata);
    xhr.onload = function(e) {
        if (this.status == 200) {
           alert(this.responseText);
        }
    };                 
}   

This is taken from here http://www.technicaladvices.com/2011/12/10/ajax-file-upload-to-a-java-servlet-in-html5/

And of-course there are plenty of examples using JSP + JQUERY

On servlet side you can always use something like

PrintWriter print = response.getWriter();

print.println("");

to print a simple output

Ok, so you have to pass an arbitrary large amount of information through a redirect. Some frameworks invented what they call the flash for that usage. Under the hood, it means :

  • save the information in the session under a well known attribute name (or pattern) before redirecting
  • in the redirected page, look whether a flash attribute exists in session, and if there is one, put it in request and remove it from session

Pros : it allows you to simulate the passage of request attributes through a redirect

Caveats : it does not work very well with AJAX calls in the middle because the flash is normally intended for next request, but normally it works fine for redirects.

Possible implementations :

  • if you use it in one single place in your app, just use a dedicated attribute name in session, set it in the servlet doing the redirect, and get it in the servlet (or JSP) where you redirect
  • if you intend to use it throughout your app, you should considere to use a filter that processes this (these) flash attribute(s), and writing a method that puts attributes in the flash and sends the redirect response to make sure that it will be coherent throughout the whole app and easy to maintain.

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