Jee Ag

  • Uploaded by: Aleksandar Vulic
  • 0
  • 0
  • February 2021
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Jee Ag as PDF for free.

More details

  • Words: 2,398
  • Pages: 20
Loading documents preview...
PROJEKAT: + DVDItem model

package com.zdvd.model; import java.io.Serializable; /** * * @author ghagos */ public class DvdItem implements Serializable { private String title; private String year; private String genre; public DvdItem(String title, String year, String genre) { this.title = title; this.year = year; this.genre = genre; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public String getGenre() { return genre; } public void setGenre(String genre) { this.genre = genre; } }

+ VIEW

Class Name: ListLibraryServlet Project: DVDLibrary Location: Source Packages Package: com.dvd.view Add information to the deployment descriptor (web.xml): Check Servlet Name: ListLibraryServlet URL Pattern(s): /list_library.view Initialization Parameters: None

--- U WEB.XML mora se podesiti ime servleta I gde se u paketu nalazi, I za mapiranje (url koji odredjeni view treba da pokaze I ime servleta koji vraca response na view):

<servlet> <servlet-name>ListLibraryServlet <servlet-class>com.dvd.view.ListLibraryServlet

<servlet-mapping> <servlet-name>ListLibraryServlet /list_library.view

package com.zdvd.view; import com.zdvd.model.DvdItem; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;

/** * * @author ghagos */ public class ListLibraryServlet extends HttpServlet { /** * Processes requests for both HTTP GET and POST * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { List dvdList = (ArrayList) request.getServletContext().getAttribute("dvdList"); out.println(""); out.println(""); out.println(""); out.println("Servlet ListLibraryServlet"); out.println(""); out.println(""); out.println("

Servlet ListLibraryServlet at " + request.getContextPath() + "

"); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); for (DvdItem dvdItem : dvdList) { out.println(""); out.println("" + "" + ""); out.println(""); } out.println(""); out.println("
TitleYearGenre
" + dvdItem.getTitle() + "" + dvdItem.getYear() + "" + dvdItem.getGenre() + "
"); out.println("Home"); out.println(""); out.println("");

} } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP GET method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP POST method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// }

+ addDVD Servlet:

package com.zdvd.controller; import com.zdvd.model.DvdItem; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author ghagos */ public class AddDVDServlet extends HttpServlet { /** * Processes requests for both HTTP GET and POST * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String title = (String) request.getParameter("title"); String year = (String) request.getParameter("year"); String genre = (String) request.getParameter("genre"); String newgenre = (String) request.getParameter("newgenre"); if (newgenre != null && newgenre.length() != 0) { genre = newgenre; } List<String> errors = new ArrayList<>(); if (title == null || title.length() == 0 ) { errors.add("Title cannot be empty."); }

if (year == null || year.length() == 0) { errors.add("Year cannot be empty."); } RequestDispatcher rd; if (errors.isEmpty()) { DvdItem dvdItem = new DvdItem(title, year, genre); request.setAttribute("dvdItem", dvdItem); rd = (RequestDispatcher) request.getRequestDispatcher("success.view"); rd.forward(request, response); } else { request.setAttribute("errors", errors); rd = (RequestDispatcher) request.getRequestDispatcher("adddvd.view"); rd.forward(request, response); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP GET method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP POST method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /**

* Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// }

+ InitializeLibrary ()

package com.zdvd.web; import com.zdvd.model.DvdItem; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /** * * @author getachew */ public class InitializeLibrary implements ServletContextListener{ @Override public void contextInitialized(ServletContextEvent sce) { InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; try { List dvdList = new ArrayList<>(); ServletContext context = sce.getServletContext(); String dataFile = context.getInitParameter("library-file"); is = context.getResourceAsStream(dataFile);

isr = new InputStreamReader(is); br = new BufferedReader(isr); String line; while ((line = br.readLine()) != null) { String[] elements = line.split("\\|"); String title = elements[0]; String year = elements[1]; String genre = elements[2]; dvdList.add(new DvdItem(title, year, genre)); } sce.getServletContext().setAttribute("dvdList", dvdList); // throw new UnsupportedOperationException("Not supported yet."); } catch (IOException ex) { Logger.getLogger(InitializeLibrary.class.getName()).log(Level.SEVERE, null, ex); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { Logger.getLogger(InitializeLibrary.class.getName()).log(Level.SEVERE, null, ex); } } if (isr != null) { try { isr.close(); } catch (IOException ex) { Logger.getLogger(InitializeLibrary.class.getName()).log(Level.SEVERE, null, ex); } } if (br != null) { try { br.close(); } catch (IOException ex) { Logger.getLogger(InitializeLibrary.class.getName()).log(Level.SEVERE, null, ex); } } } } @Override public void contextDestroyed(ServletContextEvent sce) { throw new UnsupportedOperationException("Not supported yet."); } }

+ AddFormServlet

package com.zdvd.view; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * * @author GHagos */ public class AddDVDFormServlet extends HttpServlet { private String [] genres; @Override public void init() throws ServletException { String temp = getInitParameter("genre-list"); if (temp != null && temp.length() != 0) { genres = temp.split(","); } super.init(); } /** * Processes requests for both HTTP GET and POST * methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { /* TODO output your page here. You may use following sample code. */ ArrayList<String> errors = (ArrayList) request.getAttribute("errors");

out.println(""); out.println(""); out.println(""); out.println("Servlet AddDVDFormServlet"); out.println(""); out.println(""); out.println("

Servlet AddDVDFormServlet at " + request.getContextPath() + "

"); if (errors != null && !errors.isEmpty()) { out.println("Please correct the following error(s):"); for (String error : errors) { out.println("
  • " + error + "
  • "); } out.println("
    "); } out.println("
    "); String title = request.getParameter("title"); String year = request.getParameter("year"); String newgenre = request.getParameter("newgenre"); String genre = request.getParameter("genre"); out.println("
    "); out.println("Title:
    "); out.println("Year:
    "); out.println("Genre: "); out.println("<select name=\"genre\">"); for (String g : genres) { out.println(""); } out.println(" "); out.println("or New Genre:

    "); out.println(""); out.println("
    "); out.println(""); out.println(""); } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP GET method.

    * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP POST method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// }

    TEORIJA + servlet

    1 package sl351.m1; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 import javax.servlet.ServletException; 6 import javax.servlet.annotation.WebServlet; 7 import javax.servlet.http.HttpServlet; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 11 12 @WebServlet(name="HelloServlet", urlPatterns={"/HelloServlet"}) 13 public class HelloServlet extends HttpServlet { 14 15 @Override 16 protected void doGet(HttpServletRequest request,

    17 HttpServletResponse response) 18 throws ServletException, IOException { 19 response.setContentType("text/html;charset=UTF­8"); 20 PrintWriter out = response.getWriter(); 21 try { 22 out.println(""); 23 out.println(""); 24 out.println("HelloServlet"); 25 out.println(""); 26 out.println(""); 27 out.println("

    HelloServlet says \"Hello, World!\"

    "); 28 out.println(""); 29 out.println(""); 30 } finally { 31 out.close(); 32 } 33 } 34 }

    + jsp stranica <%­­ 2 Simple Hello World JSP example 3 ­­%> 4 5 <%@page contentType="text/html" pageEncoding="UTF­8"%> 6  8 9  10  11 <meta http­equiv="Content­Type" content="text/html; charset=UTF­8"> 12 JSP Page 13  14  15 

    <%= "Hello World! I'm a JSP, it is " + new java.util.Date() %>

    16  17 

    When a browser submits a form, the request commonly includes parameters, that is, data provided by the user. These parameters are available to a servlet through the getParameter method of the request variable 1 

    2  3 <meta http­equiv="Content­Type" 4 content="text/html; charset=UTF­8"> 5 JSP Page 6  7  8 

    Hello 9 <%= request.getParameter("customerName") %> 10 

    11  12  ­ The mechanism used to invoke the JSP page is called forwarding. Code to

    perform this is shown below.  RequestDispatcher rd = request.getRequestDispatcher("view.jsp");  rd.forward(request, response); Notice that the forwarding is done in two parts. 1. RequestDispatcher object is created by the request. The RequestDispatcher is configured on creation to transfer control to a page called “view.jsp”. - Next, the RequestDispatcher is used to pass the original request and response objects into the new page for processing.

    2. Attribute map:

    ServletRequest.getAttribute(String key) ServletRequest.setAttribute(String key, Object value) Using this map, the controller servlet can send data to the view JSP. So, if a controller servlet writes a data item into an attributed using the following code: request.setAttribute("aValue", 99); Then the value can be read in a JSP page using this syntax: ${aValue}

    *************** primer *************: 

    @WebServlet(name="FullControllerExample", urlPatterns={"/FullControllerExample"}) public class FullControllerExample extends HttpServlet { @Override  protected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {  RequestDispatcher rd = request.getRequestDispatcher("fullView.jsp");    ExampleModel model = new ExampleModel();  String name = request.getParameter("name");  if (name == null) {    name = "Secret";  }   model.setName(name);   request.setAttribute("model", model);   rd.forward(request, response);  } } Code 3-1 The Controller Servlet

      package sl314.m3;    public class ExampleModel {        private String name;     

       public void setName(String s) {      name = s;    }    public String getName() {      return name;    }      public int getNameLength() {      return name.length();    } } Code 3-2 The Model

      <%@page isELIgnored="false"%>   <%@page contentType="text/html" pageEncoding="UTF­8"%>              <meta http­equiv="Content­Type" content="text/html; charset=UTF­8">   A View Built With A JSP             

    Name information

           The name of the user is ${model.name}.        That name contains ${model.nameLength} characters.       Code 3-3 The View JSP

    + HTTP Method Description OPTIONS Request for the communication options

    available on the request/response chain GET Request to retrieve information identified by the Request-URL HEAD Identical to the GET except that it does not return a message-body, only the headers POST Request for the server to accept the entity enclosed in the body of the HTTP message PUT Request for the server to store the entity enclosed in the body of the HTTP message DELETE Request for the server to delete the resource identified by the Request-URI TRACE Request for the server to invoke an application-layer loop-back of the request message CONNECT Reserved for use with a proxy - PRIMER FORME, INPUTA I SUBMITA: 6 7  8 9  10  11  12 

    Duke’s Soccer League: Add a New League

    13  14  15 16 

    17 This form allows you to create a new soccer league. 18 

    19 20  21 Year:  

    22 Season: <select name=’season’> 23 select... 24 Spring 25 Summer

    26 Fall 27 Winter 28  

    29 Title:  

    30  31  32 33  34 

    + SESIJE:

    Storing Session Attributes To store a value in a session object, use the setAttribute method. For example, if a servlet has prepared an object referred to by a variable called league, this could be placed in the session using the following code: HttpSession session = request.getSession(); session.setAttribute(“league”, league);

    The getSession method returns, or perhaps creates, the session associated with this client. You can test whether the session object has just been created using the isNew method. If the session object already exists, then every call to the getSession method returns the same object. Code that has a handle on the session object stores data using the setAttribute method. Notice that the session is a map, so a key must be used to identify this particular object when it is later retrieved.

    Retrieving Session Attributes You can use the getAttribute method to retrieve data previously stored in the session object. For example, to retrieve the league object stored in the earlier example, you could use the following code: HttpSession session = request.getSession(); League theLeague = (League)session.getAttribute(“league”);

    + Cookie

    1. ADD COOKIE: the user’s name so that on the next visit to the site, the screen is personalized for the user. In your servlet, you could use the following code to store that cookie:

    String name = request.getParameter("firstName"); Cookie c = new Cookie("yourname", name); response.addCookie(c);

    2. GET COOKIE: Later, when the visitor returns, your servlet can access the yourname cookie using the following code: Cookie[] allCookies = request.getCookies(); for ( int i=0; i < allCookies.length; i++ ) { if ( allCookies[i].getName().equals(“yourname”) ) { name = allCookies[i].getValue(); } }

    Related Documents

    Jee Ag
    February 2021 2
    Ed Ag E
    February 2021 2
    Ag Petrofac Pulsation Study
    February 2021 0
    Ag American Architecture
    January 2021 3
    Iit Jee Formula Book
    March 2021 0
    Jee Advance Tmh
    January 2021 11

    More Documents from "Devender Baghel"

    Jee Ag
    February 2021 2
    Prodica U Krizi
    February 2021 1
    Helvetius O Duhu
    February 2021 1
    February 2021 4
    Din_000013_t2_nov1999
    February 2021 1