JSP (main content)

1, C/S and B/S

  C/S is also called Client/Server or Client/Server mode. The server usually adopts high-performance PC, workstation or minicomputer, and adopts large database system, such as Oracle, Sybase, Informix or SQL Server. The client needs to install special client software, such as Youku client.

  B/S is the abbreviation of Browser / server. Only one Browser (such as 360 Browser, Google, Firefox or Internet Explorer) is installed on the client, and Oracle, Sybase, MySQL or SQL Server databases are installed on the server. The Browser interacts with the database through the Web Server, such as Youku web version.

   the advantage of C/S is that it can give full play to the processing capacity of the client PC. a lot of work can be submitted to the server after being processed by the client. The corresponding advantages are fast client response and high security. The main disadvantages are as follows:
  the client needs to install special client software. Firstly, it involves the workload of installation. Secondly, any computer problem, such as virus and hardware damage, needs to be installed or maintained. Especially when there are many branches or specialty stores, it is not a matter of workload, but a matter of distance. In addition, when upgrading the system software, each client needs to be reinstalled, and its maintenance and upgrade cost is very high.
  generally, there are restrictions on the operating system of the client. It may be suitable for Win98, but it cannot be used for win2000 or Windows XP. Or not applicable to Microsoft's new operating system, let alone Linux, Unix, etc. The biggest advantage of B/S is that it can be operated anywhere without installing any special software. As long as there is a computer that can access the Internet, it can be used, and the client has zero maintenance. The expansion of the system is very easy. As long as you can surf the Internet and assign a user name and password by the system administrator, you can use it. You can even apply online. After passing the company's internal security authentication (such as CA certificate), the system can automatically assign an account to the user to enter the system without human participation.

2, tomcat

  Tomcat server is a free open source Web application server. It is a lightweight application server. It is widely used in small and medium-sized systems and when there are not many concurrent access users. It is the first choice for developing and debugging JSP programs. For a beginner, you can think that when Apache server is configured on a machine, you can use it to respond to the access request of HTML (an application under the standard General Markup Language) page. In fact, Tomcat is an extension of Apache server, but it runs independently, so when you run tomcat, it actually runs separately as a process independent of Apache.
  the trick is that when configured correctly, Apache serves HTML pages, while Tomcat actually runs JSP pages and servlets. In addition, like IIS and other Web servers, Tomcat has the function of processing HTML pages. In addition, it is also a Servlet and JSP container. The independent Servlet container is the default mode of Tomcat. However, Tomcat does not handle static HTML as well as the Apache server.

tomcat directory structure:

bin	Contains startup.bat(Startup server) and shutdown.bat(Shut down (server) file
conf	Include settings deployed in Tomcat Upper Web The setting file of the initial value of the applied variable, which is commonly used server.xml Configure service port
lib	Contained by Tomcat Use a variety of jar Dependent files.
logs	Tomcat Log file for.
webapps	deploy Web Application where ROOT The directory is tomcat The home page directory can be replaced by other items, and the item name is not required for access
work	from Tomcat Automatic generation, this is Tomcat Place it in the middle of the run(intermediate)file(Such as compiled JSP file)local

  project directory Tomcat's Web application should consist of the following directories

   storage location of page content and other files: *. html, *.jsp, etc. can have many directory levels, which depends on the user's website structure. The realized function should be the website interface, that is, the main visible part of the user. In addition to HTML files and JSP files, there are also js (JavaScript) files, css (style sheet) files and other multimedia files.

  WEB-INF/web.xml this is a description file of a Web application. This file is an XML file that describes the Servlet and other components of the Web application. In addition, it also includes some initialization information, security constraints and so on.

  WEB-INF/classes / this directory and its subdirectories should include all compiled Java class files (*. Class) files and related configuration files such as JavaBean s and servlets of the Web application. Usually, the WEB-INF/lib / directory stores third-party jar packages.

  note: the WEB-INF directory contains the resources used by the application software, which cannot be accessed directly by the client.
  exercise: refer to the Linux chapter to complete the project deployment on windows

  1. Deploy ZY ofIEC project on port 8080 on Windows. And provide corresponding operation screenshots to form word documents.
  2. Deploy ZY Company Project on port 80 on Windows. And provide corresponding operation screenshots to form word documents.

3, Port occupancy

   generally, each application used as a service needs to listen (occupy) the corresponding port and request the port to obtain the corresponding service. However, the problem of port occupation is often encountered in development. Once the port is occupied. Later applications either change the port or force the end of the occupied process. The following two commands are used to end the port process for centos 7 in windows and linux respectively.

windows :

C:\Users\Administrator>netstat -aon|findstr 8080
 TCP    0.0.0.0:8080           0.0.0.0:0              LISTENING       6064

C:\Users\Administrator>taskkill /f  /pid 6064
 success: Terminated PID Process for 6064.

centos:

ss -lpn src :8080
kill 6723

  you can also use the unified view java process command jps provided by Java, and then end according to the end process command of the corresponding system.

C:\Users\Administrator>jps
2440 jar
6716 Jps

C:\Users\Administrator>taskkill /f /pid 2440
 success: Terminated PID Process with name 2440.

On windows, you can also end java programs through the task manager.

4, jsp basic syntax

   create an enterprise WEB application and configure Tomcat. After creating the project, start Tomcat and configure Tomcat to automatically update and modify jsp resources.

JSP is a JSP file including instruction identification, HTML code, JavaScript code, embedded Java code, comments and JSP action identification. But these contents are not necessary for a JSP page. The following will explain the composition of JSP pages through a simple JSP page.

<%@ page import="java.util.Date" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    Date date = new Date();
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String today = simpleDateFormat.format(date);
%>
<%=today%>
</body>
</html>

    the first three lines are the instruction ID, which is mainly used to set the guide package information and coding information in the whole JSP page. It is interpreted and executed by the tomcat server and will not produce any content output to the web page. That is, the instruction ID is not visible to the client browser.

  the syntax format of JSP instruction identification is as follows:

<%@Instruction name attribute 1="Attribute value 1" Attribute 2="Attribute value 2"......%>

  instruction Parameter Description:

   instruction Name: used to specify the instruction name. The JSP contains three instructions such as page, include and tagib.

   attribute: used to specify the attribute name. Different instructions contain different attributes. Multiple attributes can be set in one instruction, separated by commas or spaces.

  attribute value: used to specify attribute value.

  include and taglib instructions

  the file contains the instruction. Include is another instruction ID of JSP. With this instruction, you can include another JSP page in one JSP page. The directive has only one file attribute that specifies the path to the file to include. The path can be relative or absolute.

<%@ include file="header.jsp"%>

   in the JSP file, you can identify and declare the tag library used in the page through the taglib instruction, reference the tag library, and specify the prefix of the tag. After referencing the tag library in the page, you can reference the tags in the tag library through the prefix. We will use the tag library of jstl later

<%@ taglib prefix="c" uni="http:/java.sun.com/jsp/jstl/core" %>

  note: don't use HTML tag headers for pages in jsp, otherwise some strange errors will occur when pages are nested.

5, jsp script

  script identification is used most frequently in JSP pages. Because they can easily and flexibly generate dynamic content in the page.

  1.JSP expression

   it is used to output information to the page. Its syntax format is as follows:

<%=expression%>

   expression: it can be a complete expression of any Java language. The final result of the expression is converted to a string.

<%String manager="mr";%>         Defines the variable that holds the administrator name
 administrators: <%=manager %>            The output result is:administrators: mr
<%="administrators:"+manager %>          The output result is administrator: mr
<%= 5+6 %>                       The output is 11
<%String ur="126875jpg" %>       Defines the variable to save the file name
<img src="images/<%=url %>">     The output result is: <img src="lmages/126875.jpg">

  2. Declaration identification

   declaration identifies the variables or methods used to define the global in the JSP page. The variables and methods defined by the declaration identity can be accessed by the whole JSP page, so the identity is usually used to define the variables or methods to be referenced by the whole JSP page.

The syntax format of the declaration ID is as follows:

<%!Code that declares a variable or method%>

  each jsp will be compiled into a Servlet, and the declared variable or method will be converted into the member variable and member method of the Servlet.

<%!
    int number = 0;       //Declare global variables
    int count() {         //Declare global methods
        number++;         //Accumulate number
        return number;    //Returns the value of number
    }
%>

  after declaring global variables and global methods through the above code, if the global method is called later through <% = count()% >, the previous value + 1 will be output every time the page is refreshed.

  3. Code fragment

  the so-called code fragment is the Java code or script code embedded in the JSP page. The code fragment will be executed during the processing of the page request. Variables or process control statements can be defined through Java code, while the built-in objects of JSP can be applied through script code to output content on the page, process requests and responses, access inter session sessions, etc.

Case: output 99 multiplication table in JSP page through code fragment and JSP expression

<%
    String str = "";//Declare a string variable that holds the 99 multiplication table
    for (int i = 1; i <= 9; i++) {//External circulation
        for (int j = 1; j <= i; j++) {//Internal circulation
            str += j + "X" + i + "=" + j * i;
            str += " ";//Add space character
        }
        str += "<br>";//Add line feed
    }
%>
<%=str%>

Case: code snippets are used with expressions.

<body>
<%
    List list = Arrays.asList("Zhang San", "Li Si", "WangTwo ", "Pockmarks","Wang Wu");
%>
<%
    for (Object o : list) {
%>
<p><%=o%></p>
<%
    }
%>
</body>

  note: if a third-party jar package is used in a web project, it needs to be placed in the WEB-INF/lib directory. If the directory does not exist, create the copied jar package and right-click to add it to the project dependency.

  exercise:

   1. Loop exercise: create the project demo1, and use the java loop in index1.jsp to complete the output of A-Z.

   2. Database table query: create the page index2.jsp in project demo1, download the data table data, import the database staff, and use jdbc to generate the data in index2.jsp into the following table style, which uses bootstrap.
Data download:
Link: https://pan.baidu.com/s/19Q946fM8l5m7r2RycB-KTw
Extraction code: ljfs

Reference code:

index1.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>hello world</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        .content {
            margin: 10px auto;
            border: 2px dotted #000000;
            width: 600px;
            height: 400px;
            display: table;
        }

        .content div {
            background: #907e35;
            display: inline-block;
            width: 180px;
            height: 180px;
            margin: 10px;
            text-align: center;
            color: white;
            line-height: 180px;
            font-size: 100px;
        }
    </style>
</head>
<body>
<div class="content">
    <%
        for (char i = 'A'; i < 'Z'; i++) {
    %>
    <div><%=i%>
    </div>
    <%
        }
    %>
</div>
</body>
</html>

index2.jsp

<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
</head>
<body>

<table class="table table-bordered table-hover table-condensed">
    <thead>
    <tr class="success">
        <th>ID</th>
        <th>full name</th>
        <th>department</th>
        <th>salary</th>
        <th>level</th>
        <th>Entry time</th>
    </tr>
    </thead>
    <tbody>
    <%
        Class.forName("com.mysql.jdbc.Driver");
        Connection connection = DriverManager.getConnection("jdbc:mysql:///mydb", "root", "123456");
        PreparedStatement statement = connection.prepareStatement("select * from staff");
        ResultSet resultSet = statement.executeQuery();
        while (resultSet.next()) {
    %>
    <tr>
        <td><%=resultSet.getObject(1)%>
        </td>
        <td><%=resultSet.getObject(2)%>
        </td>
        <td><%=resultSet.getObject(3)%>
        </td>
        <td><%=resultSet.getObject(4)%>
        </td>
        <td><%=resultSet.getObject(5)%>
        </td>
        <td><%=resultSet.getObject(6)%>
        </td>
    </tr>
    <%
        }
        resultSet.close();
        statement.close();
        connection.close();
    %>
    </tbody>
</table>
</body>
</html>

6, Notes

  since JSP pages are composed of HTML, css, Java Script, etc., a variety of annotation formats can be used. This section will explain the syntax of these annotations.

   1.html comment (<! – 1111 – >) the comment of HTML language will not be displayed in the web page, but you can still see the comment information when you select to view the web page source code in the browser.

   comments in 2.jsp expression (same as in java)

   3. Hidden comment (<% -- comment content --% >) this comment can not be seen not only in the browser, but also when viewing HTML source code, so this comment has high security.

   4.JavaScript code comments (/ /), but when you right-click to view the code, you can see the annotated content.

Case:

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>hello world</title>
</head>
<body>
<%
    //int a = 12; jsp script annotations are the same as java
%>
<%--<div>1</div>jsp Note: right click to view the code, but you can't see it--%>
<!--html Comments, which can be seen when you right-click to view the source code-->

<script>
//alert(1)JavaScript comments. The content of the comments can be seen during browser debugging
<%--alert(1)jsp Note: right click to view the code, but you can't see it--%>  
</script>
</body>
</html>

7, session and cookies

  http is a stateless protocol. Every time a client reads a web page, the server opens a new connection session, and the server will not automatically maintain the client's information. How can session tracking be realized?

   session is a mechanism to save context information. It is for each browser client. The value of the variable is saved on the server. Different clients are distinguished by SessionID. Session is based on cookie or URL rewriting. Cookie is used by default. The system will create an output called JSESSIONID and return it to the client for cookie saving.

  that is, the web service will create a corresponding session space for each browser, and the session id will be set to the corresponding browser through the response header of the setcookie. The browser will bring the cookie every request, so the server will know which browser has logged in.

  note: the essence of jsp is actually Servlet. When running the jsp project, tomcat compiles jsp into Servlet source code and compiles it for operation. This series of operations are completed by the underlying jdk. Therefore, on the jsp server, you cannot only install the jre running environment.

   case: three pages index.jsp, login.jsp and check.jsp. Enter the user name and password in the form on login.jsp, and submit the data to check.jsp for verification. If the value is admin/123, jump to index.jsp and display admin welcome on the page. Otherwise, jump to login.jsp

  login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Sign in</title>
</head>
<body>
<form action="check.jsp">
    <input name="name">
    <input name="pwd">
    <input type="submit" value="Submit">
</form>
</body>
</html>

check.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>inspect</title>
</head>
<body>
<%
    String name=request.getParameter("name");//Get the key name parameter in the request
    String pwd=request.getParameter("pwd");
    if (name.equals("admin") && pwd.equals("123")){
        session.setAttribute("user",name);//Save the user name to the session
        response.sendRedirect("index.jsp");//Redirect to index.jsp
    }else {
        response.sendRedirect("login.jsp");
    }
%>
</body>
</html>

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>home page</title>
</head>
<body>
<%
    if (session.getAttribute("user") == null) {//If there is no user information in the session
        response.sendRedirect("login.jsp");//Redirect to login.jsp
    }
%>
<%=session.getAttribute("user")%>Welcome
</body>
</html>

8, Nine built-in objects

   because JSP uses Java as the scripting language, JSP will have strong object processing ability and can dynamically create Web page content. However, Java syntax needs to instantiate an object before using it, which is actually a cumbersome thing. In order to simplify development, JSP provides some built-in objects to realize many JSP applications. When using JSP built-in objects, you don't need to define these objects first. You can use them directly.

    a total of 9 such objects are predefined in JSP, namely request, response, session, application, out, pageContext, config, page and exception.

  1.request object

  the   object encapsulates all the details of the HTTP request generated by the client, mainly including HTTP header information, system information, request method and request parameters. The corresponding method provided by the request object can process various parameters in the HTTP request submitted by the client browser.

    generally, request.getParameter("id") is used to obtain the parameters after the request address, such as index.jsp?id=12

   note: when using the getParameter() method of request to obtain the passed parameter value, if the specified parameter does not exist, null will be returned; If a parameter name is specified but no parameter value is specified, the empty string ''; will be returned;

   case: the request address is as follows / deal. jsp? Id = 12 & name = Zhang San & PWD = 123, and output the obtained value to jsp.

<%@ page contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>hello world</title>
</head>
<body>
id:<%=request.getParameter("id")%>
<br>
name:<%=request.getParameter("name")%>
<br>
pwd:<%=request.getParameter("pwd")%>
</body>
</html>

  2.response object

The   response object is used to respond to customer requests and output information to the client. It encapsulates the response generated by JSP and sends it to the client in response to the client's request. The requested data can be various data types, or even files. Each response object is valid in the JSP page to which it belongs.

  redirection

  use the sendRedirect() method provided by the response object to redirect the web page to another page.

response.sendRedret("login.jsp")://Let the browser automatically jump to the login.jsp path

  3.session object

  session is called session in the network. Because HTTP protocol is a stateless protocol, that is, when a client sends a request to the server, the server receives the request and returns a response, the connection ends, and the server does not save relevant information. In order to make up for this shortcoming, HTTP protocol provides session, which can save the user's state when jumping between the Web pages of the application, so that the whole user session can exist until the browser is closed. However, if the client does not make a request to the server for a long time in a session, the session object will disappear automatically. This time depends on the server. For example, the Tomcat server defaults to 30 minutes. However, this time can be modified by writing a program. There are two common methods: setAttribute() method and getAttribute() method.

  4.config object

  it is mainly used to obtain the configuration information of the server. A config object can be obtained through the getServletConfig() method of the pageContext object. When a Servlet is initialized, the container passes some information to the Servlet through the config object. Developers can provide initialization parameters for Servlet programs and JSP pages in the application environment in the web.xml file. Common methods are as follows: getServletContexl(), getServletName(), getinitParameter(), getInitParametrNames()

  5.application object

  used to save public data in all applications. It is created automatically when the server starts and destroyed when the server stops. When the application object is not destroyed, all users can share the application object. Compared with the session object, the life cycle of the application object is longer, which is similar to the "global variable" of the system.

  6.out object

One of the most basic applications of the   out object is to output information to the client browser. The out object can output data of various data types. When outputting data of non string type, it will be automatically converted to string for output. Same as <% = "string"% >.

  7.page object

   represents the JSP itself, which is legal only in the JSP page. The page object is essentially a variable that contains the current Servlet interface reference and can be regarded as an alias for the this keyword. There are only a few simple methods: gelClass(), hashCode(), toString(), equls()

  8.pageContext object

    the pageContext object that obtains the page context is a special object. It can obtain the request, response, session, application, exception and other objects of the JSP page. The creation and initialization of the pageContext object are completed by the container. The pageContext t object can be directly used in JSP pages. It is rarely used in practical development.

  9.exception object

   the exception object is used to handle all errors and exceptions that occur during the execution of JSP files. It can only be used in pages with the isErorPage attribute value set to true in the page instruction. Using this object in general JSP pages will not be able to compile JSP files.

Chapter exercise:

1. Create project demo2 and import database data. The user uses login.jsp, check.jsp and index.jsp to complete the login logic. The user can't access index.jsp without logging in again. At the same time, connect to the database in check.jsp and verify whether the account password is correct. The database password is encrypted with md5 and the page is beautified with bootstrap, Index.jsp is responsible for displaying other information of all users except password on the page.
Data download:
Link: https://pan.baidu.com/s/19Q946fM8l5m7r2RycB-KTw
Extraction code: ljfs

Reference code:
index.jsp

<%@ page import="java.util.Map" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>home page</title>
</head>
<body>
<%
    if (session.getAttribute("userInfo") == null) {
        response.sendRedirect("login.jsp");
    }
    Map userInfo = (Map) session.getAttribute("userInfo");
%>
<div>User information:number<%=userInfo.get("id")%>
</div>
<div>User information:full name<%=userInfo.get("true_name")%>
</div>
<div>User information:Telephone<%=userInfo.get("telephone")%>
</div>
<div>User information:mailbox<%=userInfo.get("email")%>
</div>
</body>
</html>

login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Sign in</title>
</head>
<body>
<form action="check.jsp">
    <input name="login_name">
    <br>
    <input name="login_password">
    <br>
    <input type="submit" value="Submit">
</form>
</body>
</html>

check.jsp

<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.security.MessageDigest" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>inspect</title>
</head>
<body>
<%
    String loginName = request.getParameter("login_name");
    String loginPassword = request.getParameter("login_password");
    //md5 encryption
    StringBuffer sb = new StringBuffer(32);
    MessageDigest md = MessageDigest.getInstance("MD5");
    byte[] array = md.digest(loginPassword.getBytes());
    for (int i = 0; i < array.length; i++) {
        sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).toUpperCase(), 1, 3);
    }

    Class.forName("com.mysql.jdbc.Driver");
    Connection connection = DriverManager.getConnection("jdbc:mysql:///mydb", "root", "123456");
    PreparedStatement statement = connection.prepareStatement("select * from user where login_name=? and login_password =?");
    statement.setObject(1, loginName);
    statement.setObject(2, sb.toString());

    ResultSet resultSet = statement.executeQuery();
    if (resultSet.next()) {
        Map map = new HashMap();
        map.put("id", resultSet.getObject("id"));
        map.put("true_name", resultSet.getObject("true_name"));
        map.put("login_name", resultSet.getObject("login_name"));
        map.put("telephone", resultSet.getObject("telephone"));
        map.put("email", resultSet.getObject("email"));
        session.setAttribute("userInfo", map);
    }
    resultSet.close();
    statement.close();
    connection.close();
    response.sendRedirect("index.jsp");
%>
</body>
</html>

Keywords: JSP

Added by nomad9 on Sat, 27 Nov 2021 05:19:31 +0200