1, Basic syntax of EL expression
1.EL expression syntax is very simple. It starts with "${" and ends with "}". The middle is a legal expression. The specific syntax format is as follows:
${expression}
expression: used to specify the content to be output. It can be a string or an expression composed of EL operators. To output a string in EL expression, you can put the string in a pair of single quotation marks or double quotation marks.
note: because the syntax of EL expression is "Kate parse error: expected '}', got 'EOF' at end of input:... If you want to display" {"string in JSP Web page, you must add \" symbol in front of it, that is "${" to output "${" symbol.
reserved keyword of 2.EL
when naming variables, you should avoid using these keywords, including using EL to output variables that have been saved in the scope. You can't use keywords. If they have been defined, they need to be modified to other variable names.
gt eq or and div empty instanceof false ge le It not
3. Access data through EL
Data can be accessed through the "[]" and "." operators provided by EL. Generally, "[]" and "." operators are equivalent and can replace each other.
${user.id} ${user['.name']}
but not all cases can replace each other. For example, when the attribute name of an object includes some special symbols (- or.), you can only use the "[" operator to access the attribute of the object. For example, ${userInfo ['user ID]} is correct, while ${userifo. User name} is wrong. In addition, EL's "[" Operator is also used to obtain data in an array or List collection. It is described in detail below.
4. Obtaining array elements
the "[" operator can get the specified element of the array, but the "." operator cannot.
${arrBook[0]}
Case:
Store four books in the request field, and use the loop to output the number and title to the page.
<% String[] arr = {"java", "ui", "big data", "new media"}; %> <% for (String s : arr) { request.setAttribute("b", s); %> <p>${b}</p> <% } %>
in EL, arithmetic operations can also be performed. Like the Java language, EL provides five arithmetic operators: addition, subtraction, multiplication, division and remainder.
+ - * /(div) %(mod)
5.EL judgment is not empty
in EL, you can judge whether an object is empty by the empty operator, which is a prefix operator, that is, the empty operator is in front of the operand to determine whether an object or variable is null or empty. In addition, the empty operator can also be used in combination with the not operator to judge whether an object or variable is non empty.
${empty expression} ${not empty expression}
6.EL operator
in EL, six relational operators are provided. These six relational operators can be used not only to compare integers and floating-point numbers, but also to compare strings. The format of relational operators is as follows:
==or eq be equal to !=or ne Not equal to <or lt less than >or gt greater than <=or le Less than or equal to >=or ge Greater than or equal to
during comparison, if two or more judgment conditions are involved, the logical operator needs to be applied. The value of the condition expression of the logical operator must be Boolean or a string that can be converted to Boolean, and the returned result is also Boolean.
&&or and And ||or or or !or not wrong
7. When splicing variables of El string type, you cannot use +. You need to use concat() method.
${"2"+"1"} The result is 3 ${"hello"+" world!"} report errors java.lang.NumberFormatException: For input string: "hello" ${"hello".concat(" world")} The result is hello world
2, EL implied object
four implicit objects are provided in EL to access the scope, namely pageScope, requestScope, sessionScope and applicationScope. After using these four implicit objects to specify the scope of the identifier to be found, the system will no longer find the corresponding identifier in the default order of page, request, session and application. They are the same as PA in JSP The built-in objects of Ge, request, session and application are similar. However, these four implicit objects can only be used to obtain the attribute value within the setAttribute range, not other relevant information.
<% pageContext.setAttribute("id", 8); session.setAttribute("id", 2); request.setAttribute("id", 1); application.setAttribute("id", 3); %> ${sessionScope.id}
in order to obtain relevant data in Web applications, EL provides multiple implicit objects, which are similar to the built-in objects of JSP and operate directly through the object name. Among the implicit objects of EL, except that pageContext is a JavaBean object, other implicit objects correspond to java.util.Map type.
pageContext can access JSP built-in objects (such as request, response, out, session, exception, page, etc.). After obtaining these built-in objects, you can obtain their attribute values. These attributes correspond to the getXXX() method of the object. When using, remove get from the method name and change the initial letter to lowercase.
1. Access the request object
to obtain the request object in the JSP built-in object through pageContext, you can use the following statement:
${pageContext.request}
after obtaining the request object, you can obtain information related to the client through this object, such as HTTP header information, client information submission method, client host IP address and port number, etc.
${pageContext.request.severPort}
2. Access the response object
to obtain the response object in the built-in object of JSP through pageContext, you can use the following statement:
${pageContext.response}
after obtaining the response object, you can obtain the information related to the response through the object. ${pageContext.response.contentType} This code will return the content type of the response.
3. Access out object
to obtain the out object in the JSP built-in object through pageContext, you can use the following statement:
${pageContext.out}
after getting the out object, you can get the output related information through the object. ${pageContext.out.bufferSize} This code will return the size of the output buffer.
4. Access session object
to obtain the session object in the JSP built-in object through pageContext, you can use the following statement:
${pageContext.session}
after obtaining the session object, you can obtain the information related to the session through the object. ${pageContext.session.maxlnactiveInterval} This code will return the effective time of the session.
5. Access exception object
to obtain the exception object in the built-in JSP object through pageContext, you can use the following statement:
$(pageContext.exception}
after obtaining the exception object, you can obtain the exception information of the JSP page through the object. ${pagecontext. Exception. Message}
6. Access page object
to obtain the page object in the built-in JSP object through pageContext, you can use the following statement:
${pageContext.page}
after obtaining the page object, you can obtain the class file of the current page through the object. ${pageContext.page.class} This code will return the class file of the current page.
7. Access servletContext object
obtain the servletContext object in the built-in JSP object through pageContext. You can use the following statement: ${pageContext.servletContext}
after obtaining the servletContext object, you can obtain servlet context information through the object$ {pagecontext. Request. Contextpath} This code will return the context path of the current page.
8.param can obtain the parameters in the request. For example, ${param.id} can obtain the parameter of request XXX?id=12.
3, Relative path and absolute path
absolute path: absolute path is the real path (URL and physical path) of the file or directory on your home page on your hard disk
for example, C://xyz/test.txt represents the absolute path of the test.txt file. http://www.sun.com/index.html It also represents the absolute path of a URL.
relative path: the path relative to a benchmark directory. Contains the relative path of the Web (the relative directory in HTML). For example, in the Servlet, "/" represents the following directory of the Web application. Relative representation of and physical path.
for example, ". /" represents the current directory and "... /" represents the parent directory. This similar representation also belongs to relative path.
note that the relative paths in JSP/Servlet are divided into server and client paths.
1. Server address
the relative address on the server side refers to the address relative to the web application. This address is resolved on the server side (different from the relative address in html and javascript, which is resolved by the client browser). That is, at this time, the relative address in jsp and servlet should be relative to the web application, that is, relative to http: //192.168.0.1/webapp /.
it is used in:
forwarding: request.getRequestDispatcher(address) in servlet; This address is resolved on the server side. Therefore, to forward to JSP / a.jsp, it should be written as follows: in front of request.getRequestDispatcher("/ JSP / a.jsp") / relative to the current web application webapp, its absolute address is: http://192.168.0.1/webapp/jsp/a.jsp .
redirection: response.sendRedirect("/ context path / jsp/a.jsp") in JSP or Servlet;
2. Address of the client
the relative addresses in all HTML pages are relative to the server root directory( http://192.168.0.1/ )Instead of (following the directory of the Web application under the directory) http://192.168.0.1/webapp/ of The address of the action attribute of the form in HTML should be relative to the server root directory( http://192.168.0.1/ )Therefore, if the submitted to a.jsp is: action = "/ webapp/user/a.jsp" or action = "context path / user/a.jsp"; the submitted to servlet is actiom = / webapp / handleservlet "Javascript is also parsed on the client side, so its relative path is the same as that of the form form. Therefore, in general, it is better to add context paths in front of CSS, Javascript and other attributes referenced by JSP/HTML pages to ensure that the referenced files belong to the directory in the Web application. In addition, try to avoid using relative paths relative to the file location such as ".", ". /", "... /... /", which is easy to cause problems when the file is moved.
<img src="${pageContext.request.contextPath}/img/1.jpg"> <form action="${pageContext.request.contextPath}/login"> <input type="submit" value="Submit"> </form>
4, ajax submit data
ajax generally requires jquery to submit data, and the page no longer uses the submit button. When the data is clicked, it will use jquery to send a request. The sent data will find the corresponding Servlet, obtain the data returned in the background, and call the callback method to put the data in the response variable.
<form> <input name="name" id="name"> <input name="password" id="password"> <p id="msg"></p> <input type="button" value="Submit" onclick="sub()"> </form> <script> function sub(){ let name = $("#name").val(); let password = $("#password").val(); //Callback $.post("login", {name, password}, function (response) { $("#msg").html(response) }) } </script>
LoginServlet
@WebServlet("/login") public class LoginServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("utf-8"); String name = req.getParameter("name"); String password = req.getParameter("password"); System.out.println(name); System.out.println(password); resp.getWriter().write("Login succeeded"); } }
Case: full HTML login and exit system
index.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> </head> <body> <h1>welcome<span id="user"></span>Sign in!</h1> <a href="logout">Log out</a> <script> $.post("userInfo", {}, function (response) { $("#user").html(response) }) </script> </body> </html>
login.html
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title</title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> </head> <body> <form> <input name="name" id="name"> <input name="password" id="password"> <p id="msg"></p> <input type="button" value="Submit" onclick="sub()"> </form> <script> function sub() { let name = $("#name").val(); let password = $("#password").val(); //Callback $.post("login", {name, password}, function (response) { if (response.trim() == 'Login succeeded') { location.href = "index.html"; } else { $("#msg").html(response) } }) } </script> </body> </html>
loginServlet
@WebServlet("/login") public class LoginServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("utf-8"); String name = req.getParameter("name"); String password = req.getParameter("password"); if ("123".equals(password)) { req.getSession().setAttribute("userInfo", name); resp.getWriter().println("Login succeeded"); } else { resp.getWriter().println("Wrong account or password"); } } }
LogoutServlet
@WebServlet("/logout") public class LogoutServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.getSession().invalidate(); resp.sendRedirect("login.html"); } }
UserInfoServlet
@WebServlet("/userInfo") public class UserInfoServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.setCharacterEncoding("utf-8"); resp.getWriter().println(req.getSession().getAttribute("userInfo")); } }
LoginFilter
@WebFilter("/*") public class LoginFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; if (request.getRequestURI().contains("login")) { filterChain.doFilter(request, response); return; } if (request.getSession().getAttribute("userInfo") != null) { filterChain.doFilter(request, response); return; } response.sendRedirect("login.html"); } @Override public void destroy() { } }
5, JSTL common tag library
the full name of JSTL is JSP Standard[ ˈ stænd ə d] Tag Library [ ˈ la ɪ br ə ri] is the JSP Standard tag library. As the most basic tag library, JSTL provides a series of JSP tags to realize the basic functions: Collection traversal, data output, string processing, data formatting and so on. The steps to use JSTL tag library are as follows:
1. Import jstl-1.2.jar development package.
2. Use the tablib instruction to introduce the required JSTL tag in the JSP page.
core tag library
core tag library is the core tag library of JSTL, which realizes the most basic functions: process control, iterative output, etc. The prefix of the core tag library is generally c
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
c:out
Case:
<% request.setAttribute("name", "zhongfucheng"); %> //< C: out / > the label supports the label body, and the data on the default attribute can be written in the label body //< C: out value = "${name}" escapexml = "true" > the data you want cannot be found < / C: out > <c:out value="${name}" default="The data you want cannot be found" escapeXml="true"/>
we found that the effect of the above code implementation is the same as that of EL expression. It has two more outstanding properties, default and escapeXml[ ɪˈ ske ɪ p] Properties. If we use these two attributes, we will use this tag. If we do not use these two attributes, we can use EL expression.
c:if
JSTL provides the implementation of if tag to complete branch statement, and the test attribute is indispensable. The var and scope attributes seem useless to me (what's the use of saving the execution results?)
Case:
<%--If the name is zhongfucheng,Then you can log in--%> <c:if test="${param.name=='zhongfucheng'}"> user name:<input type="text" name="username"><br> password:<input type="password" name="password"><br> <input type="submit" value="land"> </c:if>
c:choose
the if tag does not have the function of else. If you need an if else process similar to that in java, you need to use the choose tag. The choose tag needs to be used together with the when and otherwise tags!
case:
<c:choose> <c:when test="${param.name=='zhongfucheng'}"> How do you do, zhongfucheng </c:when> <c:when test="${param.name=='ouzicheng'}"> How do you do, ouzicheng </c:when> <c:otherwise> Who are you? Don't come here! </c:otherwise> </c:choose>
c:forEach
forEach is a loop label, which is equivalent to while and for in Java
Case:
<% List list = new ArrayList<>(); list.add("zhongfucheng"); list.add("ouzicheng"); list.add("xiaoming"); request.setAttribute("list", list); %> <c:forEach var="list" items="${list}" > ${list}<br> </c:forEach>
traversing Map objects is slightly different. Let's take a look. The var attribute does not save the object of each iteration, but Map.Entry.
<% Map map = new HashMap(); map.put("1", "zhongfucheng"); map.put("2", "xiaohong"); map.put("3", "xiaoming"); request.setAttribute("map",map); %> <c:forEach var="me" items="${map}" > ${me.key} ${me.value}<br> </c:forEach>
By default, begin starts from 0, end is the last element of the collection, and step is 1
Case:
<c:forEach var="i" begin="1" end="10" step="1"> <c:out value="${i}" /><br> </c:forEach>
varStatus represents the information of the current object being iterated. It has the following properties.
Case:
<c:forEach var="list" items="${list}" varStatus="varStatus" > ${list}Your subscript is:${varStatus.index}<br> </c:forEach>
practice:
1. Create the project demo8, and use the security jsp and servlet to complete the user login (the account and password are backfilled when logging in). A picture management system that can upload pictures only after successful login. The operation of uploading pictures can be operated in the servlet, and the login user adopts the database table of the previous case. Add another image table. The fields in the table include id and original_ file_ Name (original name), relative_paths, create_time (upload time), user_id (upload user's id).
2. User search pagination exercise: create the project user test, prepare 100 test data as follows, and use the annotation Servlet and jsp to complete the pagination and search of a single table. During the search, ensure that it can also be paginated, and 15 data are displayed on each page by default. It is not necessary to add, modify and delete temporarily. The general effects are as follows:
The steps are as follows:
1, Design the data table and write entities according to the page.
2, Write dao layer business logic according to the figure (1. Paging query set. 2. Paging query set according to fuzzy matching of name. 3. Query all quantity. 4. Fuzzy query quantity according to name).
3, Write the service layer code according to the design drawing, encapsulate the paging object and return to the Servlet layer to facilitate the rendering of pages with Servlet and jsp.
4, jsp and Servlet cooperate with each other to complete paging and condition query.
3. Reading item: ZY user system. Refer to the items on the code cloud to complete the corresponding operations. Code cloud address
Step 1: download the corresponding database script and analyze the data structure.
Step 2: download the project source code and test whether the relevant data method dao layer is available and its function.
Step 3: check the jstl and el syntax used in the corresponding jsp page.
Step 4: check what is done in the corresponding servlet according to the browser's request path.
Step 5: complete a simple employee management business by referring to the writing method of the project, employee (id, self incremented primary key, name, age, age, dept, create_time, creation time, update_time, modification time, user name added by add_user, and user name last modified by update_user).
6, JSTL extension tag library (from)
c:forTokens
this tag is similar to a set of split() and for loops of String class. It is very similar to the forEach tag. It has the properties of begin, end, step, items, var and varStatus. The difference is that the items property of the forTokens tag contains a String, which will be divided into multiple strings by the contents of the limits property!
Case:
<c:forTokens items="zhongfucheng,ouzicheng,xiaoming,xiaohong" var="name" delims="," > ${name} </c:forTokens>
c:set
the tag has 5 attributes, which is a little complicated to use! What we should remember now is that the var attribute operates on Integer, Double, Float, String and other types of data, the target attribute operates on JavaBean or Map object data, the scope represents the Web domain, value is the value, and property is the attribute of the object!
use var attribute
since the var attribute can only operate on types such as Integer, Double and String, there must be no property attribute if the var attribute exists (property represents the member attribute of the object, and where do the member variables of Integer and String come from)
the following case is like this: create a name variable, set the value to zhongfucheng, and the range is page
<c:set var="name" value="fucheng" scope="page"/> ${name}
Of course, the set tag also supports the tag body, and the value can be written in the tag body
<c:set var="name" scope="page"> zhongfucheng </c:set>
Use the var attribute and scope attribute to implement the counter
<%--Since the following variables need to be added, they should be defined, otherwise the server does not know my variable is Integer Type--%> <% Integer sessionCount = 0; Integer applicationCount = 0; %> <c:set var="sessionCount" value="${sessionCount+1}" scope="session"/> <c:set var="applicationCount" value="${applicationCount+1}" scope="application"/>
the target attribute is paired with the property attribute. The target attribute can only operate on JavaBean or Map objects, and property is the corresponding member variable or key..
since the target attribute operates on a JavaBean or Map object, the object must be obtained through an EL expression. If the taget property cannot get data, an exception will be thrown! If you use the target attribute, there must be no scope attribute (the scope attribute represents the saved range, and the target values are obtained. Can you change others' range?)
<%--Create JavaBean Object, set to session Properties of the scope--%> <jsp:useBean id="person" scope="session"/> <%--Get person Objects, settings age The value of the property is 32--%> <c:set target="${person}" property="age" value="32"/> ${person.age}
c:remove
The remove tag is quite simple. There are only var and scope attributes, which represent the deletion of domain wide attributes
Case:
<%--Create JavaBean Object, set to session Properties of the scope--%> <jsp:useBean id="person" scope="session"/> <%--Get person Objects, settings age The value of the property is 32--%> <c:set target="${person}" property="age" value="32"/> ${person.age} <br> <%--delete session attribute--%> <c:remove var="person" scope="session"></c:remove> ${person.age==null?"existence session of person The object has been deleted!":"I'm still there!"}
c:catch
this tag is mainly used to handle exceptions generated in the program. The catch tag is also very simple. There is only one var attribute, which encapsulates the abnormal information!
<%--Create JavaBean Object, set to session Properties of the scope--%> <jsp:useBean id="person" scope="session"/> <c:catch var="message"> <%--target Property can only be EL Expression. Now I'm a string. If I can't get the object, I'm sure to throw an exception!--%> <c:set target="person" property="age" value="32"/> </c:catch> ${message}
fmt tag
The jsp page needs to introduce fmt tag:
<taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt">
Use the following code to convert a string date to a date.
<fmt:parseDate value="${personMaster.masterDate}" pattern="yyyy-MM-dd" var="masterDate"/>
Use the following code to format the date.
<fmt:formatDate value="${masterDate}" pattern="yyyy-MM-dd" timeZone="GMT+08:00"/>
fn label
jsp page needs to introduce fn tag:
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
Use the following code to cut the string into an array according to commas and traverse.
<c:set value="${ fn:split('a,b,c,d,', ',') }" var="arr"/> <c:forEach items="${arr}" var="s"> <p>${s}</p> </c:forEach>
Project assessment: (5 days)
Blog system
News system
Project display system
Content management system
Scenic spot management system travel system
1. Select the appropriate front-end page template. The page at least includes the following front and back-end requirements and translate them into Chinese. Design the database table according to the template (for database design documents, generally add the creation time, last modification time, last modifier number, upper and lower lines, sorting numbers, etc.)
2. Use the object-oriented development idea to complete the project development, and use the following package structure: servlet (control layer), service (service layer), dao (database access layer), entity (model), filter (filter layer), util (tool class layer)
3. Select the appropriate background management page template, add, delete, modify and query all data tables, place the path uniformly in the / WEB-INF/jsp/admin / directory, and add the parent path to all background servlets, such as: / admin/index.
4. Do a good job of corresponding permission control to ensure that the background management page cannot be accessed without login.
Front desk demand:
1. Show blog list
2. Show blog details
3. Record blog comments, register and comment when logging in
4. Message contact
Management requirements:
1. System big data statistics (Statistics of total number of blogs, number of online blogs, top 3 views and number of registrants)
2. User management (delete, reset password, lock and enable)
3. Blog management (add, delete, modify, go online and offline, comment management)
4. Message management (view)
Final submission:
1. Original project template
2. Database design documents (reference documents)
3. Source code and database script
4. Runnable projects and scripts
5. Professional video (introduce the use of the project and start the demonstration from the startup script)
6. Professional ppt