E_I*_*CLT 5 java cookies servlets class http
我对servlet很新,目前我正在努力添加cookie.我相信这是我采用的模块化方法的结果,我构建了一个头实用程序类,它只是将所有头信息插入到servlet中,所以我想采用相同的方法添加cookie.
我还有一个信用验证器类,除了用户名和密码,验证它,然后返回有效/无效的响应.我认为这就是问题所在.在将用户名和密码传递给凭证验证器的登录表单中,我将表单操作指向凭证servlet,将表单方法作为帖子.
如果我想从表单中将值发送到另一个servlet,或者这样做,这样做会提供一个问题吗?
对于学校来说,这个项目的目标是使用servlet严格创建一个简单的网站,然后我们可以使用JSP来减轻痛苦.
我应该考虑另一种方法吗?当使用表单操作和方法时,是否可以使这些类在表单上执行各种功能?
感谢您的任何帮助和指导.
最好的E
Joh*_*ohn 14
您可以将请求发送到servlet,然后在需要时将请求转发到另一个servlet.
在您的情况下,验证后,您可以将结果存储在属性中,然后将控制权转移到另一个servlet.(如果那是你想做的)
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/urlToServlet");
dispatcher.forward(request, response);
Run Code Online (Sandbox Code Playgroud)
这就是如何处理cookie.
创建和发送cookie
Cookie userCookie = new Cookie("name", "value");
userCookie.setMaxAge(60*60*24*365); //Store cookie for 1 year
response.addCookie(userCookie);
Run Code Online (Sandbox Code Playgroud)
从客户端读取cookie
String cookieName = "somecookie";
Cookie[] cookies = request.getCookies();
if (cookies != null)
{
for(int i=0; i<cookies.length; i++)
{
Cookie cookie = cookies[i];
if (cookieName.equals(cookie.getName()))
{
doSomethingWith(cookie.getValue());
}
}
}
else
{
//do something else for firsttime visitors
}
Run Code Online (Sandbox Code Playgroud)
您是否使用Cookie进行会话跟踪?如果是,那么使用HttpSession.使用HttpSession,不需要直接使用cookie进行会话跟踪.
例如,在一个简单的登录页面中,这就是您所做的
HttpSession session = request.getSession();
session.setAttribute("username",username);
In other pages,
if(session.getAttribute("username")==null)
{
//forward to login page.
}
Run Code Online (Sandbox Code Playgroud)
您需要在 HttpServletResponse 中使用 addCookie。我建议您准备好 java 文档,以便您可以了解 servlet 可以使用哪些内容。http://docs.oracle.com/javaee/6/api/javax/servlet/http/HttpServletResponse.html#addCookie(javax.servlet.http.Cookie )
| 归档时间: |
|
| 查看次数: |
30134 次 |
| 最近记录: |