Discuss SWING ”; Previous Next JAVA provides a rich set of libraries to create Graphical User Interface in a platform independent way. In this tutorial, we”ll look at SWING GUI controls. Print Page Previous Next Advertisements ”;
Category: Java
Spring Boot – Introduction
Spring Boot – Introduction ”; Previous Next Spring Boot is an open source Java-based framework used to create a micro Service. It is developed by Pivotal Team and is used to build stand-alone and production ready spring applications. This chapter will give you an introduction to Spring Boot and familiarizes you with its basic concepts. What is Micro Service? Micro Service is an architecture that allows the developers to develop and deploy services independently. Each service running has its own process and this achieves the lightweight model to support business applications. Advantages Micro services offers the following advantages to its developers − Easy deployment Simple scalability Compatible with Containers Minimum configuration Lesser production time What is Spring Boot? Spring Boot provides a good platform for Java developers to develop a stand-alone and production-grade spring application that you can just run. You can get started with minimum configurations without the need for an entire Spring configuration setup. Advantages Spring Boot offers the following advantages to its developers − Easy to understand and develop spring applications Increases productivity Reduces the development time Goals Spring Boot is designed with the following goals − To avoid complex XML configuration in Spring To develop a production ready Spring applications in an easier way To reduce the development time and run the application independently Offer an easier way of getting started with the application Why Spring Boot? You can choose Spring Boot because of the features and benefits it offers as given here − It provides a flexible way to configure Java Beans, XML configurations, and Database Transactions. It provides a powerful batch processing and manages REST endpoints. In Spring Boot, everything is auto configured; no manual configurations are needed. It offers annotation-based spring application Eases dependency management It includes Embedded Servlet Container How does it work? Spring Boot automatically configures your application based on the dependencies you have added to the project by using @EnableAutoConfiguration annotation. For example, if MySQL database is on your classpath, but you have not configured any database connection, then Spring Boot auto-configures an in-memory database. The entry point of the spring boot application is the class contains @SpringBootApplication annotation and the main method. Spring Boot automatically scans all the components included in the project by using @ComponentScan annotation. Spring Boot Starters Handling dependency management is a difficult task for big projects. Spring Boot resolves this problem by providing a set of dependencies for developers convenience. For example, if you want to use Spring and JPA for database access, it is sufficient if you include spring-boot-starter-data-jpa dependency in your project. Note that all Spring Boot starters follow the same naming pattern spring-boot-starter- *, where * indicates that it is a type of the application. Examples Look at the following Spring Boot starters explained below for a better understanding − Spring Boot Starter Actuator dependency is used to monitor and manage your application. Its code is shown below − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> Spring Boot Starter Security dependency is used for Spring Security. Its code is shown below − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> Spring Boot Starter web dependency is used to write a Rest Endpoints. Its code is shown below − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> Spring Boot Starter Thyme Leaf dependency is used to create a web application. Its code is shown below − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> Spring Boot Starter Test dependency is used for writing Test cases. Its code is shown below − <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> </dependency> Auto Configuration Spring Boot Auto Configuration automatically configures your Spring application based on the JAR dependencies you added in the project. For example, if MySQL database is on your class path, but you have not configured any database connection, then Spring Boot auto configures an in-memory database. For this purpose, you need to add @EnableAutoConfiguration annotation or @SpringBootApplication annotation to your main class file. Then, your Spring Boot application will be automatically configured. Observe the following code for a better understanding − import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; @EnableAutoConfiguration public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Spring Boot Application The entry point of the Spring Boot Application is the class contains @SpringBootApplication annotation. This class should have the main method to run the Spring Boot application. @SpringBootApplication annotation includes Auto- Configuration, Component Scan, and Spring Boot Configuration. If you added @SpringBootApplication annotation to the class, you do not need to add the @EnableAutoConfiguration, @ComponentScan and @SpringBootConfiguration annotation. The @SpringBootApplication annotation includes all other annotations. Observe the following code for a better understanding − import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Component Scan Spring Boot application scans all the beans and package declarations when the application initializes. You need to add the @ComponentScan annotation for your class file to scan your components added in your project. Observe the following code for a better understanding − import org.springframework.boot.SpringApplication; import org.springframework.context.annotation.ComponentScan; @ComponentScan public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } } Print Page Previous Next Advertisements ”;
Spring Boot – Tomcat Port Number ”; Previous Next Spring Boot lets you to run the same application more than once on a different port number. In this chapter, you will learn about this in detail. Note that the default port number 8080. Custom Port In the application.properties file, we can set custom port number for the property server.port server.port = 9090 In the application.yml file, you can find as follows − server: port: 9090 Random Port In the application.properties file, we can set random port number for the property server.port server.port = 0 In the application.yml file, you can find as follows − server: port: 0 Note − If the server.port number is 0 while starting the Spring Boot application, Tomcat uses the random port number. Print Page Previous Next Advertisements ”;
Spring Boot – Zuul Proxy Server and Routing ”; Previous Next Zuul Server is a gateway application that handles all the requests and does the dynamic routing of microservice applications. The Zuul Server is also known as Edge Server. For Example, /api/user is mapped to the user service and /api/products is mapped to the product service and Zuul Server dynamically routes the requests to the respective backend application. In this chapter, we are going to see in detail how to create Zuul Server application in Spring Boot. Creating Zuul Server Application The Zuul Server is bundled with Spring Cloud dependency. You can download the Spring Boot project from Spring Initializer page https://start.spring.io/ and choose the Zuul Server dependency. Add the @EnableZuulProxy annotation on your main Spring Boot application. The @EnableZuulProxy annotation is used to make your Spring Boot application act as a Zuul Proxy server. package com.tutorialspoint.zuulserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.zuul.EnableZuulProxy; @SpringBootApplication @EnableZuulProxy public class ZuulserverApplication { public static void main(String[] args) { SpringApplication.run(ZuulserverApplication.class, args); } } You will have to add the Spring Cloud Starter Zuul dependency in our build configuration file. Maven users will have to add the following dependency in your pom.xml file − <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency> For Gradle users, add the below dependency in your build.gradle file compile(”org.springframework.cloud:spring-cloud-starter-zuul”) For Zuul routing, add the below properties in your application.properties file or application.yml file. spring.application.name = zuulserver zuul.routes.products.path = /api/demo/** zuul.routes.products.url = http://localhost:8080/ server.port = 8111 This means that http calls to /api/demo/ get forwarded to the products service. For example, /api/demo/products is forwarded to /products. yaml file users can use the application.yml file shown below − server: port: 8111 spring: application: name: zuulserver zuul: routes: products: path: /api/demo/** url: http://localhost:8080/ Note − The http://localhost:8080/ application should already be running before routing via Zuul Proxy. The complete build configuration file is given below. Maven users can use the pom.xml file given below − <?xml version = “1.0” encoding = “UTF-8”?> <project xmlns = “http://maven.apache.org/POM/4.0.0” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = “http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd”> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>zuulserver</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>zuulserver</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath/> <!– lookup parent from repository –> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> <spring-cloud.version>Edgware.RELEASE</spring-cloud.version> </properties> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-zuul</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <dependencyManagement> <dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-dependencies</artifactId> <version>${spring-cloud.version}</version> <type>pom</type> <scope>import</scope> </dependency> </dependencies> </dependencyManagement> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> Gradle users can use the build.gradle file given below − buildscript { ext { springBootVersion = ”1.5.9.RELEASE” } repositories { mavenCentral() } dependencies { classpath(“org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}”) } } apply plugin: ”java” apply plugin: ”eclipse” apply plugin: ”org.springframework.boot” group = ”com.tutorialspoint” version = ”0.0.1-SNAPSHOT” sourceCompatibility = 1.8 repositories { mavenCentral() } ext { springCloudVersion = ”Edgware.RELEASE” } dependencies { compile(”org.springframework.cloud:spring-cloud-starter-zuul”) testCompile(”org.springframework.boot:spring-boot-starter-test”) } dependencyManagement { imports { mavenBom “org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}” } } You can create an executable JAR file, and run the Spring Boot application by using the Maven or Gradle commands given below − For Maven, you can use the command given below − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under the target directory. For Gradle, you can use the command given below − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under the build/libs directory. Now, run the JAR file by using the command shown below − java –jar <JARFILE> You can find the application has started on the Tomcat port 8111 as shown here. Now, hit the URL http://localhost:8111/api/demo/products in your web browser and you can see the output of /products REST Endpoint as shown below − Print Page Previous Next Advertisements ”;
Spring MVC – Dropdown
Spring MVC – Dropdown Example ”; Previous Next The following example describes how to use Dropdown in forms using the Spring Web MVC framework. To start with, let us have a working Eclipse IDE in place and stick to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create Java classes User, UserController under the com.tutorialspointpackage. 3 Create view files user.jsp, users.jsp under the jsp sub-folder. 4 The final step is to create the content of the source and configuration files and export the application as explained below. User.java package com.tutorialspoint; public class User { private String username; private String password; private String address; private boolean receivePaper; private String [] favoriteFrameworks; private String gender; private String favoriteNumber; private String country; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public boolean isReceivePaper() { return receivePaper; } public void setReceivePaper(boolean receivePaper) { this.receivePaper = receivePaper; } public String[] getFavoriteFrameworks() { return favoriteFrameworks; } public void setFavoriteFrameworks(String[] favoriteFrameworks) { this.favoriteFrameworks = favoriteFrameworks; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getFavoriteNumber() { return favoriteNumber; } public void setFavoriteNumber(String favoriteNumber) { this.favoriteNumber = favoriteNumber; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } } UserController.java package com.tutorialspoint; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.ui.ModelMap; @Controller public class UserController { @RequestMapping(value = “/user”, method = RequestMethod.GET) public ModelAndView user() { User user = new User(); user.setFavoriteFrameworks((new String []{“Spring MVC”,”Struts 2″})); user.setGender(“M”); ModelAndView modelAndView = new ModelAndView(“user”, “command”, user); return modelAndView; } @RequestMapping(value = “/addUser”, method = RequestMethod.POST) public String addUser(@ModelAttribute(“SpringWeb”)User user, ModelMap model) { model.addAttribute(“username”, user.getUsername()); model.addAttribute(“password”, user.getPassword()); model.addAttribute(“address”, user.getAddress()); model.addAttribute(“receivePaper”, user.isReceivePaper()); model.addAttribute(“favoriteFrameworks”, user.getFavoriteFrameworks()); model.addAttribute(“gender”, user.getGender()); model.addAttribute(“favoriteNumber”, user.getFavoriteNumber()); model.addAttribute(“country”, user.getCountry()); return “users”; } @ModelAttribute(“webFrameworkList”) public List<String> getWebFrameworkList() { List<String> webFrameworkList = new ArrayList<String>(); webFrameworkList.add(“Spring MVC”); webFrameworkList.add(“Struts 1”); webFrameworkList.add(“Struts 2”); webFrameworkList.add(“Apache Wicket”); return webFrameworkList; } @ModelAttribute(“numbersList”) public List<String> getNumbersList() { List<String> numbersList = new ArrayList<String>(); numbersList.add(“1”); numbersList.add(“2”); numbersList.add(“3”); numbersList.add(“4”); return numbersList; } @ModelAttribute(“countryList”) public Map<String, String> getCountryList() { Map<String, String> countryList = new HashMap<String, String>(); countryList.put(“US”, “United States”); countryList.put(“CH”, “China”); countryList.put(“SG”, “Singapore”); countryList.put(“MY”, “Malaysia”); return countryList; } } Here, for the first service method user(), we have passed a blank User object in the ModelAndView object with name “command”, because the spring framework expects an object with name “command”, if you are using <form:form> tags in your JSP file. So when the user() method is called, it returns the user.jsp view. The second service method addUser() will be called against a POST method on the HelloWeb/addUser URL. You will prepare your model object based on the submitted information. Finally, the “users” view will be returned from the service method, which will result in rendering the users.jsp. user.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring MVC Form Handling</title> </head> <body> <h2>User Information</h2> <form:form method = “POST” action = “/HelloWeb/addUser”> <table> <tr> <td><form:label path = “username”>User Name</form:label></td> <td><form:input path = “username” /></td> </tr> <tr> <td><form:label path = “password”>Age</form:label></td> <td><form:password path = “password” /></td> </tr> <tr> <td><form:label path = “address”>Address</form:label></td> <td><form:textarea path = “address” rows = “5” cols = “30” /></td> </tr> <tr> <td><form:label path = “receivePaper”>Subscribe Newsletter</form:label></td> <td><form:checkbox path = “receivePaper” /></td> </tr> <tr> <td><form:label path = “favoriteFrameworks”>Favorite Web Frameworks</form:label></td> <td><form:checkboxes items = “${webFrameworkList}” path = “favoriteFrameworks” /></td> </tr> <tr> <td><form:label path = “gender”>Gender</form:label></td> <td> <form:radiobutton path = “gender” value = “M” label = “Male” /> <form:radiobutton path = “gender” value = “F” label = “Female” /> </td> </tr> <tr> <td><form:label path = “favoriteNumber”>Favorite Number</form:label></td> <td> <form:radiobuttons path = “favoriteNumber” items = “${numbersList}” /> </td> </tr> <tr> <td><form:label path = “country”>Country</form:label></td> <td> <form:select path = “country”> <form:option value = “NONE” label = “Select”/> <form:options items = “${countryList}” /> </form:select> </td> </tr> <tr> <td colspan = “2”> <input type = “submit” value = “Submit”/> </td> </tr> </table> </form:form> </body> </html> Here, we are using <form:select /> , <form:option /> and <form:options /> tags to render HTML select. For example − <form:select path = “country”> <form:option value = “NONE” label = “Select”/> <form:options items = “${countryList}” /> </form:select> It will render following HTML content. <select id = “country” name = “country”> <option value = “NONE”>Select</option> <option value = “US”>United States</option> <option value = “CH”>China</option> <option value = “MY”>Malaysia</option> <option value = “SG”>Singapore</option> </select> users.jsp <%@taglib uri = “http://www.springframework.org/tags/form” prefix = “form”%> <html> <head> <title>Spring MVC Form Handling</title> </head> <body> <h2>Submitted User Information</h2> <table> <tr> <td>Username</td> <td>${username}</td> </tr> <tr> <td>Password</td> <td>${password}</td> </tr> <tr> <td>Address</td> <td>${address}</td> </tr> <tr> <td>Subscribed to Newsletter</td> <td>${receivePaper}</td> </tr> <tr> <td>Favorite Web Frameworks</td> <td> <% String[] favoriteFrameworks = (String[])request.getAttribute(“favoriteFrameworks”); for(String framework: favoriteFrameworks) { out.println(framework); } %></td> </tr> <tr> <td>Gender</td> <td>${(gender==”M”? “Male” : “Female”)}</td> </tr> <tr> <td>Favourite Number</td> <td>${favoriteNumber}</td> </tr> <tr> <td>Country</td> <td>${country}</td> </tr> </table> </body> </html> Once you are done with creating source and configuration files, export your application. Right click on your application, use the Export → WAR File option and save your HelloWeb.war file in Tomcat”s webapps folder. Now, start the Tomcat server and make sure you are able to access other webpages from webapps folder using a standard browser. Try a URL – http://localhost:8080/HelloWeb/user and we will see the following screen, if everything is fine with the Spring Web Application. After submitting the required information, click on the submit button to submit the form. You should see the following screen, if everything is fine with your Spring Web Application. Print Page Previous Next Advertisements ”;
Spring MVC – Upload
Spring MVC – File Upload Example ”; Previous Next The following example shows how to use File Upload Control in forms using the Spring Web MVC framework. To start with, let us have a working Eclipse IDE in place and adhere to the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with a name HelloWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create Java classes FileModel, FileUploadController under the com.tutorialspoint package. 3 Create view files fileUpload.jsp, success.jsp under the jsp sub-folder. 4 Create a folder temp under the WebContent sub-folder. 5 Download Apache Commons FileUpload library commons-fileupload.jar and Apache Commons IO library commons-io.jar. Put them in your CLASSPATH. 6 The final step is to create the content of the source and configuration files and export the application as explained below. FileModel.java package com.tutorialspoint; import org.springframework.web.multipart.MultipartFile; public class FileModel { private MultipartFile file; public MultipartFile getFile() { return file; } public void setFile(MultipartFile file) { this.file = file; } } FileUploadController.java package com.tutorialspoint; import java.io.File; import java.io.IOException; import javax.servlet.ServletContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.util.FileCopyUtils; import org.springframework.validation.BindingResult; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; @Controller public class FileUploadController { @Autowired ServletContext context; @RequestMapping(value = “/fileUploadPage”, method = RequestMethod.GET) public ModelAndView fileUploadPage() { FileModel file = new FileModel(); ModelAndView modelAndView = new ModelAndView(“fileUpload”, “command”, file); return modelAndView; } @RequestMapping(value=”/fileUploadPage”, method = RequestMethod.POST) public String fileUpload(@Validated FileModel file, BindingResult result, ModelMap model) throws IOException { if (result.hasErrors()) { System.out.println(“validation errors”); return “fileUploadPage”; } else { System.out.println(“Fetching file”); MultipartFile multipartFile = file.getFile(); String uploadPath = context.getRealPath(“”) + File.separator + “temp” + File.separator; //Now do something with file… FileCopyUtils.copy(file.getFile().getBytes(), new File(uploadPath+file.getFile().getOriginalFilename())); String fileName = multipartFile.getOriginalFilename(); model.addAttribute(“fileName”, fileName); return “success”; } } } HelloWeb-servlet.xml <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = ” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <context:component-scan base-package = “com.tutorialspoint” /> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/” /> <property name = “suffix” value = “.jsp” /> </bean> <bean id = “multipartResolver” class = “org.springframework.web.multipart.commons.CommonsMultipartResolver” /> </beans> Here, for the first service method fileUploadPage(), we have passed a blank FileModel object in the ModelAndView object with name “command”, because the spring framework expects an object with name “command”, if you are using <form:form> tags in your JSP file. So, when fileUploadPage() method is called, it returns fileUpload.jsp view. The second service method fileUpload() will be called against a POST method on the HelloWeb/fileUploadPage URL. You will prepare the file to be uploaded based on the submitted information. Finally, a “success” view will be returned from the service method, which will result in rendering success.jsp. fileUpload.jsp <%@ page contentType=”text/html; charset = UTF-8″ %> <%@ taglib prefix = “form” uri = “http://www.springframework.org/tags/form”%> <html> <head> <title>File Upload Example</title> </head> <body> <form:form method = “POST” modelAttribute = “fileUpload” enctype = “multipart/form-data”> Please select a file to upload : <input type = “file” name = “file” /> <input type = “submit” value = “upload” /> </form:form> </body> </html> Here, we are using modelAttribute attribute with value=”fileUpload” to map the file Upload control with the server model. success.jsp <%@ page contentType = “text/html; charset = UTF-8″ %> <html> <head> <title>File Upload Example</title> </head> <body> FileName : lt;b> ${fileName} </b> – Uploaded Successfully. </body> </html> Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the HelloWeb.war file in the Tomcat”s webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder using a standard browser. Try a URL– http://localhost:8080/HelloWeb/fileUploadPage and we will see the following screen, if everything is fine with the Spring Web Application. After submitting the required information, click on the submit button to submit the form. You should see the following screen, if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;
SWING – Menu
SWING – Menu Classes ”; Previous Next As we know that every top-level window has a menu bar associated with it. This menu bar consists of various menu choices available to the end user. Further, each choice contains a list of options, which is called drop-down menus. Menu and MenuItem controls are subclass of MenuComponent class. Menu Hierarchy Menu Controls Sr.No. Class & Description 1 JMenuBar The JMenuBar object is associated with the top-level window. 2 JMenuItem The items in the menu must belong to the JMenuItem or any of its subclass. 3 JMenu The JMenu object is a pull-down menu component which is displayed from the menu bar. 4 JCheckboxMenuItem JCheckboxMenuItem is the subclass of JMenuItem. 5 JRadioButtonMenuItem JRadioButtonMenuItem is the subclass of JMenuItem. 6 JPopupMenu JPopupMenu can be dynamically popped up at a specified position within a component. Print Page Previous Next Advertisements ”;
Spring MVC – Bean Name Url Handler Mapping Example ”; Previous Next The following example shows how to use Bean Name URL Handler Mapping using the Spring Web MVC Framework. The BeanNameUrlHandlerMapping class is the default handler mapping class, which maps the URL request(s) to the name of the beans mentioned in the configuration. <beans> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/”/> <property name = “suffix” value = “.jsp”/> </bean> <bean class = “org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping”/> <bean name = “/helloWorld.htm” class = “com.tutorialspoint.HelloController” /> <bean name = “/hello*” class = “com.tutorialspoint.HelloController” /> <bean name = “/welcome.htm” class = “com.tutorialspoint.WelcomeController”/> </beans> For example, using the above configuration, if URI /helloWorld.htm or /hello{any letter}.htm is requested, DispatcherServlet will forward the request to the HelloController. /welcome.htm is requested, DispatcherServlet will forward the request to the WelcomeController. /welcome1.htm is requested, DispatcherServlet will not find any controller and server will throw 404 status error. To start with, let us have a working Eclipse IDE in place and consider the following steps to develop a Dynamic Form based Web Application using the Spring Web Framework. Step Description 1 Create a project with a name TestWeb under a package com.tutorialspoint as explained in the Spring MVC – Hello World chapter. 2 Create Java classes HelloController, WelcomeController under the com.tutorialspoint package. 3 Create view files hello.jsp, welcome.jsp under the jsp sub-folder. 4 The final step is to create the content of all source and configuration files and export the application as explained below. HelloController.java package com.tutorialspoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class HelloController extends AbstractController{ @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“hello”); model.addObject(“message”, “Hello World!”); return model; } } WelcomeController.java package com.tutorialspoint; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class WelcomeController extends AbstractController{ @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView(“welcome”); model.addObject(“message”, “Welcome!”); return model; } } TestWeb-servlet.xml <beans xmlns = “http://www.springframework.org/schema/beans” xmlns:context = “http://www.springframework.org/schema/context” xmlns:xsi = “http://www.w3.org/2001/XMLSchema-instance” xsi:schemaLocation = ” http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd”> <bean class = “org.springframework.web.servlet.view.InternalResourceViewResolver”> <property name = “prefix” value = “/WEB-INF/jsp/”/> <property name = “suffix” value = “.jsp”/> </bean> <bean class = “org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping”/> <bean name = “/helloWorld.htm” class = “com.tutorialspoint.HelloController” /> <bean name = “/hello*” class = “com.tutorialspoint.HelloController” /> <bean name = “/welcome.htm” class = “com.tutorialspoint.WelcomeController”/> </beans> hello.jsp <%@ page contentType = “text/html; charset = UTF-8” %> <html> <head> <title>Hello World</title> </head> <body> <h2>${message}</h2> </body> </html> welcome.jsp <%@ page contentType = “text/html; charset = UTF-8″ %> <html> <head> <title>Welcome</title> </head> <body> <h2>${message}</h2> </body> </html> Once you are done with creating source and configuration files, export your application. Right click on your application, use Export → WAR File option and save the TestWeb.war file in the Tomcat”s webapps folder. Now, start your Tomcat server and make sure you are able to access other webpages from the webapps folder by using a standard browser. Try a URL − http://localhost:8080/TestWeb/helloWorld.htm and we will see the following screen, if everything is fine with the Spring Web Application. Try a URL − http://localhost:8080/TestWeb/hello.htm and we will see the following screen, if everything is fine with the Spring Web Application. Try a URL http://localhost:8080/TestWeb/welcome.htm and we will see the following screen, if everything is fine with the Spring Web Application. Try a URL http://localhost:8080/TestWeb/welcome1.htm and we will see the following screen, if everything is fine with the Spring Web Application. Print Page Previous Next Advertisements ”;
SWING – Layouts
SWING – Layouts ”; Previous Next Layout refers to the arrangement of components within the container. In another way, it could be said that layout is placing the components at a particular position within the container. The task of laying out the controls is done automatically by the Layout Manager. Layout Manager The layout manager automatically positions all the components within the container. Even if you do not use the layout manager, the components are still positioned by the default layout manager. It is possible to lay out the controls by hand, however, it becomes very difficult because of the following two reasons. It is very tedious to handle a large number of controls within the container. Usually, the width and height information of a component is not given when we need to arrange them. Java provides various layout managers to position the controls. Properties like size, shape, and arrangement varies from one layout manager to the other. When the size of the applet or the application window changes, the size, shape, and arrangement of the components also changes in response, i.e. the layout managers adapt to the dimensions of the appletviewer or the application window. The layout manager is associated with every Container object. Each layout manager is an object of the class that implements the LayoutManager interface. Following are the interfaces defining the functionalities of Layout Managers. Sr.No. Interface & Description 1 LayoutManager The LayoutManager interface declares those methods which need to be implemented by the class, whose object will act as a layout manager. 2 LayoutManager2 The LayoutManager2 is the sub-interface of the LayoutManager. This interface is for those classes that know how to layout containers based on layout constraint object. AWT Layout Manager Classes Following is the list of commonly used controls while designing GUI using AWT. Sr.No. LayoutManager & Description 1 BorderLayout The borderlayout arranges the components to fit in the five regions: east, west, north, south, and center. 2 CardLayout The CardLayout object treats each component in the container as a card. Only one card is visible at a time. 3 FlowLayout The FlowLayout is the default layout. It layout the components in a directional flow. 4 GridLayout The GridLayout manages the components in the form of a rectangular grid. 5 GridBagLayout This is the most flexible layout manager class. The object of GridBagLayout aligns the component vertically, horizontally, or along their baseline without requiring the components of the same size. 6 GroupLayout The GroupLayout hierarchically groups the components in order to position them in a Container. 7 SpringLayout A SpringLayout positions the children of its associated container according to a set of constraints. Print Page Previous Next Advertisements ”;
SWING – Event Listeners
SWING – Event Listeners ”; Previous Next Event listeners represent the interfaces responsible to handle events. Java provides various Event listener classes, however, only those which are more frequently used will be discussed. Every method of an event listener method has a single argument as an object which is the subclass of EventObject class. For example, mouse event listener methods will accept instance of MouseEvent, where MouseEvent derives from EventObject. EventListner Interface It is a marker interface which every listener interface has to extend. This class is defined in java.util package. Class Declaration Following is the declaration for java.util.EventListener interface − public interface EventListener SWING Event Listener Interfaces Following is the list of commonly used event listeners. Sr.No. Class & Description 1 ActionListener This interface is used for receiving the action events. 2 ComponentListener This interface is used for receiving the component events. 3 ItemListener This interface is used for receiving the item events. 4 KeyListener This interface is used for receiving the key events. 5 MouseListener This interface is used for receiving the mouse events. 6 WindowListener This interface is used for receiving the window events. 7 AdjustmentListener This interface is used for receiving the adjustment events. 8 ContainerListener This interface is used for receiving the container events. 9 MouseMotionListener This interface is used for receiving the mouse motion events. 10 FocusListener This interface is used for receiving the focus events. Print Page Previous Next Advertisements ”;