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("Title | Year | Genre |
"); out.println(""); out.println(""); for (DvdItem dvdItem : dvdList) { out.println(""); out.println("" + dvdItem.getTitle() + " | " + "" + dvdItem.getYear() + " | " + "" + dvdItem.getGenre() + " | "); out.println("
"); } out.println(""); out.println("
"); 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(""); 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=UTF8"); 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="UTF8"%> 6 8 9 10 11 <meta httpequiv="ContentType" content="text/html; charset=UTF8"> 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 httpequiv="ContentType" 4 content="text/html; charset=UTF8"> 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="UTF8"%> <meta httpequiv="ContentType" content="text/html; charset=UTF8"> 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 32 33 34