Return to Tech/java

Apache Tomcat - JSP basic states

set cookie
Set Cookie sample
file:testSetCookie.jsp
<%@ page language="java" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page pageEncoding="UTF-8" >

<!DOCTYPE html>
<html>
<body>
<%
    Cookie ck = new Cookie("cookparam1", "cookval1");
    ck.setMaxAge(120); // 120 seconds
    ck.setPath("/");
    ck.setDomain("localhost");
    ck.setSecure(false);

    response.addCookie(ck);
%>
Done
</body> </html>

get cookie
Get Cookie sample
file:testGetCookie.jsp
<%@ page language="java" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page pageEncoding="UTF-8" %>

<!DOCTYPE html>
<html>
    <body>
<%
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for ( Cookie cookie:cookies) {
%>
        <table border="1">
            <tr>
                <th>Settings</th>
                <th>Value</th>
            </tr>

            <tr>
                <td>CookieName</td>
                <td><%= cookie.getName() %></td>
            </tr>

            <tr>
                <td>CookieValue</td>
                <td><%= cookie.getValue() %></td>
            </tr>

            <tr>
                <td>Expire</td>
                <td><%= cookie.getMaxAge() %></td>
            </tr>
        </table>
<%                
        }
    }
%>
    </body>
</html>


set session
Set(Get) session sample

Session Scope : 1 client
file:testSetSession.jsp
<%@ page language="java" %>
<%@ page contentType="text/html; charset=UTF-8" %>
<%@ page pageEncoding="UTF-8" %>

<!DOCTYPE html>
<html>
    <body>
<%
    Integer count = (Integer)session.getAttribute("count");
    if (count == null) count = 0;

    count++;

    session.setAttribute("pagecounter01", count);
%>

PageCounter : <%= session.getAttribute("pagecounter01") %>
    </body>
</html>

Application Attribute
Session Scope : All Clients(1 Application)
file:testSetSession.jsp
<%= application.getAttribute("hogeAttribute") %>

Return to Tech/java