简体   繁体   中英

I want to call servlet from jsp page

This is my jsp code.In the form tag the action attribute same .jsp page is needed. & how can i call FileUploadExample servlet from this jsp.

<form id="beneficiary_sales_details" name="beneficiary_sales_details"
action="beneficiary_sales_details.jsp" autocomplete="off"  method="post">


     <input type="file" id="datafile" name="datafile" size="40" />
      <input type="button" id="cmdUpload" value="Upload" onclick = "unloadEvt();"  />

This is the javascript i used to call servlet

   function unloadEvt() {

    document.location.href='/FileUploadExample';

   }

This is the servlet to call.But I am unable to call this servlet from beneficiary_sales_details.jsp.Please suggest me any other option to call servlet from jsp

  public class FileUploadExample extends HttpServlet {  
   @Override  
   protected void doPost(HttpServletRequest request, HttpServletResponse response)  
      throws ServletException, IOException {  
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);  
     response.setContentType("text/html");  
      PrintWriter out = response.getWriter();  

      System.out.println("In fileupload servlet");

    if (isMultipart) {  
       // Create a factory for disk-based file items  
       FileItemFactory factory = new DiskFileItemFactory();  
       // Create a new file upload handler  
       ServletFileUpload upload = new ServletFileUpload(factory);  
      try {  
         // Parse the request  
         List /* FileItem */ items = upload.parseRequest(request);  
        Iterator iterator = items.iterator();  
        while (iterator.hasNext()) {  
          FileItem item = (FileItem) iterator.next();  
          if (!item.isFormField())  
           {  
            String fileName = item.getName();      
            String root = getServletContext().getRealPath("/");  
            File path = new File(root + "/uploads");  
            if (!path.exists())  
             {  
              boolean status = path.mkdirs();  
            }  
            File uploadedFile = new File(path + "/" + fileName);  
            System.out.println(uploadedFile.getAbsolutePath());  
            System.out.println(uploadedFile.getTotalSpace());
        //    bytesray = uploadedFile.length();
            byte[] b = new byte[(int)uploadedFile.length()];
            for (int i = 0; i < b.length; i++) {
           // System.out.print(b[i]);
            }
            String str = b.toString();
            System.out.println(" byte array in string---"+str);
            out.println("<h1>"+str+"</h1>");
             if(fileName!="")  
            item.write(uploadedFile);  
             else  
               out.println("file not found");  
             out.println("<h1>File Uploaded Successfully....:-)</h1>");  
          }  
           else  
           {  
             String abc = item.getString();  
             out.println("<br><br><h1>"+abc+"</h1><br><br>");  
           }  
        }  
      } catch (FileUploadException e) {  
            out.println(e);  
      } catch (Exception e) {  
            out.println(e);  
      }  
    }  
     else  
     {  
       out.println("Not Multipart");  
     }  
  }  

}

You could use <jsp:include> for this.

<jsp:include page="/servletURL" />

It's however usually the other way round. You call the servlet which in turn forwards to the JSP to display the results. Create a Servlet which does something like following in doGet() method.

request.setAttribute("result", "This is the result of the servlet call");
request.getRequestDispatcher("/WEB-INF/result.jsp").forward(request, response);

and in /WEB-INF/result.jsp

 <p>The result is ${result}</p>

Now call the Servlet by the URL which matches its <url-pattern> in web.xml , eg

THIS

If your actual question is "How to submit a form to a servlet?" then you just have to specify the servlet URL in the HTML form action.

<form action="servletURL" method="post">

Its doPost() method will then be called.

See also: Servlet Info Page

Oracle Doc

Calling a servlet requires the following steps.

  1. Configure the application so it knows here to find the servlet.

You might need to add a web.xml file to your project. If you are using netbeans go to new file--web--standard deployment descriptor(web.xml). Then you must add the servlet information to the web.xml file. This will tell the application where to look for the class.

Here is an exmaple of servlet config in a web.xml file.

<servlet>
        <servlet-name>MyServlet</servlet-name>
        <servlet-class>mypackage.MyServlet</servlet-class>
    </servlet>
<servlet-mapping>
        <servlet-name>MyServlet</servlet-name>
        <url-pattern>/MyServlet</url-pattern>
    </servlet-mapping>

2.Call the servlet from the jsp. In your case through an input component with an 'action' in the call.

<form action="MyServlet?action=doThis" method="post">

3 In the servlet process the action.

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

if (action.equalsIgnoreCase("doThis"){
do this;
forward = "originaljsp.jsp";
}
 RequestDispatcher view = request.getRequestDispatcher(forward);
        view.forward(request, response);

This will result in the application calling the servlet and returning you to the original immediately. You will be able to call the functions you want and you won't even notice.

You can do something like this in 2 steps

1.Change the action attribute to the servlet location

<form id="beneficiary_sales_details" name="beneficiary_sales_details" action="/FileUploadExample" autocomplete="off" method="post">

2.Just change the button type to submit <input type="submit" value="Upload">

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