[英]How to redirect the response of a servlet into the same jsp page from where we got the request
如何將servlet的響應重定向到從中獲取請求的同一個jsp頁面。 假設我在jsp頁面http://localhost:8080/Example/status.jsp
上有一個名為status的選項卡。 現在,當我發送請求並獲得響應時,它應該在同一頁面上顯示響應,即。 它應該顯示響應
http://localhost:8080/Example/status.
JSP。 但這顯示了我的回應
http://localhost:8080/Example/Status
,其中狀態是web.xml文件中的url-pattern。 請任何幫助表示贊賞。 下面是我的代碼。 如何在status.jsp中獲得響應。
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws
IOException {
try{
String showstatus =req.getParameter("showstatus");
PrintWriter out = res.getWriter();
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("C:\\tools\\server\\util stat -a" );
BufferedReader stdInput = new BufferedReader(new
InputStreamReader(pr.getInputStream()));
BufferedReader input = new BufferedReader(stdInput);
String stat = "";
while((stat = input.readLine()) != null){
out.println(stat);
}
}
catch (Throwable t)
{
t.printStackTrace();
}
finally {
} }
JSP代碼:
<div id= "status" style="display:none;">
<FORM action="status" METHOD="POST">
<input type=submit name=showstatus
id=txtSubmit value=Status />
</FORM>
</div>
WEB.XML:
<servlet>
<servlet-name>Status</servlet-name>
<servlet-class>com.emc.clp.license.Status</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Status</servlet-name>
<url-pattern>/status</url-pattern>
</servlet-mapping>
在您的servlet中,不要將util
的輸出直接打印到響應中,而是將其保存在內存中並將其傳遞給jsp:
String stat;
StringBuffer utilOutput = new StringBuffer();
while((stat = input.readLine()) != null){
utilOutput.append(stat + "\n");
}
req.setAttribute("utilOutput", utilOutput.toString());
req.getRequestDispatcher("/Example/status.jsp").forward(req, res);
在您的jsp中,我假設您有一個div或想要查看輸出的內容:
<div id= "status" style="display:none;">
<form action="/status" method="POST">
<input type="submit" name="showstatus" id="txtSubmit" value="Status" />
</form>
</div>
<div id="result">
<pre>
${requestScope.utilOutput}
</pre>
</div>
請注意,我在表單操作中添加了正斜杠。 如果您的用戶是從/Example/status.jsp
提交表單,則相對路徑會將帖子發送到/Example/status
,但是您的Servlet僅處理對/status
請求。
您的請求對象req
具有屬性映射,您可以在請求上使用setAttribute()方法將任何相關對象放入其中。 請求分派器將您的請求和響應對象轉發到另一個資源(您的jsp)上進行處理。 jsp可以使用上述EL表示法按名稱訪問這些值。
如果采用這種方式,內聯樣式中的display:none
始終會阻止該表單在頁面上顯示。 我認為最明顯的顯示方式是在客戶端使用javascript。 單擊選項卡時,您需要更改顯示值。 您沒有提及選項卡元素是什么,但可以說它們是div。 您可以編寫一個javascript函數來加載表單,甚至可以內聯完成所有操作:
<div id="mytab" onclick="document.getElementById('status').style.display = 'block';">Load the form</div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.