RequestDispatcher在servet的URL上打印输出,而不是重定向到JSP

时间:2016-04-27 11:34:23

标签: java jsp servlets

此代码段来自我的CustomerController servlet。

@WebServlet("/CustomerController")
/*
.
.
.
*/

if(request.getParameter("operation").equalsIgnoreCase("search-customer")) {

            CustomerDAO customerDAO = new CustomerDAO();
            Customer customer = customerDAO.searchCustomer(Integer.parseInt(request.getParameter("customer_id")));
            request.setAttribute("Customer-Result", customer);
            RequestDispatcher requestDispatcher;
            requestDispatcher = request.getRequestDispatcher("/search-results.jsp");
            requestDispatcher.forward(request, response);
}


不是重定向到search-results.jsp以打印搜索结果,而是将结果打印在servlet(CustomerController)URL本身上。

请参阅图像。 CustomerController


search-results.jsp

<%@page import="com.servlet.Customer"%>
<!DOCTYPE html>
<html>

    <body>


    Customer Found : 

    <%

    Customer customer = (Customer) request.getAttribute("Customer-Result");
    out.println(customer.getCustomer_name());

    %>


    </body>


</html>

有什么问题?

2 个答案:

答案 0 :(得分:0)

@Maven Maverick。希望这可以帮到你。

如果您希望网址中的 search-results.jsp WEB-INF 文件夹中删除该文件,并将其部署在 WebContent 下文件夹(IDE:Eclipse的)。因为WEB-INF是受保护的文件夹,所以不能通过用户调用或URL直接访问它。为此,您必须将该jsp文件移动到WebContent文件夹下,而不是RequestDispatcher使用private void takeScreenshot(){ try { //TextView I could screenshot instead of the whole screen: //TextView v1 = (TextView)findViewById(R.id.tv_code); Bitmap bitmap = null; Bitmap bitmap1 = null; View v1 = getWindow().getDecorView().getRootView(); v1.setDrawingCacheEnabled(true); bitmap = Bitmap.createBitmap(v1.getDrawingCache()); try { if (bitmap != null) bitmap1 = Bitmap.createBitmap(bitmap, 0, 0, v1.getWidth(), v1.getHeight()); } catch (OutOfMemoryError e) { e.printStackTrace(); } v1.setDrawingCacheEnabled(false); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bitmap1.compress(Bitmap.CompressFormat.JPEG, 40, bytes); File f = new File(Environment.getExternalStorageDirectory() + File.separator + "test.jpg"); FileOutputStream fo = new FileOutputStream(f); fo.write(bytes.toByteArray()); fo.flush(); fo.close(); MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), f.getName(), f.getName()); Log.d("debug", "Screenshot saved to gallery"); Toast.makeText(HuntActivity.this,"Code Saved!",Toast.LENGTH_LONG).show(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }

评论如果这适合你或不适合..因为对我有用。

希望它适合你:)

答案 1 :(得分:0)

你不想要那个!

浏览器中显示的URL是浏览器发送的最后一个查询的URL。在您的情况下,您向/CustomerController和服务器端发送查询,servlet将请求转发给JSP以显示结果。该转发是Web应用程序中的内部细节,您没有理由向客户端显示该内容。

此外,您应该不让客户知道这一点。常见的用法是将servlet内部使用的JSP(通过包含或转发)精确地放在WEB-INF文件夹下,以避免来自客户端的直接查询。请求浏览器显示无法查询的URL有什么意义?这里有趣的部分是,如果您稍后从JSP更改为模板引擎(如velocity,,因为该部分从客户端隐藏),可见界面中不会发生任何变化

我不确定这是预期的答案,但您真的应该想知道为什么要在客户端浏览器中显示内部URL。因为这将要求您将JSP放在受保护的WEB-INF文件夹之外,这绝对是一种不好的做法。