无法从Servlet发送整数到JSP。
@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MyServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Method Get in MyServlet");
int Gconta = Integer.parseInt(request.getParameter("Gcont"));
Gconta = Gconta + 1;
System.out.println(Gconta);
HttpSession session = request.getSession();
session.setAttribute("NGconta", Gconta);
response.sendRedirect("cabecalhost.jsp");
response.getWriter().append("Served at: ").append(request.getContextPath());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
[JSP页面
<body>
<h3>O Resultado NGconta:</h3>
<%String Getnumbx = request.getParameter("NGconta"); %>
<%= Getnumbx %>
<%String Getnumb = (String) request.getAttribute("NGconta");%>
<% out.println("Your Result is "+ Getnumb); %>
&{NGconta};
</body>
尝试一下
@WebServlet("/MyServlet")
public class MyServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public MyServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Method Get in MyServlet");
int Gconta = Integer.parseInt(request.getParameter("Gcont"));
Gconta = Gconta + 1;
System.out.println(Gconta);
HttpSession session = request.getSession();
session.setAttribute("NGconta", Gconta);
RequestDispatcher rd =
request.getRequestDispatcher("cabecalhost.jsp");
rd.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
<body>
<%String Getnumbx = (String)request.getSession().getAttribute("NGconta"); %>
<%= Getnumbx %>
</body>
替换
response.sendRedirect("cabecalhost.jsp");
with
request.getRequestDispatcher("cabecalhost.jsp").forward(request, response);
以及您的JSP中的代码与
<body>
<h3>O Resultado NGconta:</h3>
<%String Getnumbx = session.getAttribute("NGconta").toString(); %>
<%= Getnumbx %>
<%String Getnumb = session.getAttribute("NGconta").toString();%>
<% out.println("Your Result is "+ Getnumb); %>
${NGconta};
</body>
说明: redirect
指示服务器创建新请求,因此,当request
转发现有forward
的内容时,现有request
的内容将不会发送到新URL ]更改为新网址。检查类似的post,以更好地理解。