The application is deliberately created in JSP or servlets to keep it simple and to avoid having familiarity with other frameworks to understand the example. Before we get into the basics of the application code, let's solve the error that Eclipse complains of in step 5 of the Creating a MyDistance Project section. Add the following dependency in the pom
file and the error should vanish:
<!-- Include servlet API --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <scope>provided</scope> </dependency>
The preceding dependency will also be required for writing servlets later in the Adding a Servlet section.
The scope is provided, which means that the container will provide this dependency, and Maven will not include it in this project's output or war file. We discussed scopes in more detail in Chapter 4, Building and Running a Project.
The application will require the following additional files:
Under src/main/webapp
, open the index.jsp
file, and add the following code to get the distance, its unit, and conversion unit as input. The form consists of an input box, two radio buttons to choose units, and a button to initiate the conversion, as shown in the following code:
<body> <h2>MyDistance Utility</h2> <form> <table> <tr> <td><input type="text" id="mydistance" name='distance' placeholder="My Distance In"></td> <td> <input type="radio" name="distin" id="distin" value="km">KM<br> <input type="radio" name="distin" id="distin" value="m">Metre</td> </tr> <tr></tr> <tr></tr> <tr></tr> <tr> <td> <label for="convert">Convert To</label></td> <td> <input type="radio" name="convertto" id="convertto" value="yd">Yard<br> <input type="radio" name="convertto" id="convertto" value="mi">Miles</td> </tr> <tr> <td><input type="button" id="submit" value='Convert'></td> </tr> </table> <div id="convertvalue"> </div> </form> </body>
If you like, you can add CSS styles to make the UI more pleasing. The preceding bare bones file results in something like this:
We want to calculate the value and show the corresponding result beneath it using Ajax (jQuery Ajax). To achieve this, add the following piece of code:
<head> <script src="http://code.jquery.com/jquery-latest.js"> </script> <script> $(document).ready(function() { $('#submit').click(function(event) { var mydistance=$('#mydistance').val(); var mydistanceIn=$('[name=distin]:checked').val(); var convertTo=$('[name=convertto]:checked').val(); if(mydistanceIn==convertTo){ alert("Cannot have same unit"); return false; } console.log(mydistance+mydistanceIn+convertTo); $.get('mydistance',{distance:mydistance,distIn:mydistanceIn,convert:convertTo},function(responseText) { $('#convertvalue').text(responseText); }); }); }); </script> </head>
Before we add any Java files, create a folder, java
, under src/main
as Maven looks for Java files in this directory (all Java files should reside under it). Add the DistanceServlet
servlet in the com.packt.chpt5.mydistance
package. The servlet gets the request parameters, extracts it, and calls the corresponding conversion method in the utility class. The servlet would look like the following:
public class DistanceServlet extends HttpServlet { private static final long serialVersionUID = 1L; static Logger log=Logger.getLogger(DistanceServlet.class); public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { double convertVal = 0; double distanceProvided =Double.parseDouble(req.getParameter("distance")); String distanceIn=req.getParameter("distIn"); String convertTo=req.getParameter("convert"); log.debug("Request Parameters ==>"+"Distance-"+distanceProvided+distanceIn+" Conversion Unit- "+convertTo ); ConversionUtil conversion= new ConversionUtil(); if(distanceIn.equals("km") && convertTo.equals("yd")){ convertVal=conversion.convertkmToYard(distanceProvided); } if(distanceIn.equals("m") && convertTo.equals("yd")){ convertVal=conversion.convertMtoYard(distanceProvided); } if(distanceIn.equals("km") && convertTo.equals("mi")){ convertVal=conversion.convertKMToMile(distanceProvided); } if(distanceIn.equals("m") && convertTo.equals("mi")){ convertVal=conversion.convertMToMile(distanceProvided); } resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); out.print("The converted value is "+convertVal); out.flush(); out.close(); } }
Add the following lines in the web.xml
file under src/main/webapp/WEB-INF
:
<web-app> <display-name>MyDistance Calculator</display-name> <servlet> <servlet-name>mydistance</servlet-name> <servlet-class>com.packt.chpt5.mydistance.DistanceServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>mydistance</servlet-name> <url-pattern>/mydistance</url-pattern> </servlet-mapping> </web-app>
Add a utility class ConversionUtil
in the com.packt.chpt5.mydistance.util
package. A utility class contains methods to perform conversion across different distance units. Add the following code to the utility class:
public double convertKMToMile(double distance){ return (distance*0.62137); } public double convertkmToYard(double distance){ return distance*1093.6; } public double convertMToMile(double distance){ return (distance/1000)*0.62137 ; } public double convertMtoYard(double distance){ return (distance/1000)*1093.6; }
3.137.217.17