JSP-cooikeとsession
需要:cooikeとsessionでそれぞれアナログログインを行います(最初のページにユーザー名を入力し、後ろのページにユーザー名を表示します).
session:
MainServlet.java
cookie:
MainServlet.java
index.jsp
session:
MainServlet.java
package web;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class MainServlet extends HttpServlet {
@Override
protected void service(
HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String path = req.getServletPath();
if("/toLogin.do".equals(path)) {
toLogin(req,res);
} else if("/login.do".equals(path)) {
login(req,res);
}
}
private void toLogin(
HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
req.getRequestDispatcher("WEB-INF/login.jsp")
.forward(req, res);
}
private void login(
HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
HttpSession hs = req.getSession();
hs.setAttribute("userCode", req.getParameter("userCode"));
req.getRequestDispatcher("WEB-INF/index.jsp")
.forward(req, res);
}
}
login.jsp
index.jsp
My JSP 'index.jsp' starting page
!${userCode }。
cookie:
MainServlet.java
package web;
import java.io.IOException;
import java.net.URLEncoder;
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 MainServlet extends HttpServlet {
@Override
protected void service(
HttpServletRequest req,
HttpServletResponse res)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String path = req.getServletPath();
if("/toLogin.do".equals(path)) {
toLogin(req,res);
} else if("/login.do".equals(path)) {
login(req,res);
}
}
private void toLogin(
HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
req.getRequestDispatcher("WEB-INF/login.jsp")
.forward(req, res);
}
private void login(
HttpServletRequest req,
HttpServletResponse res) throws ServletException, IOException {
Cookie c = new Cookie("userCode",
URLEncoder.encode(req.getParameter("userCode"),"utf-8"));
res.addCookie(c); // response cookie, cookie
//(session )
req.getRequestDispatcher("WEB-INF/index.jsp")
.forward(req, res);
}
}
login.jspは上と同じですindex.jsp
My JSP 'index.jsp' starting page
!${cookie.userCode.value }。