JavaWeb笔记——通过超链接访问servlet

时间:2025-03-24 20:51:39
package myservlet; 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 TriangleServlet */ @WebServlet("/TriangleServlet") public class TriangleServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public TriangleServlet() { 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=green>"); //3.通过request对象获取JSP页面利用超链接送来的三边的参数,送给字符a,b,c String a=request.getParameter("sideA"); String b=request.getParameter("sideB"); String c=request.getParameter("sideC"); //4.如果a为空,则service方法结束,否则将字符串a,b,c通过方法转换为double型数据送给变量sideA,sideB,sideC if(a==null||a.length()==0) return; double sideA=0,sideB=0,sideC=0; try { sideA=Double.parseDouble(a); sideB=Double.parseDouble(b); sideC=Double.parseDouble(c); } catch(NumberFormatException exp) { return; } //5.求三角形面积要定义变量area初值为0,半周长p初值也为0.利用海伦公式求三角形面积 double area=0,p=0; p=(sideA+sideB+sideC)/2; area=Math.sqrt(p*(p-sideA)*(p-sideB)*(p-sideC)); //6.利用out对象的方法输出三角形面积及HTML标记 out.print("三角形"+a+","+b+","+c+"的面积是"+area); out.println("</body></html>"); } }