{"id":41,"date":"2013-05-07T15:56:06","date_gmt":"2013-05-07T15:56:06","guid":{"rendered":"https:\/\/code4reference.com\/?p=41"},"modified":"2013-05-07T15:56:06","modified_gmt":"2013-05-07T15:56:06","slug":"code4referencehandcrafted-hello-world-web-application-in-java","status":"publish","type":"post","link":"https:\/\/code4reference.com\/?p=41","title":{"rendered":"Code4ReferenceHandcrafted Hello world web-application in Java"},"content":{"rendered":"<p>Recently I was given a task to write a web-application. I didn\u2019t have prior knowledge of web-application, so I started looking for simple <em><strong>Hello world!!<\/strong><\/em> tutorial. I found many tutorials, all of them were using some kind of IDE to write the application(and no wonder most of them were using Eclipse). But I was inclined to use only VI as an editor and wanted to handcraft each and every piece of the application. Only few tutorials helped me in bits-and-pieces to write my own handcrafted <em><strong>Hello Wold!!<\/strong><\/em> web-application. I thought to share it with others.<br \/>\n<em><strong>Prerequisite :<\/strong><\/em><br \/>\n<strong>Build tool :<\/strong> Gradle (<a href=\"http:\/\/code4reference.com\/2012\/08\/how-to-install-gradle\/\">want to install gradle?<\/a>)<br \/>\n<strong>Server :<\/strong> <a href=\"http:\/\/tomcat.apache.org\/download-70.cgi\">Apache tomcat 7.0.30<\/a><br \/>\n<strong>Development Language :<\/strong> Java<\/p>\n<p>Let\u2019s define the proper directory structure compatible with the gradle <strong>war<\/strong> plugin. The project directory structure is shown below.<\/p>\n<pre>\n HelloWorldWebApp\n    \u2502       \n    \u251c\u2500\u2500 build.gradle\n    \u2514\u2500\u2500 src\n        \u2514\u2500\u2500 main\n            \u251c\u2500\u2500 java\n            \u2502   \u2514\u2500\u2500 com\n            \u2502       \u2514\u2500\u2500 code4reference\n            \u2502           \u2514\u2500\u2500 mywebapp\n            \u2502               \u2514\u2500\u2500 HelloWorldController.java\n            \u2514\u2500\u2500 webapp\n                \u2514\u2500\u2500 WEB-INF\n                    \u251c\u2500\u2500 appContext\n                    \u2502   \u251c\u2500\u2500 mappings.xml\n                    \u2502   \u2514\u2500\u2500 beans.xml\n                    \u2514\u2500\u2500 web.xml\n<\/pre>\n<p><strong>Note :<\/strong> Here, <strong>com\/code4reference\/webapp<\/strong> is basically the package name in which the HelloWoldController.java is defined. This directory structure will change according to the package name. For creating the above directory structure, execute the commands given below.<\/p>\n<pre>\nmkdir -p HelloWorldWebApp\/src\/main\/java\/com\/code4reference\/mywebapp\nmkdir -p HelloWorldWebApp\/src\/main\/webapp\/WEB-INF\/appContext\n<\/pre>\n<p>Create HelloWorldController.java in mywebapp and put the following content. You will notice that <b><i>greeting<\/i><\/b> and <b><i>hi<\/i><\/b> methods are mapped to the same name url in mappings.xml file. These urls are automatically mapped by the Spring framework. If the method name and the url are different, the Spring will throw exceptions.<\/p>\n<pre>package com.code4reference.mywebapp;\n\nimport java.util.Calendar;\nimport java.util.Date;\nimport java.util.GregorianCalendar;\n\nimport javax.servlet.http.HttpServletResponse;\n\nimport java.util.Properties; \nimport java.io.UnsupportedEncodingException;\n\nimport org.springframework.stereotype.Controller;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RequestParam;\nimport org.springframework.web.bind.annotation.ResponseBody;\nimport org.springframework.web.bind.annotation.RequestMethod;\n\n@Controller\npublic class HelloWorldController {\n        private final static String PARAMETER_MESSAGE = \"msg\";\n\n    \/** The method below handles the \n     * url localhost:8080\/HelloWorldWebApp\/greeting?msg=Hello \n     * here 'Hello' can be any word which can be passed \n     * as msg variable value. \n     * Here, url parameter msg is mapped to message variable.\n     **\/ \n    @RequestMapping(method = RequestMethod.GET)\n        @ResponseBody\n        public String greeting(@RequestParam(value = PARAMETER_MESSAGE ) String message,\n                                   HttpServletResponse response) throws Exception {\n                                   \n      System.out.println(\"Received param msg : \"+ message);\n       \/\/The below string will appear on the brwoser window.\n      return \"<\/pre>\n<h3><i>Your greeting &#8220;+message + &#8220;<\/i><\/h3>\n<pre>\";\n        }\n\n    \/** The below method will handle the \n     *url localhost:8080\/HelloWorldWebApp\/hi \n     *\n     **\/ \n    @RequestMapping(method = RequestMethod.GET)\n        @ResponseBody\n        public String hi(HttpServletResponse response) throws Exception {\n      \/\/The below string will appear on the brwoser window.\n      return \"<\/pre>\n<h3><i>Hi!! This is your first simple webapp<\/i><\/h3>\n<pre>\";\n        }\n}<\/pre>\n<p>Usually people create bean and URL mapping in web.xml but for better clarity and manageable code, we create two different files, called beans.xml and mappings.xml. beans.xml file will have the bean definition whereas mapping of bean to URL will be defined in mappings.xml file. These files will be imported to the web.xml.<br \/>\nNow, create file beans.xml in appContext directory and put the following content.<\/p>\n<pre>\n\n\n   \n   \n <\/pre>\n<p>In the same directory create another file called mappings.xml file and put the following content.<\/p>\n<pre>\n\n   \n   \n      \n          \n             \/greeting=HelloWorldController\n             \/hi=HelloWorldController\n           \n      \n   \n<\/pre>\n<p>Now it\u2019s time to define the web.xml file. Create the web.xml file in <em><strong>WEB-INF<\/strong><\/em> directory.<\/p>\n<pre>\n\n         \n   \n      dispatcher\n     org.springframework.web.servlet.DispatcherServlet\n      1\n      \n         contextConfigLocation\n         \n            \/WEB-INF\/appContext\/mappings.xml\n            \/WEB-INF\/appContext\/beans.xml\n         \n      \n   \n\n   \n      dispatcher\n      \/*\n   \n     \n   \n    \n   \n<\/pre>\n<p>You may have noticed that mappings.xml and beans.xml have been imported to web.xml. Now its time to build the application for which we will write the gradle script. Create build.gradle file in HelloWoldWebApp directory and put the following content.<\/p>\n<pre>apply plugin: 'java'\napply plugin: 'war'\n\nrepositories {\n   mavenCentral()\n}\ndependencies {\n        compile 'org.springframework:spring-webmvc:3.0.5.RELEASE'\n        compile 'commons-codec:commons-codec:1.4'\n        providedCompile \"javax.servlet:servlet-api:2.5\"\n        \n}<\/pre>\n<p>Here Java and War plugin have been used to compile the java source code and to build the war file respectively. Gradle war plugin expects the java source code in src\/main\/java and the web configuration file in src\/main\/webapp\/WEB-INF folder. Notice that compile time dependencies are included in the dependencies section of the gradle script. The Gradle takes care of including the dependencies jar files in the war file. Once done, just execute the following command in HelloWoldWebApp folder<\/p>\n<pre>gradle war<\/pre>\n<p>Gradle creates the war file in <em><strong>build\/libs<\/strong><\/em> directory. Now put the HelloWorldWebApp.war in [apache-tomcat-home-directory]\/bin\/webapps and restart the tomcat.<\/p>\n<p><strong>Note :<\/strong> If Apache-tomcat 7.0 is installed in your system, then you don\u2019t need to restart the tomcat. Tomcat identifies new web-application, deploys it and restarts itself<\/p>\n<p>Once the tomcat is restarted, hit <em><strong>\u201chttp:\/\/localhost:8080\/HelloWorld\/hi\u201d<\/strong><\/em> on browser. You will see this line \u201cHi!! This is your first simple webapp\u201d on webpage. Even you can try with this url <em><strong>\u201chttp:\/\/localhost:8080\/HelloWorld\/greeting?msg=Hellothere\u201d<\/strong><\/em>, try to change the word \u201cHellothere\u201d and hit the url. The message displayed on the webpage changes accordingly.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Recently I was given a task to write a web-application. I didn\u2019t have prior knowledge of web-application, so I started looking for simple Hello world!! tutorial. I found many tutorials, all of them were using some kind of IDE to write the application(and no wonder most of them were using Eclipse). But I was inclined [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-41","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts\/41","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=41"}],"version-history":[{"count":0,"href":"https:\/\/code4reference.com\/index.php?rest_route=\/wp\/v2\/posts\/41\/revisions"}],"wp:attachment":[{"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=41"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=41"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/code4reference.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=41"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}