使用HttpSession对象管理会话写一个代码并运行
时间: 2024-03-02 14:50:00 浏览: 39
好的,以下是一个简单的使用HttpSession对象管理会话的Java代码示例:
```java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionExample extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// 获取当前会话的HttpSession对象
HttpSession session = request.getSession(true);
// 设置会话属性
session.setAttribute("username", "JohnDoe");
session.setAttribute("age", 30);
// 获取会话属性
String username = (String) session.getAttribute("username");
int age = (Integer) session.getAttribute("age");
// 输出会话属性
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Session Example</title></head>");
out.println("<body>");
out.println("<h1>Session Example</h1>");
out.println("<p>Username: " + username + "</p>");
out.println("<p>Age: " + age + "</p>");
out.println("</body>");
out.println("</html>");
}
}
```
这个例子展示了如何获取当前会话的HttpSession对象,设置和获取会话属性,并将会话属性输出到HTML页面中。请注意,这个例子假设你已经有一个Servlet容器(如Tomcat)来运行这个Servlet。你需要将这个Servlet打包成一个WAR文件并部署到Servlet容器中,然后访问这个Servlet的URL来运行它。
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)