Create a Java Web project


premise

In the index article , I mentioned that we use Java Web to write server programs. In this article, we really enter the coding stage.


Prerequisite knowledge required for this article


Choice of IDE

There are countless IDEs on the market that can write Java Web projects, but the most mainstream IDE is Eclipse, the IDE that was abandoned by Google after the release of Android Studio. The reason why it is the most mainstream is because it has the advantage of small size... this one.

Because many things need to be done manually when writing code with it, I chose a "non-mainstream" IDE - NetBeans


NetBeans installation

Originally, I wanted to mention it in one sentence, but found that there are two steps that must be mentioned:

1. The download button is on the right side of the homepage. If you don't see it, you may click "NetBeans IDE" in the navigation bar above, and you will be at a loss after seeing a bunch of introductions;

download button

2. The download page provides us with multiple versions, we choose the second one, the version with Java EE (As for what Java EE is, check it yourself, it doesn’t matter if you don’t understand, you know that this version can write Java Web server programs on the line).

version selection

I won't go into details about the installation after downloading.


Create and configure a project

1. Create a new project

Open the IDE, File -> New Project

New Project

In the pop-up window, select Java Web on the left, select Web Application on the right, and click Next

step 1

In this step, enter your project name, select the project location (you can create a WorkSpace folder like me), and click Next

step 2

In this step, the default settings should be the same as the picture below, otherwise you need to add a server, and then click Next

step 3

In this step, we don’t use any frameworks (those are for optimization, let’s run through the basic process first), then click Finish

step four

2. Configuration before writing

After the new project is completed, the default index.jsp should be automatically opened on the right side, we don’t need it, it is the default page for writing websites, so click the “X” in the upper right corner to close it.

close index.jsp

Now let's add a configuration file to our project (I don't know why it is not generated directly when creating a new project)

Select our project, then right click, and select New -> Standard Deployment Descriptor (web.xml) in the pop-up menu

New configuration file

In the pop-up window, we click Finish (because they are all default and cannot be changed)

set configuration file

After that, we will see that the configuration file directory is automatically opened on the left, and there is a web.xml file in it, and the file is automatically opened on the right, and you can see the contents inside

web.xml

3. Introduce dependent packages

The so-called "standing on the shoulders of giants", we can not all the original code, if there is a direct reference to the results of predecessors, there is no need to reinvent the wheel. Our project needs to depend on the following packages, so it needs to be imported. This is a very important step. If you don't do it, you will report various errors that the class cannot be found and the file cannot be found when programming.

We are going to use the following 8 .JAR files

external dependencies

The first 6 are JSONObject packages, which are a collection, 6 are in the same compressed package, go to the following address to download,
link password: pa10

The seventh is the MySQL driver package, go to the following address to download
the link Password: je2o

The eighth is the Servlet API package, go to the following address to download
the link Password: 6s1t

ok, after downloading these packages, we create a lib folder under the project path, and put the 8 .JAR files just downloaded into it

Create a lib folder

This is not over yet, we still need to introduce them into the project.
Right click on library -> Add JAR/Folder

Add JAR/folder

In the pop-up window, find the lib folder, select all JAR files, then select the relative path on the right, and finally click Open

Import all JARs

After completion, we click on the library folder, and we can see that all external dependencies have been imported into the library
library

4. Create package

Click the open source package and we can see that there is a gray default package inside. It is not recommended to use the default package. We create our own package. Right-click Source Package -> New -> Java Package

create package

In the pop-up window, modify the package name, you don’t have to be like me, but the format is generally: net/com . [company name]. group name. application name

Package names

At this point, we see that the default package in the source package disappears and is replaced by the package we just created. The gray color is because it is empty. After creating a class and entering it, it will become a normal color.

Bag


Let's make it happen!

For the convenience of explanation, we aim to write a user login function.
To achieve simple user login, we can write two classes, and I will explain them separately below.

1. User entity class - User

User class, this class is generally called Java Bean, which defines various fields of the user and then encapsulates them. The code is posted below:

public class User {
    
    

    //用户姓名
    private String userName;

    //用户密码
    private String password;

    public String getUserName() {
    
    
        return userName;
    }

    public void setUserName(String userName) {
    
    
        this.userName = userName;
    }

    public String getPassword() {
    
    
        return password;
    }

    public void setPassword(String password) {
    
    
        this.password = password;
    }
}

2. Processing login request - LoginServlet

This class is our top priority, it is the class that handles requests from clients and sends responses back. For an introduction to Servlet, please go to the prerequisite knowledge required in this article .

①The
creation process of creating a Servlet is as follows, see the picture ↓
Create Servlets

②Modify the Servlet name
Modify the Servlet name in the pop-up interface, then click Next, do not click Finish! ! !

Change the Servlet name

③Configure Servlet deployment
If you click Finish in the previous step, you will skip this step, and then you need to deploy manually. If you forget to deploy, your request will not be responded, and you will not even find the error!
Select the Add information to deployment descriptor (web.xml) check box and click Finish.

Configure Servlet Deployment

At this time, open web.xml, and you will see that these things have been added to it

Changes in web.xml

Go back to LoginServlet, verify whether the account password in the request is correct, and then return the verification result as a response. For the sake of simplicity in programming, we do not connect to the database here, but write the account password in the code and make a simple judgment. The code is given below:

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;

/**
 * 测试登录Servlet
 *
 * @author Implementist
 */
public class LoginServlet extends HttpServlet {
    
    

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    
    

        // 设置响应内容类型、请求和相应的字符集
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");

        try (PrintWriter out = response.getWriter()) {
    
    

            //获得请求中传来的用户名和密码
            //从请求链接中的username=xxx&password=yyy取得
            String username = request.getParameter("username").trim();
            String password = request.getParameter("password").trim();

            //验证账号密码是否正确且匹配
            Boolean loginSuccess = verifyLogin(username, password);
			
			//根据登录验证的结果返回相应内容
			if (loginSuccess) {
    
    
            	out.write("Success");
			} else {
    
    
				our.write("Fail");
			}
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    
    
        //为简便起见,Get请求的处理直接调用Post请求
        doPost(request, response);
    }

    /**
     * 模拟登录验证,判断用户名是否imple,同时密码是否123
     *
     * @param username 用户名
     * @param password 密码
     */
    private Boolean verifyLogin(String username, String password) {
    
    
    	return username.equals("imple") && password.equals("123");
    }
}

Ok, after writing this, the server-side login function request response is realized, remember to press Ctrl+S to save, but this is not finished, we need to package this project, and then put it under the path of Tomcat, the following are the steps

Pack

Right click on our project -> Clean and Build

clean and build
After the build is complete, we can see that there is a .war file in the dist folder , which is the "war package" we need
.WAR file


postscript

1. As I was writing today, it suddenly occurred to me that maybe JSONObject needs to write a separate blog post, but it shouldn’t be a problem to just take pictures of cats and tigers, so I’ll talk about it when I’m free;

2. Every time you modify the program, remember to save -> clean and build -> deploy, then close and restart Tomcat in the XAMPP control panel, and it will take effect.

3. I finally finished writing today. This post has been written for several days, and it seems to be relatively long. Let’s just read it this way.

4. Let’s talk about why there have been more questions about Java Web recently. I just suddenly discovered that the download links of the 8 jar packages I gave above have all started to charge, and one is blacker than the other. The jar package you made up yourself may be incompatible or wrong, so there will be various errors. Don't be impatient everyone, I will upload my jar package to the cloud disk later today, and then change the link.
——2018.03.14

Guess you like

Origin blog.csdn.net/Mr_Megamind/article/details/109566889