通过表单向servlet提交数据

1.创建名为ComputeBill的servlet文件

Java Web-servlet技术-通过表单向servlet提交数据

Java Web-servlet技术-通过表单向servlet提交数据

2.重写init()和service()

package myservlet;

import java.io.IOException;
import java.io.PrintWriter;

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 ComputeBill
 */
@WebServlet("/ComputeBill")
public class ComputeBill extends HttpServlet {
	private static final long serialVersionUID = 1L;
 
    public ComputeBill() {
        super();
        // TODO Auto-generated constructor stub
    }


	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}

	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//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=lightblue>");
	    //3.通过request对象获取表单中名字叫billMess的文本区中的内容并送给字符串str
	    String str = request.getParameter("billMess");
	    //4.如果str为空,则service方法结束,否则利用split()方法,其参数为正则表达式,将数字分解后送到字符串数组price中
	    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>");
	}

}

3.配置web.xml

Java Web-servlet技术-通过表单向servlet提交数据

4.创建sevletdemo2.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="computeBill" method="post" >
输入账单:<br>
<textarea rows="5" cols="30" name="billMess">
 洗衣粉:12.8元
 可乐:12元
 泡菜:2.8元
</textarea>
<br>
<input type="submit" name="提交" />
</form>
</body>
</html>

5.运行

Java Web-servlet技术-通过表单向servlet提交数据

点击提交按钮

Java Web-servlet技术-通过表单向servlet提交数据

相关文章:

  • 2021-04-17
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-10-22
猜你喜欢
  • 2021-12-12
  • 2021-06-02
  • 2021-08-03
  • 2022-12-23
  • 2021-08-13
  • 2021-05-10
  • 2022-12-23
相关资源
相似解决方案