判断是否存在cookie名字为张三 //如果用户登陆后返回success.html //如果用户没有登陆 返回登陆页面
时间: 2023-10-09 14:11:13 浏览: 79
以下是一个简单的 Java Servlet 实现判断是否存在名为 `username` 的 Cookie,如果存在则重定向到 `success.html` 页面,否则重定向到登录页面:
```java
@WebServlet("/")
public class LoginServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] cookies = request.getCookies();
boolean hasUsernameCookie = false;
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("username")) {
hasUsernameCookie = true;
break;
}
}
}
if (hasUsernameCookie) {
response.sendRedirect(request.getContextPath() + "/success.html");
} else {
response.sendRedirect(request.getContextPath() + "/login.html");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
```
在这个示例中,`doGet` 方法获取所有的 Cookie,并检查是否存在名为 `username` 的 Cookie。如果存在,则重定向到 `success.html` 页面,否则重定向到 `login.html` 页面。
注意,需要在 `web.xml` 文件中配置默认的欢迎页面:
```xml
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
```
这里将默认欢迎页面设置为 `index.html`,也就是登录页面。
如果用户已经登录并且存在名为 `username` 的 Cookie,访问默认欢迎页面时会自动重定向到 `success.html` 页面。如果用户没有登录或者名为 `username` 的 Cookie 已经过期,会自动重定向到登录页面。