用户除了可以在浏览器的地址栏中直接键入servlet的请求格式来请求运行一个servlet外,也可以通过JSP页面来请求一个servlet。
可以让JSP页面负责数据的显示,而让一个servlet去做和处理数据有关的事情。
操作示范:
next
Finish
完整代码:
package myservlet;
//import java.io.IOException;
import java.io.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ComputerBill
*/
@WebServlet("/ComputerBill")
public class ComputerBill extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ComputerBill() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see Servlet#init(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
// TODO Auto-generated method stub
super.init(config);
}
/**
* @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//1.设置编码格式
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
//2.用printWriter类输出流声明out对象,通过response对象调用getWriter方法获取一个输出流,利用out对象调用println方法输出HTML标记。将背景色设置为黄色
PrintWriter out=response.getWriter();
out.println("<html><body bgcolor=yellow>");
//3.通过request对象获取表单中名字叫billMess的本文区中的内容送给字符串str
String str = request.getParameter("billMess");
//4.如果str为空,则servlet方法结束,否则利用split方法,其参数为正则表达式,将数字分解后送到字符串数组中
if (str==null||str.length()==0)
return;
String []price=str.split("[^0123456789.]+");
//5.求和要定义变量sum初值为0,利用循环遍历数组,求出数组中存储的数字的和
double sum=0;
try {
for (int i=0;i<price.length;i++) {
if (price[i].length()>=1)
sum += Double.parseDouble(price[i]);
}
}
catch(NumberFormatException e) {
out.print(""+e);
}
//6.利用out对象的方法输出消费总额,及HTML标记
out.print("\""+str+"\"<br>的消费额:"+sum+"元");
out.println("</body></html>");
}
}
添加方框内容
新建servletdemo2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>使用表单给servlet送数据</title>
</head>
<body>
<form action="computerBill" method="post">
输入账单:<br>
<textarea name="billMess" rows="5" cols="30">
洗衣粉:12.8元,可乐:12元,泡菜:0.8元
</textarea>
<br>
<input type=submit value="提交">
</form>
</body>
</html>
运行
提交