编写两个jsp页面inputString.jsp 和computer.jsp,用户可以并使用inputString.jsp提供的表单输入一个字符串,并提交给computer.jsp页面,该页面通过内置对象获取inputString.jsp页面提交的字符串,计算并显示该字符串的长度。
inputstring.jsp
inputString.jsp
<%@ page contentType="text/html"%>
<%@ page pageEncoding="utf-8"%>
<style>
#tom{
font-family:宋体;font-size:22;color:blue;
}
</style>
<html><body id=tom bgcolor="#ffccff">
在inputString.jsp页面输入字符串后,computer.jsp页面通过内置对象获取提交的字符串的长度。<br>
<%= session.getAttribute("str")%>
<form action="a.jsp" id=tom method="post">
<input type ="text" id="tom" name="str">
<input type="submit" id ="tom" name="submit" value="提交"/>
</form>
</body></html>
computer.jsp
computer.jsp
<%@ page contentType="text/html"%>
<%@ page pageEncoding="utf-8"%>
<html><body>
<%
request.setCharacterEncoding("utf-8");
String str=request.getParameter("str");
if(str==null||str.length()==0){
response.sendRedirect("inputString.jsp");
session.setAttribute("str","刚刚未输入字符"+str);
}
%>
<%
int a=str.length();
%>
字符串为:<%=str%><br>
长度为:<%= a%>
</body></html>
执行结果
未输入字符时显示结果:
在未输入字符串时再次点击,将显示如下结果:
注意:当输入的区域是文本框时(即input 标签改为 :textArea name="str" id="tom" ......),session.setRedirect("")重定向无效
输入字符串时显示结果