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>