简体   繁体   English

是否可以从 Spring 中的脚本调用 controller 方法

[英]Is it possible to call controller method from a scriptlet in Spring

I need to implement a call to a method that I have in my controller. But I want to call this method from a scriptlet and I don't know how to do it.我需要调用我的 controller 中的一个方法。但是我想从一个 scriptlet 中调用这个方法,但我不知道该怎么做。 I am trying to export data that I get from the server to CSV.我正在尝试将从服务器获取的数据导出到 CSV。

This is the scriptlet that I have so far:这是我到目前为止的脚本:

<%  
String csvDataIn = request.getParameter("exportCSVParam");
String csvFileName = request.getParameter("exportCSVFileName");
if (csvFileName == null || csvFileName == "") csvFileName = "export.csv";

String strHeader = "attachment; filename=" + csvFileName;
String contentType = "application/octet-stream";
response.setContentType(contentType);
response.addHeader("content-disposition",strHeader);

ServletOutputStream ostr = response.getOutputStream();    
String data=csvDataIn;//DATA GOES HERE;
ostr.write(data.getBytes("ISO-8859-1"));
ostr.flush();
ostr.close();
%>

Assume that I want to call a method getDataAsCsv() that I have in my controller that returns a String with the CSV data that I want to print in that file.假设我想调用我的 controller 中的方法getDataAsCsv() ,它返回一个字符串,其中包含我想在该文件中打印的 CSV 数据。 Lines 1 and 2 ( csvDataIn , csvFileName ) should be deleted since I am not going to send parameters to this jsp. How do you do that?.第 1 行和第 2 行( csvDataIncsvFileName )应该被删除,因为我不会向这个 jsp 发送参数。你是怎么做到的? How do you bind the controller bean with this scriptlet.您如何将 controller bean 与此 scriptlet 绑定。

I am new to spring and I am still learning about this.我是 spring 的新手,我还在学习这个。 Probably the solution is very simple but I am stuck with this.解决方案可能非常简单,但我坚持这一点。

You can't, because you shouldn't.你不能,因为你不应该。 All this code should go in the controller. controller 中的所有此代码应为 go。

(technically, you can have a JSTL function and call it, or simply call a static method, or even get the controller with WebApplicationContextUtils.getRequiredWebApplicationContext(..).getBean(..) , but all these will be ugly) (从技术上讲,您可以拥有一个 JSTL function 并调用它,或者简单地调用一个 static 方法,或者甚至通过WebApplicationContextUtils.getRequiredWebApplicationContext(..).getBean(..)获得 controller ,但所有这些都会很难看)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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