Session
sessin是在服务器存一个东西,然后客户端会拿到一个ID,用这个ID去取东西。
每个人都有一个独特的ID
建一个SessionDemo01
@WebServlet("/s1")
public class SessionDemo01 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=utf-8");
//得到session
HttpSession session = req.getSession();
//在session里面存东西
session.setAttribute("name",new Person("亲将",1));
//获取sessionid
String id = session.getId();
//判断session是不是新创建的
if(session.isNew()){
resp.getWriter().write("session创建成功,ID:"+id);
}else{
resp.getWriter().write("session以及在服务器中存在了,ID:"+id);
resp.sendRedirect("/success.jsp");
}
}
session这节课的重要代码
//得到session
HttpSession session = req.getSession();
//在session里面存东西
session.setAttribute("name",new Person("亲将",1));
//获取sessionid
String id = session.getId();
用封装的方式获取SessionID
public class Person {
private String name;
private int age;
public Person(){
}
public Person (String name,int age){
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name){
this.name = name;
}
public int getAge(){
return age;
}
public void setAgea(int age){
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
在SessioDemo01中new一个person

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//解决乱码问提i
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//得到session
HttpSession session = request.getSession();
//得到name
Person person = (Person) session.getAttribute("name");
//在页面看到自己写的东西
response.getWriter().print(person.getName() + " " + person.getAge());
}
}
浙公网安备 33010602011771号