在 JSP 表单上调用 java 类方法提交并传递 File 对象参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11880761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
invoke java class method on JSP form submit and pass File object parameter
提问by DarkKnightFan
I wish to call a java class method from JSP whenever I submit my form. My JSP file will have a file tag. User will browse a file from his local machine. And click on Submit. This file object should be available in a Java class where I will have my business logic.
我希望在提交表单时从 JSP 调用 java 类方法。我的 JSP 文件将有一个文件标记。用户将从他的本地机器浏览一个文件。然后点击提交。这个文件对象应该在我将拥有我的业务逻辑的 Java 类中可用。
Is this possible without using struts?
这可能不使用支柱吗?
<s:form action="**direct call to Action method here**" method="post" enctype="multipart/form-data" >
<s:file name="userImage" label="User Image" /><s:submit />
Please help me with the ways of doing this.
请帮助我了解这样做的方法。
thanks.
谢谢。
采纳答案by Kapelchik
Value of actionattribute should be URL. The given URL specifies an address to which the data from the form should be sent when a form is submitted.
action属性的值应该是URL。给定的 URL 指定了提交表单时表单数据应发送到的地址。
Use following html code in your jsp page:
在您的 jsp 页面中使用以下 html 代码:
<form action="uploadFile" method="post"
enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Upload file" />
Define mapping of servlet that responsible for loading a file in your web.xml
file:
定义负责在文件中加载文件的 servlet 的映射web.xml
:
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>package.UploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/uploadFile</url-pattern>
</servlet-mapping>
And implement the method doPost in given servlet in which call the method from your business logic:
并在给定的 servlet 中实现方法 doPost,其中从您的业务逻辑调用该方法:
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
yourMethod();
}
You can specify any JSP page in attribute action
if you are using in your application only JSP:
action
如果您在应用程序中仅使用JSP,则可以在属性中指定任何 JSP 页面:
<form action="upload_file.jsp" method="post" enctype="multipart/form-data">
This page will process a upload-file request in this case.
在这种情况下,此页面将处理上传文件请求。