Introduction to Servlets and Java EE, GJA 1 PDF

Document Details

FinerHydrangea

Uploaded by FinerHydrangea

Brno University of Technology

GJA

Tags

servlets java java ee web development

Summary

This document provides an introduction to servlets and the Java EE framework, outlining key course components and concepts, including lectures, midterm and final exam details, and project requirements.

Full Transcript

Introduction Lectures 2 hours a week Points Midterm test – 10 Team Project with defense – 39 (29 product, 5 documentation, 5 defense) Final exam – 51 (10 points for the oral part) Lower limits Team project – 10 Final exam – 20...

Introduction Lectures 2 hours a week Points Midterm test – 10 Team Project with defense – 39 (29 product, 5 documentation, 5 defense) Final exam – 51 (10 points for the oral part) Lower limits Team project – 10 Final exam – 20 Projects Web (and mobile) application for 5 students Fewer students possible after consultation. GJA 1 2 / 70 Course overview 1 Servlets, Java Server Pages 2 Maven, Testing and JAX (Java API for XML) 3 RMI (Remote Method Invocation) and JMS (Java Message Service) 4 EJB (Enterprise Java Beans) and Java Server Faces 5 PrimeFaces 6 Spring Midterm test 7 Lecture of an expert from practice 8 JPA (Java Persistence API), Hibernate 9 Google Web Toolkit 10 Android basics 11 Cloud 12 Advanced Android Project defenses GJA 1 3 / 70 Java EE and Jakarta EE 1998 – Sun started Java Professinoal Edition project. 1999 – Java 2 Platform Enterprise Edition (J2EE) was born. 2006 – J2EE was renamed to Java EE or Java Platform Enterprise Edition. 2017 – Oracle decided to give away the rights for Java EE to the Eclipse Foundation (the Java language is still owned by Oracle). the Eclipse Foundation legally had to rename Java EE, because Oracle has the rights over the “Java” brand. 2018 – community voted for the new name and picked Jakarta EE. GJA 1 6 / 70 Servlet containers and application servers Servlet containers Apache Tomcat http://tomcat.apache.org/ Eclipse Foundation Jetty http://www.eclipse.org/jetty/ Application servers Oracle GlassFish https://javaee.github.io/glassfish/ https://glassfish.org/ Payara Services Ltd Payara https://www.payara.fish/ – drop in replacement for GlassFish Red Hat WildFly (renamed from JBoss) http://wildfly.org/ IBM WebSphere Application Server https: //www.ibm.com/cloud/websphere-application-platform GJA 1 7 / 70 CGI Scripts CGI stands for “Common Gateway Interface”. CGI script is an external program, which is called by the webserver. So the webserver is the mediator between the client and application. It is necessary to run a new instance for each request (it is stateless). 1 Client sends a request to server. 2 Server starts a CGI script. 3 Script computes a result for the server and quits. 4 Server returns response to the client. 5 Another client sends a request. 6 Server starts the CGI script again. GJA 1 8 / 70 Servlets A servlet is a small Java program that runs within a Web server. Simply said it is a Java class. From specification: For a servlet not hosted in a distributed environment (the default), the servlet container must use only one instance per servlet declaration. However, for a servlet implementing the SingleThreadModel interface, the servlet container may instantiate multiple instances to handle a heavy request load and serialize requests to a particular instance. 1 Client sends a request to server. 2 Server starts a servlet. 3 Servlet computes a result for server and does not quit. 4 Server returns response to client. 5 Another client sends a request. 6 Server calls the servlet again. GJA 1 9 / 70 Servlets vs. CGI scripts Advantages Running a servlet doesn’t require creating a separate process each time. A servlet stays in memory, so it doesn’t have to be reloaded each time. There is only one instance handling multiple requests, not a separate instance for every request. It can keep context (session) in memory. Untrusted servlets can be run in a “sandbox”. Disadvantage More complicated configuration. GJA 1 10 / 70 Servlets A servlet is any class that implements the javax.servlet.Servlet or jakarta.servlet.Servlet interface. In practice, most servlets extends the javax.servlet.http.HttpServlet or jakarta.servlet.http.HttpServlet class (with built-in support for HTTP protocol). Some servlets extends javax.servlet.GenericServlet or jakarta.servlet.GenericServlet instead. Servlets usually lack a main method, but must implement or override certain other methods. GJA 1 11 / 70 Important servlet methods When a servlet is first started up, its init(ServletConfig config) method is called. init should perform any necessary initializations. init is called only once, and does not need to be thread-safe. Every servlet request results in a call of service(ServletRequest request, ServletResponse response). service calls another method depending on the type of service requested – e.g. doGet() or doPost(). Usually you would override the called methods of interest, not service itself. service handles multiple simultaneous requests, so service and the methods it calls must be thread safe. When the servlet is shut down, destroy() is called. destroy is called only once, but must be thread safe (because other threads may still be running). GJA 1 12 / 70 Servlet deployment Web archive ROOT/META-INF Contains deployment descriptors. Typically contains MANIFEST.MF ROOT/WEB-INF Can not be read by the client directly – can be used for storing of database password and other secrets. Actual program ROOT/WEB-INF/classes ROOT/WEB-INF/libs Configuration file web.xml stored in ROOT/WEB-INF Contains Filters Init and context parameters Servlet mapping Error handlers Alternatively configuration can be done by the annotations. GJA 1 13 / 70 Methods and configuration Init param (for given servlet) // web.xml controlServlet my.package.ControlServlet myParam paramValue // ControlServlet.java public void init(ServletConfig servletConfig) throws ServletException{ this.myParam = servletConfig.getInitParameter("myParam"); } Context param (for whole application) myParam the value String myContextParam = request.getSession().getServletContext().getInitParameter("myParam"); Load on startup By default the servlet is loaded when first requested. Can be loaded immediately after server start or deployment: 1 GJA 1 14 / 70 Configuration Filters Mostly predefined filters from libraries. Used for various aspects like logging, security, etc. Security mostly handled otherwise. MyFilter my.package.MyFilter MyFilter @Path("myresource") public class MyResource { @GET @Produces(MediaType.TEXT_PLAIN) public String getIt() { return "Got it!"; } } Examples JerseyHelloWorld, JerseyPath GJA 2 52 / 87 Form parameters @FormParam annotation Form submit needed @POST @Produces(MediaType.TEXT_HTML) @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public void newTodo(@FormParam("id") String id, @FormParam("summary") String summary, @FormParam("description") String description, @Context HttpServletResponse servletResponse) throws IOException { // method body servletResponse.sendRedirect("../index.html"); } Example JerseyCRUD GJA 2 53 / 87 Matrix parameters GET parameters separated by ; Call example../mapping;year=1234;country=CZ;author=Me @GET public Response getBooks(@MatrixParam("year") String year, @MatrixParam("author") String author, @MatrixParam("country") String country) { //method body return Response.status(200).entity("Jersey servlet called my method with following parametres - year : " + year + ", author : " + author + ", country : " + country).build(); } Example JerseyMatrix GJA 2 54 / 87 Path parameters Parameters separated by "/" Call example../mapping/2001/11/12 @GET @Path("{year}/{month}/{day}") public Response getUserHistory( @PathParam("year") int year, @PathParam("month") int month, @PathParam("day") int day) { String date = year + "/" + month + "/" + day; return Response.status(200).entity("Jersey servlet called my method with following parameters, year/month/day : " + date).build(); } Example JerseyPathParam GJA 2 55 / 87 File upload Jersey multipart InputStream with file data FormDataContentDisposition is optional @Context ServletContext servletContext; @POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.TEXT_PLAIN) public Response uploadFile( @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) { String fileName = fileDetail.getFileName(); String path = servletContext.getRealPath(fileName); // save it writeToFile(uploadedInputStream, path); String output = "File uploaded to : " + path + " and have " + Long.toString(fileDetail.getSize()) + "bytes"; return Response.status(200).entity(output).build(); } GJA 2 56 / 87 File download @Context ServletContext servletContext; @GET @Path("/get") @Produces("image/png") public Response getFile() { File file = new File(servletContext.getRealPath("image_on_server.png")); ResponseBuilder response = Response.ok((Object) file); response.header("Content-Disposition", "attachment; filename=image_on_server.png"); return response.build(); } Example JerseyUpload GJA 2 57 / 87 JAXB Java™ Architecture for XML Binding (JAXB) JSR 222 Object to XML mapping Root element specification @XmlRootElement Data object Return type specification MediaType.TEXT XML MediaType.APPLICATION XML MediaType.APPLICATION JSON Object is returned from response function. Object is automatically converted to return type specified by annotation. GJA 2 58 / 87 JAXB example @XmlRootElement public class Product { private String name; private double price; public Product() { } public Product(String name, double price) { this.name = name; this.price = price; }... } JAXBContext jc = JAXBContext.newInstance(Product.class); Marshaller m = jc.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); OutputStream os = new FileOutputStream("product.xml"); m.marshal(new Product("Káva", 20.5d), os); Unmarshaller u = jc.createUnmarshaller(); Object p = u.unmarshal(new File("product.xml")); GJA 2 59 / 87 References http://www.mkyong.com/tutorials/jax-rs-tutorials/ https://www.vogella.com/tutorials/REST/article.html https://eclipse-ee4j.github.io/jersey.github.io/ documentation/latest/getting-started.html https://docs.oracle.com/cd/F28299_01/pt857pbr3/eng/pt/tibr/ concept_UnderstandingRESTServiceOperations.html https://jcp.org/en/jsr/detail?id=339 https://allegro.tech/2014/10/async-rest.html https://www.jesperdj.com/2018/09/30/ jaxb-on-java-9-10-11-and-beyond/ GJA 2 60 / 87 JAX-WS Introduction Java™ API for XML-Based Web Services (JAX-WS) JSR 224 extends the existing JAX-RPC 1.0 specification with new features What are Web Services Services and clients communicates via XML Message or RPC oriented approach Web service operation invocation is represented by SOAP (Simple Object Access Protocol) SOAP messages (XML files) are sent via HTTP GJA 2 62 / 87 SOAP XML-based protocol Defines envelope structure encoding rules conventions for representing web service invocations and responses Web methods GET retrieves a representation of a resource. POST updates an existing resource or creates a new resource. PUT creates a new resource or modify an existing resource. DELETE removes the resources. Server side Java interface (created later by client as a proxy) defining methods of interface Client side create proxy call proxy methods (these are invoked on server) GJA 2 63 / 87 SOAP Message A SOAP message is an XML document containing the following elements: an Envelope element that identifies the XML document as a SOAP message a Header element that contains header information a Body element that contains call and response information a Fault element containing errors and status information GJA 2 64 / 87 SOAP Message E4-11-5B-F2-54-AA GJA 2 65 / 87 JAX-WS architecture Implementations Apache AXIS Glassfish Metro (reference implementation) GJA 2 66 / 87 JAX-WS Web Integration Glassfish Metro Endpoint specified in sun-jaxws.xml web.xml WSServletContextListener – listener class WSServlet – web service servlet @WebService @WebMethod GJA 2 67 / 87 sun-jaxws.xml GJA 2 68 / 87 web.xml Archetype Created Web Application com.sun.xml.ws.transport.http.servlet.WSServletContextListener hello com.sun.xml.ws.transport.http.servlet.WSServlet 1 hello /hello Example JAX-WS-Web GJA 2 69 / 87 JAX-WS Endpoints RPC (Remote Procedure Call) style web service endpoint Document style web service endpoint GJA 2 70 / 87 JAX-WS RPC style Synchronous Easy to implement SOAP engine takes care of marshalling Poor performance Interface annotation @WebService @SOAPBinding(style = Style.RPC) Implementation @WebService(endpointInterface = "package.Interface") Accessible on URL commonly named by package QName defines target service endpoint Communication via service port GJA 2 71 / 87 JAX-WS RPC example // Service Endpoint Interface @WebService @SOAPBinding(style = Style.RPC) public interface HelloWorld{ @WebMethod String getHelloWorldAsString(String name); } // Service Implementation @WebService(endpointInterface = "cz.vutbr.fit.knot.gja.ws.HelloWorld") public class HelloWorldImpl implements HelloWorld{ @Override public String getHelloWorldAsString(String name) { return "Hello World JAX-WS " + name; } } // Endpoint publisher public class HelloWorldPublisher{ public static void main(String[] args) { Endpoint.publish("http://localhost:9999/ws/hello", new HelloWorldImpl()); } } GJA 2 72 / 87 JAX-WS RPC example (2) It is possible to access deployed web service by accessing the generated WSDL (Web Service Definition Language) document via this URL http://localhost:9999/ws/hello?wsdl import javax.xml.namespace.QName; import javax.xml.ws.Service;... public class HelloWorldClient { public static void main(String[] args) throws Exception { URL url = new URL("http://localhost:9999/ws/hello?wsdl"); // 1st argument is service URI, refer to wsdl document above // 2nd argument is service name, refer to wsdl document above QName qname = new QName("http://ws.gja.knot.fit.vutbr.cz/", "HelloWorldImplService"); Service service = Service.create(url, qname); HelloWorld hello = service.getPort(HelloWorld.class); System.out.println(hello.getHelloWorldAsString("fit")); } } GJA 2 73 / 87 JAX-WS RPC example (3) Alternative, you can use wsimport tool to parse the published wsdl file, and generate necessary client files (stub) to access the published web service. wsimport -keep http://localhost:9999/ws/hello?wsdl import com.mkyong.ws.HelloWorld; import com.mkyong.ws.HelloWorldImplService; public class HelloWorldClient{ public static void main(String[] args) { HelloWorldImplService helloService = new HelloWorldImplService(); HelloWorld hello = helloService.getHelloWorldImplPort(); System.out.println(hello.getHelloWorldAsString("fit")); } } Example JAX-WS GJA 2 74 / 87 JAX-WS Document style Used for implementing asynchronous service More time consuming to create Large size documents processed without significant performance drop Better custom data type definition Interface annotation @WebService @SOAPBinding(style = Style.DOCUMENT, use=Use.LITERAL) SOAPBinding.Use.ENCODED – SOAP message contains data type information SOAPBinding.Use.LITERAL – SOAP message contains reference (namespace) to the schema that is used Otherwise similar as RPC GJA 2 75 / 87 JAX-WS Document example // Service Endpoint Interface @WebService @SOAPBinding(style = Style.DOCUMENT, use=Use.LITERAL) // optional public interface HelloWorld { @WebMethod String getHelloWorldAsString(String name); } // Service Implementation @WebService(endpointInterface = "cz.vutbr.fit.knot.gja.ws.HelloWorld") public class HelloWorldImpl implements HelloWorld{ @Override public String getHelloWorldAsString(String name) { return "Hello World JAX-WS " + name; } } // Endpoint publisher public class HelloWorldPublisher{ public static void main(String[] args) { Endpoint.publish("http://localhost:9999/ws/hello", new HelloWorldImpl()); } } GJA 2 76 / 87 JAX-WS Document example (2) Document style requires extra classes to run. You need to use wsgen tool to generate necessary JAX-WS portable artifacts. wsgen -keep -cp. cz.vutbr.fit.knot.gja.ws.HelloWorld It will generate two classes, copy it to your package.jaxws folder. Publish it and test it via URL http://localhost:9999/ws/hello?wsdl GJA 2 77 / 87 JAX-WS Document example (3) import javax.xml.namespace.QName; import javax.xml.ws.Service;... public class HelloWorldClient{ public static void main(String[] args) throws Exception { URL url = new URL("http://localhost:9999/ws/hello?wsdl"); QName qname = new QName("http://ws.gja.knot.fit.vutbr.cz/", "HelloWorldImplService"); Service service = Service.create(url, qname); HelloWorld hello = service.getPort(HelloWorld.class); System.out.println(hello.getHelloWorldAsString("fit")); } } Example JAX-WS-Document GJA 2 78 / 87 JAX-WS MTOM Message Transmission Optimization Mechanism Sending binary attachments Combines Base64 with SOAP File upload File download MIME types // Service Implementation Bean @MTOM @WebService(endpointInterface = "cz.vut.fit.knot.gja.ws.ImageServer") public class ImageServerImpl implements ImageServer{ @Override public Image downloadImage(String name) {... If the server WSDL advertises that it supports MTOM, the MTOM support in the client will be automatically enabled. Example JAX-WS-MTOM GJA 2 79 / 87 JAX-WS architecture GJA 2 80 / 87 Web Service handlers Client handlers intercept client calls to server injects authentication adds MAC, IP address,... Server interceptors retrieves information from SOAP header block authorizes client GJA 2 81 / 87 Client handler Create the client for the web service Create SOAP Handler Handler Configuration Handler Mapping Tracing the outgoing and incoming messages in success and failure case SOAPHandler interface public class MySOAPHandler implements SOAPHandler { @Override public boolean handleMessage(SOAPMessageContext messagecontext) { Boolean outbound = (Boolean) messagecontext.get( MessageContext.MESSAGE_OUTBOUND_PROPERTY);... SOAPMessage message = messagecontext.getMessage(); SOAPHeader header = message.getSOAPHeader(); SOAPBody body = message.getSOAPBody();... handleMessage returns true to continue processing, false to block processing. GJA 2 82 / 87 Client handler (2) Interceptor mapping specified in XML file @HandlerChain More mapping possible @WebServiceClient(name = "ServerInfoService", targetNamespace = "http://ws.gja.knot.fit.vutbr.cz/", wsdlLocation = "http://localhost:8888/ws/server?wsdl") @HandlerChain(file="handler-client.xml") public class ServerInfoService extends Service { //... } cz.vutbr.fit.knot.gja.ws.client.MacAddressInjectHandler GJA 2 83 / 87 Server handler Create Web Service Create SOAP Handler Handler Configuration Handler Mapping SOAPHandler interface SOAPMessageContext handleMessage returns true or false (chain may be broken) GJA 2 84 / 87 Server handler (2) Intercept mapping specified in XML file @HandlerChain More mapping possible @WebService @HandlerChain(file="handler-server.xml") public class Server{ @WebMethod public String getServerName() { return "localhost server"; } } cz.vutbr.fit.knot.gja.ws.server.MacAddressValidatorHandler Example JAX-WS-Handler GJA 2 85 / 87 References JAX-WS http://www.mkyong.com/tutorials/jax-ws-tutorials/ https://www.mkyong.com/webservices/jax-ws/ jax-ws-java-web-application-integration-example/ https://www.mkyong.com/webservices/jax-ws/ jax-ws-soap-handler-in-client-side/ https://www.mkyong.com/webservices/jax-ws/ jax-ws-soap-handler-in-server-side/ https://web.archive.org/web/20211023024040/http: //blog.jdevelop.eu/?p=67 https://javadoc.io/doc/org.glassfish.metro/ webservices-api/4.0.0/index.html https://docs.oracle.com/javaee/7/api/ https://jcp.org/en/jsr/detail?id=224 http://javainsimpleway.com/ jax-ws-basic-example-document-style/ SOAP https://www.w3.org/TR/soap12-part0/ https://www.w3schools.com/xml/xml_soap.asp https://www.ibm.com/support/knowledgecenter/en/ SSB27H_6.2.0/fa2ws_ovw_soap_syntax_lit.html GJA 2 86 / 87 Content RMI (Remote Method Invocation) JMS (Java Message Service) GJA 3 2 / 43 RMI RMI Remote method invocation Distributed Java TCP/IP transport layer Allow code that defines behavior and code that implements behavior to remain separate and to run on separate JVMs Part of JDK since Java 1.1 Code running on one JVM may call method on other JVM Client/Server architecture GJA 3 4 / 43 RMI protocols RMI uses a protocol called Java Remote Method Protocol JRMP is proprietary For increased interoperability RMI later used the Internet Inter-ORB Protocol (IIOP) IIOP is CORBA’s communication protocol using TCP/IP as the transport. CORBA is Common Object Request Broker Architecture language neutral protocol standard way to make method calls to remote objects PortableRemoteObject instead of UnicastRemoteObject -iiop parameter of the rmic compiler In JDK 11, the Java EE and CORBA modules were removed. These modules were deprecated for removal in JDK 9. RMI is all about remote calls at runtime. It’s not about compilation against a remote class. GJA 3 5 / 43 RMI architecture GJA 3 6 / 43 RMI features Simplifies communication with remote applications local method calls Supports security on both server and client side RMI layers Stub client side creates marshall stream from client requests demarshalling server response object references are accessible via stub Skeleton server side transforms marshall stream to method call GJA 3 7 / 43 RMI principles RMI uses proxy design pattern An object in one context is represented by another (the stub) in a separate context. The stub knows how to forward method calls between the participating objects. A naming or directory service is run on a well-known host and port number usually port 1099 RMI includes RMI registry which is actually a naming service may be created directly in java or by “rmiregistry” program available in JDK Stubs and skeletons are generated Static stubs and skeletons can be created by rmic program Deprecated Skeletons and stubs should be generated dynamically 5 ways, e.g. subclassing UnicastRemoteObject and calling it’s constructor (super()). GJA 3 8 / 43 RMI Registry The RMI registry is a simple server-side bootstrap naming facility that enables remote clients to obtain a reference to an initial remote object. It can be started with the rmiregistry command which produces no output and is typically run in the background. Before you execute rmiregistry, you must make sure that the shell in which you will run rmiregistry either has no CLASSPATH environment variable set or has a CLASSPATH that does not include the path to any classes that you want downloaded to clients of your remote objects. From JDK 7 Update 21, the RMI property java.rmi.server.useCodebaseOnly is set to true by default. When set to false, it allows one side of an RMI connection to specify a network location (URL) from which the other side should load Java classes. If it is set to true, classes are loaded only from preconfigured locations, such as the locally-specified java.rmi.server.codebase property or the local CLASSPATH, and not from codebase information passed through the RMI request stream. GJA 3 9 / 43 RMI naming Naming static class Bind // binds the specified name to a remote object List // returns an array of the names bound in the registry Lookup // returns a reference, a stub, for the remote object Rebind // rebinds the specified name to a new remote object Unbind // destroys the binding for the specified name LocateRegistry static class may create new registry naming methods are available UnicastRemoteObject also static class, which can export any object to be accessible on registry Extend it or use exportObject(Remote, PORT) GJA 3 10 / 43 Server implementation Shared proxy object public interface Message extends Remote { int add(int a, int b) throws RemoteException; } Shared proxy must be implemented public class MessageImpl extends UnicastRemoteObject implements Message { public MessageImpl() throws RemoteException { } @Override public int add(int a,int b) throws RemoteException { return a+b; } } Registry is created (if not already running) Registry registry = LocateRegistry.createRegistry(1099); Service is bind to given name // create a new service named myMessage registry.rebind("myMessage", new MessageImpl()); GJA 3 11 / 43 Client implementation Shared proxy object public interface Message extends Remote { int add(int a, int b) throws RemoteException; } Remote call Registry myRegistry = LocateRegistry.getRegistry("127.0.0.1", 1099); Message impl = (Message) myRegistry.lookup("myMessage"); System.out.println(impl.add(3, 5)); GJA 3 12 / 43 Server callback With RMI also server may initiate communication Communication object must implement proxy (which extends java.rmi.Remote) This object then may be referenced via stub Object export via UnicastRemoteObject Another JVM is running → use different port UnicastRemoteObject.exportObject(Remote,PORT) Asynchronous messages server is the origin of communication Example RMI GJA 3 13 / 43 RMI security SSL or any other mechanism may be used Initialize security manager System.setSecurityManager(new RMISecurityManager()); Applets typically run in a container that already has a security manager, so there is generally no need for applets to set a security manager. By default, the RMISecurityManager restricts all code in the program from establishing network connections. Naming doesn’t work by default (creating registry manually approach does) java -Djava.security.manager -Djava.security.policy= policy-file MyClass grant { permission java.net.SocketPermission "*:1024-65535", "connect"; } GJA 3 14 / 43 SecurityManager Package javax.security.manager Individual for every application Restricts what stubs can do resolve accept connect listen Host can be defined by following way host = (hostname | IPv4address | iPv6reference) [:portrange] portrange = portnumber | -portnumber | portnumber-[portnumber] GJA 3 15 / 43 References RMI http://docs.oracle.com/javase/tutorial/rmi/ http://docs.oracle.com/javase/7/docs/technotes/ guides/rmi/enhancements-7.html https://docs.oracle.com/javase/8/docs/api/java/ rmi/server/UnicastRemoteObject.html https://docs.oracle.com/en/java/javase/15/docs/ specs/rmi/index.html https://docs.oracle.com/en/java/javase/11/ migrate/index.html API https://docs.oracle.com/javase/8/docs/api/ https://docs.oracle.com/en/java/javase/15/docs/ api/index.html GJA 3 16 / 43 JMS JMS Java Message Service asynchronous message exchange between Java applications JMS implementations are called JMS providers. Different providers are not interoperable. Reliable delivery. Providers Open Message Queue (Part of GlassFish) JBossMQ / JBossMessaging (Red Hat) WebSphere MQ (IBM) ActiveMQ (Apache project) RabbitMQ (Pivotal Software) ZeroMQ (iMatix Corporation) GJA 3 18 / 43 Messaging domains P2P Point to point domain Each message has only one consumer. No timing (client 1 may send a message before client 2 is started, and yet message will be delivered). Each queue may have more senders. Only one receiver can process the message (only once). GJA 3 19 / 43 Messaging domains PubSub Publish-Subscribe domain Multiple publishers/subscribers Weak timing (no messages delivered before subscription) Durable subscriptions available (survive reboot) GJA 3 20 / 43 JMS architecture JMS is an interface specification Providers implement queues and topics Heavy use of JNDI (Java Naming and Directory Interface) Connection factories (Topic or Queue factory) Destinations (channels of communication) GJA 3 21 / 43 JMS programing model GJA 3 22 / 43 JMS programming model Connection factory managed by JMS provider TopicFactory QueueFactory Destination also managed by JMS provider Topic and Queue channels (and interfaces) configured on application server (not in application) Topic Many to many (PubSub) Queue Many to one (P2P) When message is retrieved, it is deleted from the queue. GJA 3 23 / 43 JMS model Session context to deliver and consume message created from connections (factories) lifecycle start and end defined Consumer and Producer created by sessions Session exists for each producer and consumer. GJA 3 24 / 43 JMS messages MapMessage for sending of key-value pairs also sending of objects MessageProducer producer = session.createProducer(queue); MapMessage m = session.createMapMessage(); m.setIntProperty("Id", 987654321); m.setStringProperty("name", "Widget"); m.setDoubleProperty("price", 0.99); List colors = new ArrayList(); colors.add("red"); colors.add("green"); colors.add("white"); m.setObject("colours", colors); Producer.send(m); Consumer receives MapMessage Object Getters getInt("key1") getString("key2") getObject("key3") getMapNames() GJA 3 25 / 43 JMS messages TextMessage simple string messages queueConnectionFactory = (QueueConnectionFactory) jndiContext.lookup("QueueConnectionFactory"); queue = (Queue) jndiContext.lookup("myQueue"); queueConnection = queueConnectionFactory.createQueueConnection(); queueSession = queueConnection.createQueueSession(false, Session.AUTO_ACKNOWLEDGE); QueueSender queueSender = queueSession.createSender(queue); TextMessage textMessage = queueSession.createTextMessage(); textMessage.setText("My message"); queueSender.send(textMessage); Receiver queueReceiver = queueSession.createReceiver(queue); textMessage = (TextMessage) queueReceiver.receive(); String message = textMessage.getText(); GJA 3 26 / 43 JMS messages ObjectMessage used to send serializable objects setObject(Serializable Object) getObject() StreamMessage for sending of binary primitives getABC, setABC where ABC is primitive java type (Integer, String,... ) It is possible to read different type than was written (conversion table exists). null can be dangerous Read is treated as calling the primitive’s corresponding valueOf(String) with a null value. char does not support a String conversion, attempting to read a null value as a char must throw a NullPointerException. GJA 3 27 / 43 JMS messages BytesMessage contains stream of uninterpreted bytes based on DataInputStream and DataOutputStream binary data Methods – corresponding read/write calls writeDouble writeBytes writeUTF readDouble readBytes readUTF... Example JMSP2P GJA 3 28 / 43 JNDI Java Naming and Directory Interface JMS is tightly coupled to JNDI Provider Queue name lookups an instance implementing the JNDI interface specification and services name lookups. returns answers to name lookup requests. Initial context starting point for name lookups Different providers need to be parametrized with different properties. GJA 3 29 / 43 JNDI Association associate name with object (create binding) Find locate object specified by the name Context set of bindings to object names similar to e. g. filesystem Naming system set of connected contexts LDAP (Lightweight Directory Access Protocol) Namespace all names in naming system for example all DNS names GJA 3 30 / 43 JNDI architecture Defines only interface for client accesses Common API for service providers JNDI SPI (service provider interface) allows to use different naming service providers Custom naming service may be developed by implementing JNDI SPI GJA 3 31 / 43 JNDI services Access to directory services through common API Directories are structured trees of informations Directory services LDAP (Lightweight Directory Access Protocol) DNS NIS (Network Information Service) (Oracle) NetWare Directory Services (NDS) Microsoft Active Directory IBM Lotus Notes/Domino Common Object Request Broker Architecture (CORBA) GJA 3 32 / 43 Message consumptions Asynchronous A client can register a message listener with a consumer. Whenever a message arrives at the destination, the JMS provider delivers the message by calling the listener’s onMessage() method. Synchronous A subscriber or a receiver explicitly fetches the message from the destination by calling the receive method. The receive method can block until a message arrives or can time out if a message does not arrive within a specified time limit. Examples jms-chat, JMSChat GJA 3 33 / 43 JMS features Additional features turned off by default Message acknowledgement Message priorities Persistent delivery mode Control of message expiration Durable subscriptions Message transactions GJA 3 34 / 43 Message acknowledgements In non-transacted sessions client receives the message message is processed acknowledgement is sent Acknowledgement modes Auto-acknowledgement An acknowledgement is sent after a successful return from receive function, or when listener successfully returns. Session.AUTO ACKNOWLEDGE Client acknowledgement Explicit call of message’s acknowledge method. Session.CLIENT ACKNOWLEDGE Lazy client acknowledgement reduces JMS overhead acknowledgment each time it has received a fixed number of messages, or when a fixed time interval has elapsed since the last acknowledgment (10 messages and 7 seconds) Broker does not acknowledge receipt of the client acknowledgment. You have no way to confirm that your acknowledgment has been received; if it is lost in transmission, the broker may redeliver the same message more than once, so duplicates may occur. Session.DUPS OK ACKNOWLEDGE GJA 3 35 / 43 Persistent delivery mode Persistent delivery mode default mode A message sent with this delivery mode is logged to stable storage when it is sent. Messages can survive provider crashes. Persistent delivery needs more performance. Persistent delivery needs more storage. Non persistent delivery mode does not require the JMS provider to store the message or otherwise guarantee that it is not lost if the provider fails may improve performance, but you should use it only if your application can afford to miss messages. Can be enabled using: producer.setDeliveryMode(DeliveryMode.NON PERSISTENT); GJA 3 36 / 43 Priorities, expirations Priorities 10 levels 0 – lowest priority 4 – default priority 9 – highest priority Queues and Topics may grow big producer.setPriority(7); Expiration By default, messages never expire. Expiration may be useful when using priorities. TTL may be set to every message in milliseconds. producer.setTimeToLive(10000); topicPublisher.publish(message, DeliveryMode.NON PERSISTENT, 8, 10000); GJA 3 37 / 43 Durable subscriptions, transactions Default subscriptions are non-persistent After each reboot the receiver must subscribe again. Messages that arrived during the reboot will not be delivered. Durable subscriptions are persistent After reboot the receiver do not need to subscribe again. Messages that arrived during reboot will be delivered after a new session is created. Subscription is not session In first case, messages M3 And M4 are not delivered. In second case, messages M2, M4, M5 are received when user starts new session. GJA 3 38 / 43 Transactions Transactions allows grouping of operations into an atomic unit of work. During rollback all produced messages are destroyed, consumed messages are recovered. Commit means that all messages are sent and consumed messages acknowledged. Transactions cannot be combined with request-reply mechanism. GJA 3 39 / 43 Transactions Rollback After rollback, all “buffered” messages are destroyed. Commit After commit, messages begins to be retrieved. GJA 3 40 / 43 ActiveMQ How to run the broker: 1 Download the distribution package from https:// activemq.apache.org/components/classic/download/ or from https://activemq.apache.org/components/ artemis/download/ 2 Run the broker (you can use command./activemq start in the bin directory in Linux or./artemis create../../testArtemis and then./artemis run in the testArtemis directory) Default URL of the broker is ActiveMQConnection.DEFAULT BROKER URL; or DefaultConnectionProperties.DEFAULT BROKER URL; GJA 3 41 / 43 References JMS Concepts https://docs.oracle.com/javaee/7/tutorial/ jms-concepts.htm JMS Examples https://docs.oracle.com/javaee/7/tutorial/ jms-examples.htm Tutorial https://www.javatpoint.com/jms-tutorial ActiveMQ https://activemq.apache.org/ https: //examples.javacodegeeks.com/enterprise-java/jms/ apache-activemq-hello-world-example/ Examples https://hantsy.medium.com/ kickstart-a-jakarta-ee-10-application-d579577af634 GJA 3 42 / 43 Contents EJB Introduction Session Beans Message Driven Beans (based on JMS) Transactions Deployment New features in EJB 3.1 GJA 4 3 / 67 EJB Enterprise JavaBeans (EJB) Enterprise bean is a server-side component that encapsulates the business logic of an application. EJB execute within an EJB container, which is running in the EJB server. GJA 4 4 / 67 EJB server EJB server is a part of an application server that hosts EJB containers can be also standalone (Apache TomEE) EJBs do not interact directly with the EJB server. GlassFish (Oracle), WebSphere (IBM), WebLogic (Oracle), WildFly (Red Hat), WebObjects (Apple),... EJB specification outlines eight services that must be provided by an EJB server: Naming Transaction Security Persistence Concurrency Life cycle Messaging Timer GJA 4 5 / 67 EJB Container EJB Container is a runtime environment for EJB component beans. Containers are transparent to the client. There is no client API to manipulate the container. Container provides EJB instance life cycle management and EJB instance identification. Container manages the connections to the enterprise information systems (EISs). Container provides services, such as transaction management, concurrency control, pooling (cache with beans) and security authorization. GJA 4 6 / 67 Multitiered Java EE Applications GJA 4 7 / 67 EJB Components EJB components are server-side, modular, reusable, and containing specific units of functionality. They are similar to the Java classes as we create every day, but are subject to special restrictions and must provide specific interfaces for container and client use and access. We should consider using EJB components for applications that require scalability, transactional processing, or availability to multiple client types. GJA 4 8 / 67 Enterprise Java Bean types Session Beans models task or workflow Façade for Entity beans structural design pattern – simplified interface to a larger set of interfaces. maintains conversational state with clients (one bean per client) Message Driven Beans asynchronous communication with MOM (Message Oriented Middleware) – distributed over heterogeneous platforms allows non-Java EE resources to access Session and Entity Beans via JCA (Java EE Connector Architecture – connects AS with EIS) Resource adapters uses JMS (Entity Beans 2.1) JPA 2.0 in Java EE 6 implicitly persistent transparent persistence with transaction support typically stored in a relational database (Object/Relational Mapping) Example guestbook-jee6 (Entity) GJA 4 9 / 67 Stateless Session Beans @Stateless annotation State only for the duration of a client invocation of a single method. Pool of stateless beans is managed by the container. Any available stateless session bean may handle the client request. Lifecycle event callbacks supported for stateless session beans (optional) @PostConstruct – occurs before the first business method invocation on the bean. @PreDestroy – occurs at the time the bean instance is destroyed. GJA 4 10 / 67 Stateless Session Beans @Stateless public class FooBean { @PostConstruct private void init() {...} @Remove public void remove() {} // removed from container } Example StatelessBean GJA 4 11 / 67 Stateful Session Beans Instance variables unique to the client/session. State is retained for the duration of the client/bean session. Client initiate creation and destruction (or timeout). Stateful Session Beans can not be pooled. Stateful Session Beans can be passivated. Supports following callbacks for the lifecycle events: @PostConstruct – same as stateless bean, once for each session. @Init – designates the initialization method of a bean. @PreDestroy – same as stateless, once for each session. @PrePassivate – container invokes this method right before it passivates a stateful session bean (clean up held resources, such as database connections or any resources that cannot be transparently passivated using object serialization). @PostActivate – container invokes this method right after it reactivates the bean. @Remove – called by container before it ends the life of the stateful session bean. Than invokes the bean’s PreDestroy method, if any. @AroundInvoke – interceptor method that interposes on business methods (one per class). GJA 4 12 / 67 Stateful Session Beans @Stateful public class FooBean { @PostConstruct private void init() {...} @Remove public void remove() {} } Example StatefullBean GJA 4 13 / 67 Singleton Session Beans Singleton Session Bean is a POJOs marked with @Singleton annotation, has only a single instance per JVM, supports data sharing and concurrent access, allows to set order of initialization (@DependsOn), initialization can be eager (@Startup). @Startup @Singleton(name = "PrimaryBean") @DependsOn("SecondaryBean") public class PrimaryBean {...} @Startup @Singleton(name = "SecondaryBean") public class SecondaryBean {...} GJA 4 14 / 67 Business interfaces Business interfaces visible to the client implemented inside the bean GJA 4 15 / 67 Local and Remote Interface Local Interface (@Local) invoking EJBs within the same JVM, faster, but not so flexible, scalable and adaptable, no network traffic, parameters passed by reference. Remote Interface (@Remote) invoking EJBs across JVMs, anywhere on the network, parameters passed by value (serialization/de-serialization). GJA 4 16 / 67 Local and Remote Interface @Stateless public class CalculatorBean implements CalculatorRemote, CalculatorLocal { public int add(int x, int y) { return x + y; } public int subtract(int x, int y) { return x - y; } } public interface Calculator { int add(int x, int y); int subtract(int x, int y); } @Remote public interface CalculatorRemote extends Calculator {} @Local public interface CalculatorLocal extends Calculator {} GJA 4 17 / 67 No-interface view New in EJB 3.1 EJB may not have business interface. Session Beans are simple POJO. Automatically exposes public methods. @Stateless public class FooBean { public void foo() {...} } It is not necessary to use @local or @remote (selected automatically). GJA 4 18 / 67 Message Driven EJB @MessageDriven annotation invoked asynchronously by messages from standard Session Beans, cannot be invoked with local or remote interfaces (from clients), stateless, transaction aware, JMS (Java Messaging Service) used as a transport layer, implements method onMessage(...). Two types of messaging: point-to-point (queues) pub-sub (topics) Example MessageDrivenBean (JDK 1.8) GJA 4 19 / 67 Types of EJB Session Beans Stateless Statefull Singleton Message Driven Beans Entity Beans GJA 4 20 / 67 Accessing Session Beans Clients never use “new” operator on managed beans. Session Beans are accessed using DI or JNDI. Dependency Injection only from clients in an Java EE environment other EJB, other managed beans, servlet,... during deployment of the bean to the container @EJB Foo fooBean; JNDI programming interface to the directory services to locate any object in a network even from non-EE clients access remote business interface Context ctx = new InitialContext(); FooRemote example = (FooRemote) ctx.lookup("java:global/myApp/FooRemote"); GJA 4 21 / 67 Dependency Injection Example public class Main { @EJB private static BookEJBRemote bookEJB; public static void main(String[] args) { // Creates an instance of Book Book book = new Book(); book.setTitle("The Hitchhiker’s Guide to the Galaxy"); book.setPrice(12.5F); book.setDescription("Science fiction by Douglas Adams."); book.setIsbn("1-84023-742-2"); book.setNbOfPage(354); book.setIllustrations(false); book = bookEJB.createBook(book); // business layer request book.setTitle("H2G2"); book = bookEJB.updateBook(book); // business layer request List books = bookEJB.findBooks(); // business layer // request System.out.println("List of books in DB:"); for (Book b : books) { System.out.println(b); } bookEJB.deleteBook(book); // business layer request } } GJA 4 22 / 67 JNDI names java:global[/]// [!] java:app// [!] java:module/ [!] Examples: java:global/fooEar/fooweb/FooBean java:global/fooEar/fooweb/FooBean!com.acme.Foo java:app/fooweb/FooBean java:app/fooweb/FooBean!com.acme.Foo java:module/FooBean java:module/FooBean!com.acme.Foo GJA 4 23 / 67 Calendar-based Timer Service Annotation @Schedule with attributes: year, month, dayOfMonth, dayOfWeek hour, minute, second timezone @Singleton public class ServiceBean { @Schedule(dayOfWeek = "Sun", hour = "2", minute = "30") public void cleanDatabase() {...} } GJA 4 24 / 67 Asynchronous Invocation Calls are synchronous by default. Methods can be invoked also asynchronously. Return value is a Future object of the java.util.concurrent @Stateless public class MathSessionBean { @Asynchronous public Future compute(Integer x, Integer y) { Integer z =... return new AsyncResult(z); } } Future r = mathBean.compute(20, 11); while (!r.isDone()) {... } Integer i = r.get(); GJA 4 25 / 67 EJB Transactions Container-managed (default) Container maintains persistence transparently using JDBC calls. @TransactionAttribute( TransactionAttributeType.REQUIRED) public void foo() {...} REQUIRED – if the transaction is running, it will be used, else it will be created. REQUIRES NEW – new transaction required. MANDATORY – transaction must be already running. NOT SUPPORTED – out of transaction. SUPPORTS – can be inserted into transaction, but will not be created. NEVER – can not be inserted into transaction. Rollback Exception is thrown. Transaction is marked for rollback and can never commit. @Resource SessionContext scx;... scx.setRollbackOnly(); Test if the transaction has been marked for rollback only: getRollbackOnly() GJA 4 26 / 67 EJB Transactions Bean-managed Programmer provides persistence logic. Used to connect to non-JDBC data sources like LDAP, mainframe, etc. GJA 4 27 / 67 EJB Transactions Bean-managed @TransactionManagement(TransactionManagementType.BEAN) class MyBean {... @Resource UserTransaction userTransaction;... userTransaction.begin();...... userTransaction.commit(); userTransaction.rollback();... } GJA 4 28 / 67 EJB Lite EJB Lite is a subset of the full EJB. EJB Lite can be a part of.war file. A Java EE Web Profile certified container has to support the EJB Lite. A subset of EJB Full no Message Driven Beans no remote interfaces no EJB timers and scheduling no asynchronous invocation no web services GJA 4 29 / 67 Embeddable Container Client and EJB runs on the same JVM. Better support for testing. Batch processing. Usage of EJB programming model in desktop applications. @Test public void hello() throws Exception { EJBContainer ec = EJBContainer.createEJBContainer(); Context c = ec.getContext(); HelloSessionBean hello = (HelloSessionBean) c.lookup( "java:global/classes/HelloSessionBean" ); String s = hello.sayHello( "Eva" ); assertEquals( "Hello, Eva", s ); } GJA 4 30 / 67 Contents of EJB Enterprise bean class Business interfaces Other classes Deployment descriptor (optional) GJA 4 31 / 67 Deployment Descriptors Deployment Descriptors are included in the JARs, along with component-related resources. Deployment Descriptors are XML documents that describe configuration and other deployment settings. The statements in the deployment descriptor are declarative instructions to the Java EE container (transactional settings,... ). The deployment descriptor for an EJB component must be named ejb-jar.xml, and it resides in the META-INF directory inside the EJB JAR files. It is also possible to configure it using annotations. GJA 4 32 / 67 References JSR-299 (CDI) http://docs.jboss.org/weld/reference/latest/en-US/html/ Java EE 6 Tutorial https://docs.oracle.com/javaee/6/tutorial/doc/ Jakarta EE Tutorial https: //eclipse-ee4j.github.io/jakartaee-tutorial/ Oracle R Containers for J2EE Enterprise JavaBeans Developer’s Guide https: //docs.oracle.com/cd/E16439_01/doc.1013/e13981/toc.htm Programming WebLogic Enterprise JavaBeans https://docs.oracle.com/cd/E13222_01/wls/docs81/ejb/ session.html Simplify enterprise Java development with EJB 3.0, Part 1 https://www.infoworld.com/article/2159164/java-web- development-simplify-enterprise-java-development-with- ejb-3-0-part-1.html GJA 4 33 / 67 References Distributed Multitiered Applications – Tiers https://docs.oracle.com/javaee/6/tutorial/doc/ bnaay.html The Open Tutorials - Java EE https://ibytecode.com/blog/category/java-ee/ejb3/ https://ibytecode.com/blog/servlet-datasource-resource- injection-in-tomcat/ https://ibytecode.com/blog/apache-cxf-restful-web- service-example/ Stateful session beans (EJB 3) http: //vkpedia.com/sandbox/files/EJB%203%20in%20Action.pdf Others https://access.redhat.com/solutions/158153 GJA 4 34 / 67 Contents Introduction Creating pages and backing beans (dynamic binding with EL) Defining navigation JSF Lifecycle Data Conversion and Validation Events Other frameworks (PrimeFaces) Conclusions GJA 4 36 / 67 Introduction JavaServer Faces (JSF) application framework for creating Web-based user interfaces component-based provides standard set of components transparently saves and restores component state event handling, server side validation, data conversion framework for implementing custom components based on Model-View-Controller (MVC) running in the standard web container (e.g. Tomcat or Jetty) GJA 4 37 / 67 JSF application JSF tags in a Java Server Pages (JSP) files (.jsp) or in facelets (.xhtml) defines the layout of JSF components Backing beans (.java) JavaBeans components, defines properties and functions for UI components on a page Configuration resource files (web.xml, faces-config.xml) navigation, configuration of backing beans, custom components, deployment descriptor Custom objects (.java) Custom UI components, validators, converters, listeners Custom tag library definition (.xml) GJA 4 38 / 67 JSF Architecture GJA 4 39 / 67 JSF Lifecycle JSF manages components’ state GJA 4 40 / 67 1. (Re)Constitute component tree ID of the view is extracted from the request (name of the page). Component tree for the current view is created. Two possibilities initial request build a view of the page (ui components), event handlers, validators,... postback form was sent restore view from state information (server or client) GJA 4 41 / 67 2. Apply Request Values Every component retrieves current state. Calls the decode method on component renderer set component values, queue events, messages values from request (headers, cookies, form data) If any decode methods / event listeners called renderResponse on the current FacesContext instance, the JSF moves to the render response phase. Values are converted from strings and set into instances of UI component classes. GJA 4 42 / 67 3. Process events, validations Queued events processed after Apply Request Phase. Processes all validators registered on the components in the tree validators may setValid(false) error message added to FacesContext if any validation error, skip to Render Response phase otherwise, continue to the Update Model Values Phase. If the local value is invalid, the JSF adds an error message to the FacesContext instance, and the life cycle advances to the Render Response phase and display the same page again with the error message. FacesContext contains objects on the page. GJA 4 43 / 67 4. Update Model Values Updates values of the model (properties of the managed beans). Conversion errors may happen. If any updateModels methods or any listeners called renderResponse on the current FacesContext instance, the JSF moves to the Render Response phase. GJA 4 44 / 67 5. Invoke Application Handles any application-level events, such as submitting of a form or linking to another page. Application may define a next view action event (form submission). default ActionListener handles the “action” result and passes to NavigationHandler. Value of action in UICommand is compared with the rules in the faces-config.xml. GJA 4 45 / 67 6. Render Response Phase JSP or facelet container will render the page JSF tag handlers will setup rendering of the components. User can see the result. After the content of the view is rendered, the response state is saved so that subsequent requests can access it and it is available to the restore view phase. Tags and (for errors, etc.) GJA 4 46 / 67 JSF Lifecycle GJA 4 47 / 67 JSF Technology JSF UI Components basic building blocks of a JSF application can represent simple to complex user interface components ranging from a button or input field to a complete page can be associated to Model data objects through Value Binding usage of EL (${...} and #{...}) UI Components use helper objects: validators, converters, listeners/events GJA 4 48 / 67 User Interface Component Classes JSF components have two parts Component (Java Class) Renderer (JQuery) Displaying of component Direct implementation (component encodes/decodes itself) Delegated implementation (encoding/decoding delegated to Renderer – used for extensions) UIComponent form a tree, instance of UIViewRoot class is the root hold state (interface StateHolder), registers listeners,... UI Component classes UIViewRoot, UIForm UIOutput, UIInput UICommand UISelectMany, UISelectOne, UISelectItem UIData, UIColumn UIPanel Example JSFTutorial GJA 4 49 / 67 Component rendering Renderer JSF tree to HTML (XUL, SVG,... ) Renderkit set of renderers with same output format multiple renderers for one component UICommand – commandLink, commandButton UISelectOne – selectOneListbox, selectOneMenu, selectOneRadio defined in tag library Component tags outputText, inputText, inputTextarea, inputHidden, inputSecret,... Component tag attributes id: unique id of the component immediate: events, validation, conversion should happen in the “apply request phase” – use this attribute to skip validation in case of Cancel button is clicked. rendered: do not render if set to false value: binds the value to some backing bean property binding: binds the instance to some backing bean property (whole component!) style styleClass GJA 4 50 / 67 Creating pages JSP pages with JSF tag library View is a tree of JSF components Editable components inside a “form” component GJA 4 51 / 67 Backing beans Usually one managed bean per page. Backing beans defines properties and methods associated with UI components. Component value to bean property binding defined in JSF page using Unified Expression Language (EL) class SigninBean { private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } public String signin() {... if (ok) { return "success"; } else { return null; } } } GJA 4 52 / 67 JSF Managed Beans JSF Managed Beans works as Model for UI component, can be acessed from JSF page, contains getters, setters (like backing bean), Backing bean contains all the HTML form values, managed not. registered through annotations @ManagedBean(name="helloWorld", eager=true) eager=true – created before requested, otherwise lazy Scopes @RequestScoped, @NoneScoped, @ViewScoped, @SessionScoped, @ApplicationScoped, @CustomScoped @NoneScoped created on every single EL expression referencing the bean. @ManagedProperty annotation Bean can be injected to another managed bean. GJA 4 53 / 67 JSF Managed Beans From JSF 2.2 it is highly recommended to use CDI (Contexts and Dependency Injection). @ManagedBean is deprecated @Named (jakarta.inject.Named) can be used instead eager = true needs extension https://ovaraksin. blogspot.com/2013/02/eager-cdi-beans.html javax.faces.bean.SessionScoped is deprecated jakarta.enterprise.context.SessionScoped can be used instead similar for other scopes (e. g. jakarta.enterprise.context.ApplicationScoped) GJA 4 54 / 67 Page navigation Page navigation is defined in faces-config.xml file can be defined in managed beans implicit navigation set of navigation rules from-view-id (optional) navigation-case from-outcome – outcome as defined in JSF page or as returned by action method It is also possible to return page name directly, but it is not recommended. Use to switch view and redirect (change URL) instead of forward (internal forwarding – same URL). /index.jsp success /home.jsp Example JSFPageNavigation GJA 4 55 / 67 Conversion Value of a component can be bound (not same as binding) to a backing bean property. Conversion to some types is automatic e.g. UISelectBoolean to boolean or java.lang.Boolean Converter Classes BigDecimalConverter, IntegerConverter, DoubleConverter,... DateTimeConverter style full, short, medium, long pattern MM dd yyyy“ ” Can be created also for custom objects. GJA 4 56 / 67 Conversion Custom converters interface Converter Object getAsObject(FacesContext, UIComponent, String) String getAsString(FacesContext, UIComponent, Object) f:converter registered converter binding attribute Converter registration in faces config com.example.MyClass com.example.MyConverter GJA 4 57 / 67 Validation Validates components data, produces an error message. Standard validators validateDoubleRange, validateLength, validateLongRange Custom validation public void validateFoo(FacesContext context,UIComponent toValidate, Object value) {... ((UIInput)toValidate).setValid(false); } or implement a Validator interface (method validate() throws ValidatorException) and register a validator in faces-config... GJA 4 58 / 67 Event and Listener Action events clicking on buttons or links public void bar(ActionEvent event); sets target property of backing bean (e.g. on click) Value change event user changes the value of a UIInput component f:valueChangeListener tag type – name of the class that implements ValueChangeListener interface binding – EL expression which evaluates to bean instance of class implementing ValueChangeListener Data model event (interface DataModelListener) new row of a UIData is selected Examples JSFActionListener, JSFActionListenerCDI and JSFEventListeners GJA 4 59 / 67 Using UIData h:dataTable value - EL expression which evaluates to: list/array of beans, jakarta.faces.model.DataModel, java.sql.ResultSet, javax.sql.RowSet,... var – name of the variable which iterates through the DataModel first, rows,... GJA 4 60 / 67 Custom components UIComponent subclass UIComponentBase behavioral interfaces StateHolder, ValueHolder, NamingContainer, EditableValueHolder, ActionSource component family Renderer encodeBegin (before descendants) encodeEnd (after descendants) decode (state from request) Tag abstract class UIComponentELTag (values from EL API) UIComponentBodyELTag (processing of tag body) getComponentType, getRendererType sets the component properties based on attributes Example JSFCustomComponent GJA 4 61 / 67 JSF AJAX Using AJAX technique, JavaScript code exchanges data with server and updates parts of web page without reloading of the whole page (partial rendering). JSF Tag Tag attributes disabled event (what events invokes AJAX – blur, keypress, click,...) execute (processed components – @all) immediate (True – action attribute evaluated in apply request values / False – action attribute evaluated in invoke application phase) listener – what should be called during AJAX request (on the server) oneerror – name of JavaScript function, when error in AJAX occurs onevent – JavaScript callback to handle UI event render – what should be rendered Example JSFAjax GJA 4 62 / 67 Frameworks on top of JSF Apache MyFaces Implementation of JSF with additional components UI-Component Sets Trinidad Tobago ICEFaces (ICEsoft Technologies) and RichFaces (Red Hat) AJAX components without writing JavaScript code skinable Menus, Trees, Calendar, File Upload, Drag and Drop, Google Maps,... Rich text editor TinyMCE in RichFaces CKEditor in ICEFaces PrimeFaces (PrimeTek Informatics) Others GJA 4 63 / 67 Conclusion JavaServer Faces is a standard EE component based framework. JSF by default uses JSP for rendering, provides basic HTML-based components (facelets are replacing JSPs). Managed beans as backing beans for pages defines properties and methods. View state is stored between requests. Rich frameworks on top of JSF. GJA 4 64 / 67 References JSF http://www.tutorialspoint.com/jsf/ API http://docs.oracle.com/javaee/6/api/ https: //jakarta.ee/specifications/platform/10/apidocs/ https: //eclipse-ee4j.github.io/jakartaee-tutorial/ Others https://www.mkyong.com/jsf2/jsf-page-forward-vs- page-redirect/ https://jakarta.ee/xml/ns/jakartaee/#10 GJA 4 65 / 67 Appendix – parameter encoding GlassFish AS have deployment descriptor glassfish-web.xml (see documentation) For correct reading of the form values with diacritic, it is necessary to set: GJA 4 66 / 67 Introduction JSF doesn’t provide rich set of components It is left for 3rd party libraries PrimeFaces rich set of components uses JQuery library for custom components AJAX support (based on JSF 2.0) push support via Atmosphere framework (WebSocket/Comet) In 7.0 Push has been removed. Please use the JSF 2.3 socket or OmniFaces now. one-jar library, no configuration nor dependencies lots of built-in themes, visual theme designer tool Old versions ThemeRoller https://jqueryui.com/themeroller/ Theme Designer https://www.primefaces.org/designer-jsf/ New Theme Designer in Q4/2024? extensive documentation XHTML facelets on client combined with Java on the server side GJA 5 3 / 45 Content PrimeFaces Theming concept Inputs and selects Client side validations Panels Data iteration components Menus Dialog framework Working with files and images Drag & Drop Charts Push RequestContext (PrimeFaces.current()) GJA 5 4 / 45 Theming concept Themes 3 free built-in themes 8 premium themes 29 built-in SAAS themes 37 community themes Configuration (web.xml) primefaces.THEME aristo May be dynamic primefaces.THEME #{loggedInUser.preferences.theme} GJA 5 5 / 45 Custom theme Custom theme must be present in one.jar file. mandatory structure.jar – META-INF – resources – primefaces-yourtheme – theme.css – images Image adressing url("images/my_image.png") must be changed to url("#{resource[’primefaces-yourtheme:images/my_image’]}") GJA 5 6 / 45 Predefined selectors Selector Description.ui-widget All PrimeFaces components.ui-widget-header Header section of a component.ui-widget-content Content section of a component.ui-state-default Default class of a clickable.ui-state-hover Class applied when cursor is over widget.ui-state-active When clickable is activated.ui-state-disabled Disabled elements.ui-state-highlight Highlighted elements.ui-icon An element to represent an icon GJA 5 7 / 45 Inputs and selects Input mask minimizes the chances for the user to input incorrect data a kind of regular expressions 9 is used as a pattern for 0 – 9 Input language kind of regular expressions for validating input asterisk for multiple occurrence question mark for optional occurrence GJA 5 8 / 45 Inputs and selects Autocomplete method complete takes a string and returns a List Autocomplete event public void handleSelect(SelectEvent event) { Object selectedObject = event.getObject(); MessageUtil.addInfoMessage("selected.object", selectedObject); } Every input component can fire appropriate AJAX events when they occur. Example PFInput GJA 5 9 / 45 Other input elements InputTextArea events/attributes: onkeyup, onfocus, onblur,... TextEditor rich text editing features (https://quilljs.com/) SelectManyCheckBox used to choose multiple items from a collection Calendars multiple display modes Spinner boundaries Slider it is possible to set min/max value, step, range,... vertical or horizontal... Examples PFEvents, PFBasicLayout, PFCalendar GJA 5 10 / 45 Partial processing Partial processing allows updating JSF components with AJAX. Partial processing speeds up large form processing. Partial rendering defines elements to be updated. Partial validations may prevent unwanted validations... Example PrimePartialProcessing GJA 5 11 / 45 Partial processing Search expression framework Keyword Type Description @this Standard Current component @all Standard Whole view @form Standard Closest ancestor form @none Standard No component @namingcontainer PrimeFaces Closest ancestor naming container @parent PrimeFaces Parent of the current component @composite PrimeFaces Closest composite component ancestor @child(n) PrimeFaces Nth child @previous PrimeFaces Previous sibling @next PrimeFaces Next sibling @widgetVar(name) PrimeFaces Component with given widget variable GJA 5 12 / 45 Client side validations Validations must be compatible with server side implementation. Conversion and validation happens at client side. Partial process&update support for AJAX. i18n support along with component specific messages. Client side renderers for message components. Easy to write custom client converters and validators. Global or component based enable/disable. Advanced bean validation integration. Little footprint using HTML5. GJA 5 13 / 45 Validations Client side validations are disabled by default, has to be enabled in configuration (web.xml) primefaces.CLIENT_SIDE_VALIDATION true Non-AJAX In non-AJAX case, all visible and editable input components in the form are validated and message components must be placed inside the form. AJAX partial processing and updates Custom validation implementing client validation interface method validate() Example PFValidations GJA 5 14 / 45 Validations Bean validation constraints via annotations public class Bean { @Size(min=2,max=5) private String name; @Min(10) @Max(20) private Integer age; } growl is used for messages (in the top right corner) GJA 5 15 / 45 Messages Messages components are used to display FacesMessages. Severity: Info, Warn, Error or Fatal. Messages can indicate errors in the forms.... FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_FATAL, "Fatal!", "System Error")); Examples PFMessages GJA 5 16 / 45 Panels Panels serves as containers for storing of other widgets. Panel is a generic component. toggling closing built-in pop-up menu AJAX listeners Panel grid support for colspan and rowspan. Dynamic content loading Tabs can be lazily loaded based on a value of underlying JavaBean. Dynamic tabbing AccordionPanel Example PFAccordion GJA 5 17 / 45 Panels Overflow content ScrollPanel Buttons grouping toolbars, separators Draggable widgets DashBoard panel grid with row and columns constraints Element layout (Primefaces < 10.0) at element level, styled with CSS Layout component was removed in PrimeFaces 10.0 in favor or pure CSS. PF Extensions still has a similar Layout component. Full Page layout (Primefaces < 10.0) North, West, Center, East, South In PrimeFaces 10.0 can be replaced by PF Extensions Panels can fire appropriate events close, toggle, resize Examples PFFullPageLayout GJA 5 18 / 45 Data iteration components Data iteration components are usually data tables or trees. Selection selection mode (single or multiple)... property listeners Selected object is referenced as a variable and can be passed to underlying Java method. Example PFDataTable GJA 5 19 / 45 Data iteration components Sorting and filtering in DataTable Sorting Filtering displays filter text fields user filters the data all fields can be searched GJA 5 20 / 45 Data iteration components In cell editing AJAX events Lazy models – handling lots of records supports pagination org.primefaces.LazyDataModel Programmer must implement load, getRowData and getRowKey methods. Example PFTableCell GJA 5 21 / 45 Data iteration components Trees and TreeTables Events collapse, expand, select, unselect Context menu support GJA 5 22 / 45 Menus Menu positioning static displayed in page by default dynamic overlay, not displayed by default defines trigger button, position relative to that button Programmatic menu Menu can be defined also in Java Model object returns constructed menu. Context menu Example PFMenu, PFContextMenu GJA 5 23 / 45 Menus Other menus Menubar displays root items horizontally and nested items as tiered for static menus MegaMenu multi-column menu displays submenus of root items together TieredMenu submenus in nested overlays PanelMenu hybrid of accordion-tree SlideMenu displays nested submenus with a slide animation SelectCheckBoxMenu menu with checkboxes which are on or off Example PFMenuBar GJA 5 24 / 45 Dialogs Simple dialogs

Use Quizgecko on...
Browser
Browser