I’m wondering is possible to integrate custom servlet logic with .jsp template view. For example I have the following servlet:
public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = "Mark";
}
}
and I want to place name variable inside jsp file(new.jsp) like:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>New</title>
</head>
<body>
<%= name %>
</body>
</html>
My web.xml:
<servlet>
<servlet-name>MyServlet</servlet-name>
<jsp-file>/new.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/new</url-pattern>
</servlet-mapping>
I don’t want to put name in request.
Any help?
UPDATE
Great thanks, but I’m still having a trouble.
Firstly, I updated my servlet:
public class MyServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = "Mark";
request.setAttribute("name", name);
request.getRequestDispatcher("/WEB-INF/new.jsp").forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name = "Mark";
request.setAttribute("name", name);
request.getRequestDispatcher("/WEB-INF/new.jsp").forward(request, response);
}
}
I also changed my view:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>New</title>
</head>
<body>
${name}
</body>
</html>
But when I use ${name} there’s nothing displayed. I thought that I should import any jstl, but unfortunately if I use <%= request.getAttribute("name") %> I’m getting null.
UPDATE 2
Finally solved! It was my fault, I forgot set
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.example.MyServlet</servlet-class>
</servlet>
You need to implement the
doGet()method instead. A normal HTTP request (clicking a link, a bookmark or entering the URL straight in browser address bar) defaults toGETmethod.In order to make objects available in JSP in a preprocessing servlet, you need to set it as an attribute in request, session or application scope. Finally you need to forward the request/response to the JSP so that it can be displayed.
If you fix the servlet mapping as follows
then you can just invoke the servlet by http://localhost:8080/contextname/new. In the forwarded JSP you can access the
namejust by ELNote that the JSP is placed in
/WEB-INFfolder in order to avoid direct access without the preprocessing servlet being called by entering the JSP URL in browser address bar instead.See also: