HttpSession session = requset.getSession();
void setAttribute(String name, Object value)
Object getAttribute(String name)
void invalidate()
void setMaxInactivelnterval(int interval)
boolean isNew()
Long getCreationTime()
Long getLashAccessedTime()
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>calc</title>
</head>
<body>
<form action="calc" method="post">
<div>
<input type="text" name="v">
</div>
<div>
<input type="submit" name="operator" value="+">
<input type="submit" name="operator" value="-">
<input type="submit" name="operator" value="=">
</div>
</form>
</body>
</html>
package com.song.pra;
import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class calc
*/
@WebServlet("/calc")
public class calc extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext app = getServletContext();
HttpSession session = request.getSession();
String v_ = request.getParameter("v");
String op = request.getParameter("operator");
int v = 0;
if(!v_.equals("")) {
v = Integer.parseInt(v_);
}
int result = 0;
if(op.equals("=")) {
// int x = (Integer)app.getAttribute("value");
int x = (Integer)session.getAttribute("value");
int y = v;
// String operator = (String) app.getAttribute("operator");
String operator = (String) session.getAttribute("operator");
if(operator.equals("+")) {
result = x + y;
}else {
result = x - y;
}
response.getWriter().printf("result is %d", result);
} else {
// app.setAttribute("value", v);
// app.setAttribute("operator", op);
session.setAttribute("value", v);
session.setAttribute("operator", op);
}
}
}
Servlet / JSP