我们接受了将信件转换为电话号码的练习。我有两个servlet,一个用于读取表单中的输入并将信息存储在会话和cookie中(按照我们的教授的指示),另一个servlet的工作是输出存储在会话对象和cookie中的值。问题是我每次输入的内容都不会立即显示出来。
示例:
输入:0922-ABCDEFG |输出:-2223334
输入2:0912-ABCDEFG |产量:0922-2223334
输入3:-ABCDEFG |产量:0912-2223334
输入4:0917-ABCDEFG |输出: - 2223334
这是两个servlet的代码:
package com.telco.process;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class ConvertServlet
*/
@WebServlet("/Convert")
public class ConvertServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private String num;
private String telco;
private HttpSession session;
private Cookie cTelco;
private RequestDispatcher rd;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String convertedNum = "";
session = request.getSession();
num = request.getParameter("number");
telco = request.getParameter("telco");
rd = request.getRequestDispatcher("Display");
if (num != null || num != "")
{
for (byte i = 0; i < num.length(); i++)
{
switch(num.charAt(i))
{
case 'A':
case 'B':
case 'C': convertedNum += "2"; break;
case 'D':
case 'E':
case 'F': convertedNum += "3"; break;
case 'G':
case 'H':
case 'I': convertedNum += "4"; break;
case 'J':
case 'K':
case 'L': convertedNum += "5"; break;
case 'M':
case 'N':
case 'O': convertedNum += "6"; break;
case 'P':
case 'Q':
case 'R':
case 'S': convertedNum += "7"; break;
case 'T':
case 'U':
case 'V': convertedNum += "8"; break;
case 'W':
case 'X':
case 'Y':
case 'Z': convertedNum += "9"; break;
}
}
session.setAttribute("number", convertedNum);
cTelco = new Cookie("telco", telco);
response.addCookie(cTelco);
}
rd.forward(request, response);
}
}
Servlet 2:
package com.telco.process;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/Display")
public class DisplayNumber extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
Cookie ck[] = request.getCookies();
pw.println("The converted number is " + ck[1].getValue() + "-" + request.getSession(false).getAttribute("number"));
}
}
答案 0 :(得分:0)
您应该从浏览器方面进行调查:查看发送的HTTP标头。
此外Cookie ck[] = request.getCookies()
是一个数组,但您只显示第二个元素ck[1]