我当前正在使用最新版本的eclipse和tomcat服务器(v8.5)
类型不匹配错误正在“ Cookie cookie [] = req.getCookies();”的SqServlets.java文件中生成。我的代码行。如果解决了,那么我将添加for循环并获取“ k”值的cookie,但该行中的第一个错误将被清除。
Addservlets.java
package servlets;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
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;
public class Addservlet extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException, IOException {
int i= Integer.parseInt(req.getParameter("num1"));
int j= Integer.parseInt(req.getParameter("num2"));
int k=i+j;
String str=Integer.toString(k);
Cookie cookie=new Cookie("k",str);
res.addCookie(cookie);
res.sendRedirect("sq");
}
}
SqServlets.java
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.tomcat.util.http.parser.Cookie;
public class SqServlets extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res) throws IOException {
int k=0;
Cookie cookie[]= req.getCookies();
k=k*k;
PrintWriter out=res.getWriter();
out.print("square value is = "+k);
}
}
我认为错误是在导入中:
import org.apache.tomcat.util.http.parser.Cookie;
从HttpServletRequest的文档中,我们发现方法getCookies
返回与您的声明不兼容的javax.servlet.http.Cookie
。
因此,请使用以下方式修复导入:
import javax.servlet.http.Cookie;
然后使用相对API查找并获取Cookie的值。