javaweb experiment: JSP application development


foreword

In this article, I will introduce how to use jsp technology to develop some simple small functions and a simple web application to realize user registration and login functions. jsp is a dynamic web page technology based on java, it can embed java code in html code to achieve dynamic page effect. Jsp application development needs to use a web server, such as Tomcat or Jetty, to run and deploy jsp files, and tomcat is used in this article.

I found that many people's problems lie in the configuration and construction of the environment. Put a configuration link here, and if you follow along, there should be no problems (if you use idea)

http://t.csdn.cn/2Ud0g


1. Purpose of the experiment

(1) Learn to write and run simple JSP pages, and understand their operating principles;

(2) Learn to use JSP declarations, expressions, scripts and comments;

(3) Understand the grammatical format of JSP page instructions and actions, and use them skillfully;

(4) Understand the built-in objects commonly used in JSP and use them skillfully.

2. Experimental principle

JSP has three directive elements: page, include, and taglib. These directive elements are aimed at the JSP engine and do not produce any visible output. They are both enclosed within <%@ and %> tags. This experiment mainly learns the page command.

The <%@ page %> directive acts on the entire JSP page, including statically included pages, but not dynamically included pages. Multiple <%@ page %> directives can be included in a page, but its attributes can only appear once in the entire page except import.

The <%@ page %> directive can be placed anywhere on the page, but for the readability of the JSP program, the <%@ page %> directive is generally placed in front of the page.

Include directive: static include: <@ include file="">

          Dynamic inclusion: <jsp:include page=""/> No parameter passing

                    <jsp:include page=””>

                      <jsp:param: name=”” value=””>

                    </jsp:include/>

Jump instruction: <jsp:forward page="">

              <jsp:param: name=”” value=””>

          </jsp:forward/>

Use of built-in objects

3. Experimental content

(1) Program to output a rhombus composed of asterisks "*" in the JSP page;

(2) Program to implement a counter that realizes page count, and requires that the count not be increased when the page is refreshed;

(3) [Throughout the project] User login verification (no database implementation) .

4. Experimental process

1. Program to output a rhombus composed of asterisks "*" in the JSP page;

code show as below:

<% 
StringBuffer sb3 = new StringBuffer();
int n=10;
//前10行.上半部分
for(int i=1;i<=n;i++)//控制行数
{
    for(int k=n;k>=i;k--)//打印空格
    {
        sb3.append("&nbsp");
    }
    for(int j=1;j<=i;j++)//打印*
    {
        sb3.append("*");
    }
    sb3.append("<br>");
}
//后9行,下半部分
for(int i=n-1;i>=1;i--)
{
    for(int k=i;k<=n;k++)
    {
        sb3.append("&nbsp");
    }
    for(int j=1;j<=i;j++)
    {
        sb3.append("*");
    }
    sb3.append("<br>");
}
 %>
<%=sb3.toString() %>

Create a web project, select tomcat as the web server, create a jsp file in the web project, name it sb3, enter the code into it, and get the following results

2. Program to implement a counter that realizes page counting, and requires that the count not be increased when the page is refreshed

code show as below:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%! int count = 0; %>
<% count++; %>
Welcome! You are visitor number <%= count %>
</body>
</html>

Similarly, create a jsp file named counter.jsp, write the code to get the following results

 

when we refresh

It will increase by one every time it is refreshed

Question 1: Which JSP syntax elements are included in the JSP page. Visit the page in a browser, what is the output? Refresh the page multiple times, what's the result?

Answer: This JSP page contains multiple JSP syntax elements such as directives, script elements, and comments. The page also includes a script block that increments the visitor count variable every time the page loads. Then use the expression tag to display the visitor count on the page

To access this JSP page, you need to deploy it on a web server that supports JSP. Once deployed, you can access it with a web browser by navigating to its URL. The visitor count is incremented every time the page is refreshed

Question 2: Open the converted source file counter_jsp.java from counter.jsp , where is the corresponding class file? What is the file name?

Answer: The compiled JSP files are located in the /work folder of the Tomcat environment by default. There should be a subfolder representing the default domain name of localhost, which should contain counter.jspthe compiled JSP file, and the file name should becounter_jsp.class

问题三:Check where the count variable is declared?

answer:

countVariables are declared in script tags at the top of the code block, as follows:

<%! int count = 0; %>

It is initialized to 0 and has scope visible to all other scripts and expressions in the JSP file. The following script tag countincrements the value of 1:

<% count++; %>

This script tag increments the value of 1 every time the JSP page is accessed count. Finally, mark the displayed value with an expression count, like this:

<%= count %>

This expression marks the current value displayed on the web page count.

Question 4: Change the <%! int count = 0; %> line in the above JSP page to <% int count = 0; %>, can the page be executed normally, and what is the difference between it and the above page?

<%! int count = 0; %>Answer: Change one line in the above JSP page <% int count = 0; %>, and the page can still be executed normally. The difference between these two methods is the scope of variables. Variables declared using <%! %>tags have global scope and can be used anywhere in the JSP file. Variables declared <% %>with tags can only be used within the current script block. Therefore, if you need to use variables in multiple script blocks in a JSP file, you should use the former method.

2.1, using the counter implemented with session

 code show as below:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%!
    static int num = 0;
%>
<%
    if(session.isNew())
		num++;
%>
<%="欢迎光临! 您是第 " + num + " 位访问者!" %>
</body>
</html>

The following results are obtained:

At this time, refreshing will not increase the number of visits. When we copy the URL to another browser, it will appear

Close the previous browser and copy the URL again, then

explain:

<%
    if(session.isNew())
		num++;
%>

numThis script tag checks to see if the current session is a new session and increments the value of 1 if it is a new session . numFinally, mark the displayed value with the expression

2.2, use the counter implemented by application

code show as below:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
	int n;
	if(application.getAttribute("num") == null) 
		n = 1;
	else
	   	n = Integer.valueOf(application.getAttribute("num").toString());
    if(session.isNew()) 
    	n++;
	application.setAttribute("num", n);
    out.println("欢迎光临! 您是第 " + application.getAttribute("num") + " 位访问者!");
%>
</body>
</html>

The effect is as follows:

In the same way,


Copy the URL to another browser, the effect is as follows

3. Programming to realize user login (no database implementation)

content:

(1) Create a new project . The project name adopts the following naming format: proj_****www_exp2 (Note: replace **** with the last 4 digits of your student number , and replace www in it with the full Chinese spelling of your name ).

    (2) Configure the build path for the project and add Apache Tomcat Server (for example: Apache Tomcat 7.0 or 8.5).

    (3) Confirm that the subdirectory WEB-INF under the project root directory contains web.xml (if there is no such file, it can be copied from the Tomcat installation directory).

    (4) Write the following page to realize user login and logout functions . The knowledge points used include: include instructions; jump instructions; request, response, session objects; cookies.

      login.jsp: user login form page

login_check.jsp : User login verification page, enter the specified ID and password to log in successfully, otherwise fail, request to remember the user's login status, and automatically fill in the login ID information when logging in next time. Provide at least three IDs and passwords for successful login. Such as (changyh, 123), (shiqj, 456), (wangzhe, 789)

      login_success.jsp: login success page

      login_failure.jsp: login failure page

      logout.jsp: Exit the login page

      header.jsp: The header file, which is included in the login.jsp page, defines the effect by itself (in this case, it is "login operation").

      function1 , function2, and function3 are defined by themselves.

The login.jsp code is as follows:

<%@ page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>登录程序之表单页面</title>
</head>
<body>
<%
    String userId = "";
    String password = "";
    Cookie[] cookies = request.getCookies();
    if(cookies != null){
        for(int i=0; i<cookies.length; i++){
            if (cookies[i].getName().equals("Cookie2019")) {
                //如果cookie对象的名称为Cookie2019
                userId = cookies[i].getValue().split("#")[0];  //获取用户名
                password = cookies[i].getValue().split("#")[1];  //获取登录时间
            }
        }
    }
%>
<center>
    <h1>登录操作</h1>
    <hr>
    <form action="login_check.jsp" method="post">
        <table border="1">
            <tr>
                <td colspan="2">用户登录</td>
            </tr>
            <tr>
                <td>登录ID:</td>
                <td><input type="text" name="id" value="<%=userId %>"></td>
            </tr>
            <tr>
                <td>登录密码:</td>
                <td><input type="password" name="password" value="<%=password %>"></td>
            </tr>
            <tr>
                <td colspan="2">
                    &nbsp;&nbsp;<input type="submit" value="登录">&nbsp;&nbsp;
                    <input type="reset" value="重置">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    <input type="checkbox" name="remenber" checked>记住我
                </td>
            </tr>
        </table>
    </form>
</center>
</body>

The effect is as follows:

This is the user login form interface

 The login_check code is as follows:

<%@page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8">
    <title>登录程序之验证页面</title>
</head>
<body>
<%!
    public static String[] userids={"zhaoyixing","tianzhengwang","shuangdanwasi"};
    public static String[] usernames={"找异性","天镇王","双蛋瓦斯"};
    public static String[] userpws={"123","456","789"};
    String check(String userid, String userpw){
        int i;
        for(i=0;i<userids.length; i++){
            if(userids[i].equals(userid)){
                break;
            }
        }
        if(i<userids.length){
            if(userpws[i].equals(userpw)){
                return usernames[i];
            }else{
                return "";
            }
        }else{
            return "";
        }
    }
%>
<%
    request.setCharacterEncoding("UTF-8");
    String id = request.getParameter("id");
    String password = request.getParameter("password");
    String remenber = request.getParameter("remenber");
    String name;
    Cookie[] cookies;
    if((!(name=check(id,password)).equals(""))){
        cookies = request.getCookies();
        int i;
        boolean cookies_flag = false; //表示是否创建Cookie
        if(cookies != null){
            for(i=0; i<cookies.length; i++){
                if("Cookie2019".equals(cookies[i].getName())){
                    break;
                }
            }
            if(i<cookies.length){
                cookies_flag = false;
            }else{
                cookies_flag = true;
            }
        }else{
            cookies_flag = true;
        }

        Cookie cookie;

        if(remenber != null){
            if(cookies_flag){
                cookie = new Cookie("Cookie2019", id+"#"+password);
                cookie.setMaxAge(45);
                response.addCookie(cookie);
            }
        }else{
            if(!cookies_flag){
                cookie = new Cookie("Cookie2019", id+"#"+password);
                cookie.setMaxAge(0);
                response.addCookie(cookie);
            }
        }

        session.setAttribute("username", name);
        session.setMaxInactiveInterval(60);
        response.sendRedirect("login_success.jsp");

    }else{              //登录失败,跳转到失败页
        response.sendRedirect("login_failure.jsp");
    }
%>
</body>

In this code, it mainly introduces that JSP has three directive elements: page, include, and taglib. These directive elements are aimed at the JSP engine and do not produce any visible output. They are both enclosed within <%@ and %> tags. This experiment mainly learns the page command. The <%@ page %> directive acts on the entire JSP page, including statically included pages, but not dynamically included pages. Multiple <%@ page %> directives can be included in a page, but its attributes can only appear once in the entire page except import. The <%@ page %> directive can be placed anywhere on the page, but for the readability of the JSP program, generally the <%@ page %> directive is placed in front of the page. Include directive: Static include: <@ include file=””> Dynamic include: <jsp:include page=””/> Pass without parameter <jsp:include page=””> <jsp:param: name=”” value= ""> </jsp:include/> Jump instruction: <jsp:forward page=””> <jsp:param: name=”” value=””> </jsp:forward/> Use of built-in objects

The login_succsee code is as follows:

<%
  if(session.getAttribute("username") == null)
  {
    response.sendRedirect("login.jsp");
  }
%>
<h2>欢迎[<%=session.getAttribute("username")%>]</h2>
<br>
<table>
  <tr>
    <th>新闻管理系统</th>
  </tr>
  <tr>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td align="center"><a href="function1.jsp">功能1</a></td>
  </tr>
  <tr>
    <td align="center"><a href="function2.jsp">功能2</a></td>
  </tr>
  <tr>
    <td align="center"><a href="function3.jsp">功能3</a></td>
  </tr>
</table>
<hr>
<table width="200">
  <tr>
    <td align="left">&nbsp;</td>
    <td align="right"><a href="logout.jsp">登出</a></td>
  </tr>
</table>
</center>
</body>

This is the home page of a news management system. If the user is not logged in, it redirects to the login.jsp page. If logged in, a welcome message and three function links are displayed. Users can click on the link to visit the corresponding function page. Additionally, there is a logout link that the user can click to log out of the system.

The effect is as follows:

The login_failure code is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"%>

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Insert title here</title>
</head>
<body>
用户名或密码错误,请重新<a href="login.jsp">登录</a>
</body>
</html>

The code contains an error message. This error message indicates that the username or password is incorrect and a new login is required. The page also contains a link, which leads to the login page. If you want to log back in, click the link

The effect is as follows:

Click Login here to jump to the login page, namely login

The header.jsp code is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>header</title>
  <meta charset="UTF-8">
  <title>Insert title here</title>
  <style>
    body {
      background-color: lightblue;
    }
    h1 {
      color: white;
      text-align: center;
    }
  </style>
</head>
<body>
<center><h1>登录操作</h1></center></body>
<hr>
</html>

This code adds the color of the title and the color of the background, the effect is as follows:

The logout.jsp code is as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>Insert title here</title>
</head>
<body>
<%session.invalidate(); %>
<jsp:forward page="login.jsp"/>
</body>
</html>

 This code, it invalidates the current session and forwards the request to the login.jsp page. The session.invalidate() method is used to invalidate the current session. <jsp:forward> tag is used to forward the request to another JSP page. In this case it forwards the request to the login.jsp page.

The effect is as follows:

Click to log out to log out 

Content about function

Write a function sample code here 

<%@page contentType="text/html;charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<body>

<h2>生成一个随机数</h2>

<p>点击按钮调用函数。</p>

<button onclick="myFunction()">点我</button>

<p id="demo"></p>

<script>
    function getRandomInt(max) {
        return Math.floor(Math.random() * max);
    }

    function myFunction() {
        document.getElementById("demo").innerHTML = getRandomInt(100);
    }

</script>

</body>
</html>

This code can generate a random number from 0-100 by clicking the button

The effect is as follows:

It can be used to attract jade, and more interesting functions can be written  


Summarize

This is a tutorial on how to use JSP technology to develop some simple functions and a simple web application to realize user registration and login functions. JSP is a Java-based dynamic web page technology, which can embed Java code into HTML code to achieve dynamic page effects. JSP application development requires a web server such as Tomcat or Jetty to run and deploy JSP files. In this article, Tomcat is used. This tutorial covers the following topics:


Introduction to JSP Technology
The three directive elements of JSP: page, include, and taglib How to program a diamond
made of stars in JSP accomplish)

Guess you like

Origin blog.csdn.net/m0_72471315/article/details/129776940