JSP实验三(2)response
文章目录
一、实验题目及要求
1 实验内容
编写两个JSP页面input.jsp和result.jsp。input.jsp页面提交一个数字给result.jsp页面,result.jsp页面使用response对象做出动态响应。
1 input.jsp的具体要求
input.jsp提供表单,用户在表单中输入一个数字,提交给result.jsp页面。
2 result.jsp
result.jsp页面首先使用request对象获得input.jsp页面提交的数字,然后根据数字的大小作出不同的响应。
如果数字小与0,response对象的调用setContentType(String s)方法将contentType属性的值设置为text/plain,同时输出数字的平方;
如果数字大于等于0并且小于100,response对象的调用setContentType(String s)方法将contentType属性的值设置为application/msword,同时输出数字的立方;
如果数字大于等于100,response对象调用sendError(int n)方法将状态行的内容设置为404;
如果用户在input.jsp页面输入了非数字,response对象调用**sendRedirect(URL url)**方法将用户的重定向到input.jsp页面。
实验效果实例
input.jsp
result.jsp
二、实验代码及效果
1 input.jsp
<%--
Created by IntelliJ IDEA.
User: ruochen
Date: 2020/11/1
Time: 22:29
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="result.jsp" method="post">
输入数字
<input type="text" name="sideA" />
<input type="submit" value="提交"/></form>
</body>
</html>
result.jsp
<%--
Created by IntelliJ IDEA.
User: ruochen
Date: 2020/11/1
Time: 22:29
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<% request.setCharacterEncoding("UTF-8"); %>
<% String a=request.getParameter("sideA");
try {
double x=Double.parseDouble(a);
if(x<0)
{out.print(x+"的平方:"+(x*x));
response.setContentType ("text/plain;charset=UTF-8");
}
else
if(x>=0&&x<100)
{out.print(x+"的立方:"+(x*x*x));
response.setContentType ("application/msword;charset=UTF-8");
}
else
if(x>=100)
response.sendError(404);
}
catch (Exception e)
{response.sendRedirect("input.jsp");
}
%>
</body>
</html>
效果实例
总结
- 老师给的题目实例有问题,一切以实际为准
- String a=request.getParameter(“sideA”);获取input.jsp中输入框的值
- response.setContentType (“text/plain;charset=UTF-8”);将当前页面转换为纯文本文档
- response.setContentType (“application/msword;charset=UTF-8”);application/msword:Word文件,我们这里转换成了一个text文件
- response.sendError(404); 返回404
- response.sendRedirect(“input.jsp”);重定向input.jsp