JSP Form Processing and Salary Calculation

JSP Form Processing

Page: pagina1.jsp

This page contains a form to collect user data (name and last name).

Form:
Name:
Last Name:

Page: procesar.jsp

This page processes the data received from the form on pagina1.jsp.

Code Snippet:

<% String nombre = request.getParameter("txtNombre"); String apellido = request.getParameter("txtApellido"); %>

Processed Data

Name: <%=nombre%>
Last Name: <%=apellido%>

JSP Salary Calculation

Page: index.jsp

This page contains a form to calculate an employee’s salary based on hours worked and hourly rate.

Form:
Employee Name:
Number of Hours:
Hourly Rate:

Page: procesarHoras.jsp

This page calculates the salary based on the data submitted from index.jsp.

Code Snippet:

<% int horas = 0, horasExtra = 0; double valorHora = 0.00, pagoTotal = 0.00; String nombre = "";nombre = request.getParameter("txtNombre"); horas = Integer.parseInt(request.getParameter("txtNumeroHoras")); valorHora = Double.parseDouble(request.getParameter("txtValorHora"));if (horas > 44) { horasExtra = horas - 44; if (horasExtra > 8) { pagoTotal = (44 * valorHora) + (8 * 2 * valorHora) + ((horasExtra - 8) * 3 * valorHora); } else { pagoTotal = (44 * valorHora) + (horasExtra * 2 * valorHora); } } else { pagoTotal = horas * valorHora; } %>

Salary Calculation Result

Employee Name:<%=nombre%>
Total Salary:<%=pagoTotal%>

Servlet Example

Create a new package named “servlet” in “Source Packages”. Inside this package, create a new servlet named “Procesar.java”.

Page: pagina1.jsp

This page contains a form similar to the first example, but it will be processed by a servlet.

Form:
Name:
Last Name:

Servlet: Procesar.java

This servlet processes the form data from pagina1.jsp.

Code Snippet:

protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String nombre = request.getParameter("txtNombre"); String apellido = request.getParameter("txtApellido"); try { out.println("<html>"); out.println("<head>"); out.println("<title>Servlet Procesar</title>"); out.println("</head>"); out.println("<body>"); out.println("<h4>Data Processed from Servlet</h4>"); out.println("<b>Name: <b>" + nombre + "<br><br>"); out.println("<b>Last Name: <b>" + apellido + "<br><br>"); out.println("</body>"); out.println("</html>"); } finally { out.close(); } }