Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
DEZVOLTAREA APLICATIILOR WEB Asist. Univ. Dr. Mihai Stancu LAB 6 MVC Pattern with JSP and Servlets Custom Tag Example DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – Custom Tags And Design Patterns MVC = Model – View – Controller. design pattern that separates the business logic, presentation logic and data. Advantage Navigation Control is centralized Easy to maintain the large applications DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – MVC Pattern with JSP and Servlets LoginPage.jsp <%@ page language="java" contentType="text/html; charset=windows-1256" pageEncoding="windows-1256"%> <% response.setHeader("Cache-Control", "no-store, must-revalidate"); response.setHeader("Pragma", "no-cache"); response.setDateHeader("Expires", -1); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1256"> <script> function clearForms() { var i; for (i = 0; (i < document.forms.length); i++) document.forms[i].reset(); } DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – MVC Pattern with JSP and Servlets LoginPage.jsp – 2 function validateForm() { var x = document.forms["myForm"]["un"].value; if (x == null || x == "") { alert("Username must be filled out"); document.getElementById('un').focus(); return false; } var y = document.forms["myForm"]["pw"].value; if (y == null || y == "") { alert("password must be filled out"); document.getElementById('pw').focus(); return false; } } </script> <title>Login Page</title> </head> <body onLoad="clearForms()" onunload="clearForms()"> <form action="LoginServlet" onsubmit="return validateForm()" method="post" name="myForm"> Please enter your user name <input type="text" name="un" id="un" /><br> Please enter your password <input type="text" name="pw" id="pw" /> <input type="submit" value="submit"> </form> </body> </html> DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – MVC Pattern with JSP and Servlets invalidLogin.jsp <%@ page language="java" contentType="text/html; charset=windows-1256" pageEncoding="windows-1256" %> <% response.setHeader("Cache-Control","no-store,must-revalidate"); response.setHeader("Pragma","no-cache"); response.setDateHeader ("Expires", -1); new java.util.Date(); %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1256"> <title>Invalid Login</title> </head> <body> <center> Sorry, you are not a registered user! Please sign up first </center> </body> </html> DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – MVC Pattern with JSP and Servlets userLogged.jsp <%@ page language="java" contentType="text/html; charset=windows-1256" pageEncoding="windows-1256" import="ExamplePackage.UserBean"%> <% response.setHeader("Cache-Control","no-store,must-revalidate"); response.setHeader("Pragma","no-cache"); response.setDateHeader ("Expires", -1); if(session.getAttribute("currentSessionUser")!=null) { %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=windows-1256"> <title> User Logged Successfully </title> <script type="text/javascript"> function noBack() { window.history.forward(); } </script> </head> DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – MVC Pattern with JSP and Servlets userLogged.jsp – 2 <body onload="noBack();"> <a href="LogoutServlet">Logout</a> <center> <% UserBean currentUser = (UserBean)(session.getAttribute("currentSessionUser"));%> Welcome <%= currentUser.getFirstName() + " " + currentUser.getLastName() %> </center> </body> </html> <% } else { response.sendRedirect("LoginPage.jsp"); } %> DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – MVC Pattern with JSP and Servlets LoginServlet.java package ExamplePackage; import import import import import javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; javax.servlet.http.HttpSession; public class LoginServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { try { UserBean user = new UserBean(); user.setUserName(request.getParameter("un")); user.setPassword(request.getParameter("pw")); user = UserDAO.login(user); if (user.isValid()) { HttpSession session = request.getSession(true); session.setAttribute("currentSessionUser", user); response.sendRedirect("userLogged.jsp"); // logged-in page } else response.sendRedirect("invalidLogin.jsp"); // error page } catch (Throwable theException) { System.out.println(theException); } } } DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – MVC Pattern with JSP and Servlets UserBean.java package ExamplePackage; public class UserBean { private String private String private String private String public boolean username; password; firstName; lastName; valid; public String getFirstName() { return firstName; } public void setFirstName(String newFirstName) { firstName = newFirstName; } public String getLastName() { return lastName; } public void setLastName(String newLastName) { lastName = newLastName; } public String getPassword() { return password; } DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – MVC Pattern with JSP and Servlets UserBean.java – 2 public void setPassword(String newPassword) { password = newPassword; } public void removePassword() { password = null; } public String getUsername() { return username; } public void setUserName(String newUsername) { username = newUsername; } public void removeUserName() { username = null; } public void removeLastName() { lastName = null; } public void removeFirstName() { firstName = null; } public boolean isValid() { return valid; } public void setValid(boolean newValid) { valid = newValid; } } DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – MVC Pattern with JSP and Servlets UserDao.java package ExamplePackage; import java.sql.*; public class UserDAO { static Connection currentCon = null; static ResultSet rs = null; public static UserBean login(UserBean bean) { // preparing some objects for connection Statement stmt = null; String username = bean.getUsername(); String password = bean.getPassword(); String searchQuery = "select * from users where username='" + username + "' AND password='" + password + "'"; // "System.out.println" prints in the console; Normally used to trace // the process System.out.println("Your user name is " + username); System.out.println("Your password is " + password); System.out.println("Query: " + searchQuery); try { // connect to DB currentCon = ConnectionManager.getConnection(); stmt = currentCon.createStatement(); DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – MVC Pattern with JSP and Servlets UserDao.java – 2 rs = stmt.executeQuery(searchQuery); boolean more = rs.next(); // if user does not exist set the isValid variable to false if (!more) { System.out.println("Sorry, you are not a registered user! Please sign up first"); bean.setValid(false); } // if user exists set the isValid variable to true else if (more) { String firstName = rs.getString("FirstName"); String lastName = rs.getString("LastName"); System.out.println("Welcome " + firstName); bean.setFirstName(firstName); bean.setLastName(lastName); bean.setValid(true); } } catch (Exception ex) { System.out.println("Log In failed: An Exception has occurred! " + ex); } // some exception handling DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – MVC Pattern with JSP and Servlets UserDao.java – 3 finally { if (rs != null) { try { rs.close(); } catch (Exception e) { } rs = null; } if (stmt != null) { try { stmt.close(); } catch (Exception e) { } stmt = null; } if (currentCon != null) { try { currentCon.close(); } catch (Exception e) { } currentCon = null; } } return bean; } } DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – MVC Pattern with JSP and Servlets ConnectionManager.java package ExamplePackage; import java.sql.DriverManager; import java.sql.Connection; import java.sql.SQLException; public class ConnectionManager { static Connection con; static String url; public static Connection getConnection() { try { String url = "jdbc:oracle:thin:@localhost:1521:XE"; Class.forName("oracle.jdbc.driver.OracleDriver"); try { con = DriverManager.getConnection(url, "*******", "*******"); } catch (SQLException ex) { ex.printStackTrace(); } } catch (ClassNotFoundException e) { System.out.println(e); } return con; } } DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – MVC Pattern with JSP and Servlets LogoutServelt.java package ExamplePackage; import import import import import import javax.servlet.ServletException; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; javax.servlet.http.HttpSession; ExamplePackage.UserBean; public class LogoutServlet extends HttpServlet { private static final long serialVersionUID = 1L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException { try { UserBean user = new UserBean(); user.removeUserName(); user.removePassword(); HttpSession session = request.getSession(false); session.removeAttribute("currentSessionUser"); session.invalidate(); response.sendRedirect("LoginPage.jsp"); } catch (Throwable theException) { System.out.println(theException); } } } DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – MVC Pattern with JSP and Servlets AcceptInput.html <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> </head> <body style="font-family:'Verdana';font-size: 1.5em;color: #112244;"> <h2>Select a color of your choice</h2> <form method="post" action="Hello.jsp"> <br> <input type="radio" name="r1" value="G">Green<br> <input type="radio" name="r1" value="Y">Yellow<br> <input type="radio" name="r1" value="R">Red<br> <input type="radio" name="r1" value="B">Blue<br> <p> Enter Name <input type="text" name="uname"> <br><br> <input type="Submit" value="Submit" name="b1" > </p> </form> </body> </html> DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – Custom Tag Example Hello.jsp <%@ taglib uri="/Mytaglib.tld" prefix="first"%> <html> <head> <title>Customized Tag</title> </head> <body> <% String str = request.getParameter("r1"); if (str.compareTo("G") == 0) { %> <first:hello color="LIGHTGREEN"> <%=request.getParameter("uname")%> </first:hello> <% } if (str.compareTo("R") == 0) { %> <first:hello color="RED"> <%=request.getParameter("uname")%> </first:hello> <% } if (str.compareTo("Y") == 0) { %> <first:hello color="LIGHTYELLOW"> <%=request.getParameter("uname")%> </first:hello> DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – Custom Tag Example Hello.jsp – 2 <% } if (str.compareTo("B") == 0) { %> <first:hello color="LIGHTBLUE"> <%=request.getParameter("uname")%> </first:hello> <% } %> <br> </body> </html> DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – Custom Tag Example /src/hello/HelloTag.java package hello; import import import import java.io.*; javax.servlet.jsp.*; javax.servlet.jsp.tagext.*; java.util.GregorianCalendar; public class HelloTag extends BodyTagSupport { private String name; private PageContext pageContext; private Tag parent; String color; public HelloTag() { super(); } public void setName(String name) { this.name = name; } public void setColor(String color) { this.color = color; } ... DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – Custom Tag Example HelloTag.java – doAfterBody method public int doAfterBody() throws JspException { try { BodyContent bc = getBodyContent(); String body = bc.getString(); JspWriter out = bc.getEnclosingWriter(); String dt; GregorianCalendar now = new GregorianCalendar(); dt = now.getTime().toString(); String dt1 = dt.substring(11, 16); out.print("<body bgcolor=" + color + ">"); if (body != null) out.print("<CENTER>Hi" + body + "! </CENTER>"); if (dt1.compareTo("12.00") < 0) out.print("<CENTER>Good Morning to You.</CENTER>"); if ((dt1.compareTo("12.00") > 0) && (dt1.compareTo("16.00") < 0)) out.print("<CENTER>Good Afternoon to You.</CENTER>"); if ((dt1.compareTo("16.00") > 0) && (dt1.compareTo("24.00") < 0)) out.print("<CENTER>Good Evening to You.</CENTER>"); out.print("<BR>"); out.print("<CENTER>Welcome to ABC Inc.</CENTER>"); out.print("<BR>"); out.print("<CENTER>The current time: " + dt1 + "</CENTER>"); out.print("</body>"); } catch (IOException ioe) { throw new JspException("Error:" + ioe.getMessage()); } return SKIP_BODY; } } DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – Custom Tag Example Mytaglib.tld <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>first</short-name> <uri></uri> <info>A simple tag library for the examples</info> <tag> <name>hello</name> <tag-class>hello.HelloTag</tag-class> <body-content>JSP</body-content> <attribute> <name>color</name> <rtexprvalue>true</rtexprvalue> <required>true</required> </attribute> </tag> </taglib> DEZVOLTAREA APLICATIILOR WEB – LAB 6 JSP – Custom Tag Example