一共有四个页面:getattribute1,2,3。 getattribute为输入数字页面,2为结果页。3计算出和,4计算乘积。
int value=(Integer)request.getAttribute(“mynum”);
getattribute可以直接强制转换得到整形数。而getparameter得到的是字符串,必须转换。
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="getattribute11.jsp"> 输入整数[1-10]:<input type="text" name="num" /><br><br> <input type="submit" value="ok"> </form> </body> </html> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% String s=request.getParameter("num"); request.setAttribute("mynum", Integer.parseInt(s)); %> 和:<jsp:include page="getattribute2.jsp"></jsp:include><br> 积:<jsp:include page="getattribute3.jsp"></jsp:include> </body> </html> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% int value=(Integer)request.getAttribute("mynum"); int sum=0; for(int i=1;i<=value;i++) sum+=i; out.print(sum); %> </body> </html> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% int value=(Integer)request.getAttribute("mynum"); int sum=1; for(int i=1;i<=value;i++) sum*=i; out.print(sum); %> </body> </html>