session, simple usage of filter, file upload

Keywords: Eclipse servlet

1. Open eclipse to establish a dynamic website

2. Create a new index.html under WebContent and modify the access path

(1) Normally, you need to add an html name, such as http://localhost:8080/index.html To access the page, now want to http://localhost:8080 Direct access

(2) Write code in html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Landing page</title>
<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
</head>
<body style="padding:300px;">

  user name:<input type="text" id="username"/><br/><br/>
  password:&nbsp&nbsp&nbsp<input type="password" id="password"/><br/><br/>
  <button onclick="login()">Sign in</button>     

<script>
 function login(){                                //Clicking the button will trigger the function
	 var username=$("#username").val(); / / enter the username in the browser
	 var password=$("#password").val();
	 console.log("username:"+username);       //Print the user name in the browser's console
	 console.log("password:"+password);       //Note that there is $, and jquery should be referenced in the header
//Only after the trigger content is obtained can it be submitted to the background
	
 }
</script>
</body>
</html>

3. Start writing the background servlet, create a servlet package under src, and create a new servlet named LoginServlet under the package

Enter the code in the doGet of the servlet

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String username =request.getParameter("username");   //Receive the user name (input by the browser) from the front end and "try to be the same as the name in # the back of html"
		String password =request.getParameter("password");
		System.out.println("username:"+username);            //Output the user name in the background (see Console at the bottom)
		System.out.println("password:"+password);
		
		response.getWriter().append(username+"---"+password);//Pass these processed to the front end
	}

4. Deal with the foreground, so that the front and back ends can interact, and in html

<script>
 function login(){                            
	 var username=$("#username").val();      
	 var password=$("#password").val();
	 console.log("username:"+username);       
	 console.log("password:"+password);
	 $.post(
				"LoginServlet",
				{
					"username":username,
					"password":password,
				},
				function(data){
					console.log(data);
							
				});
 }
</script>

 

The post submission method is the doPost method in the background, and then the doGet method

(click the user name and password input box, trigger the login function, get it through jquery, and request the background to print out the parameters and submit them to the foreground by post submission)

  5. Login logic addition: fixed only allowed: user name: admin   Password: qcby0810 returns successful login, others return wrong user name or password

(1) If the database is involved in the background, this function is not required

(2) Front and rear console codes

  6.session: it is a collection on the server side that can store anything. The most important feature of session is that it can identify customers     Household.

Common API s:

//Get session ID
String id = session.getId();

//Stored value
session.setAttribute(name, value);

//Value
session.getAttribute(name);

//Remove value
session.removeAttribute(name);

(1) Create a new html called home.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
This is a home page
</body>
</html>

  (2) The new servlet is called HomeServlet

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
           response.sendRedirect("home.html"); //Jump to home page

	}

Modify the index page, log in successfully, jump to the HomeServlet background, and then enter home.html

function(data){
				   console.log(data);
					if(data=="0"){
						alert("Login succeeded!")
						window.location.href="HomeServlet";
					}
						else if(data=="1"){
						alert("User name error!")
							}
						else if(data=="2"){
							alert("Password error!")
								}
						else {
							alert("System exception")
								}

 --- At this time, even if you don't log in the user name and password (close the browser and re-enter the website at the background of HomeServlet, you can go in without realizing the function of user identification)

7. Add session function to realize user identification

(1) Change the LoginServlet and add a session statement

int r = 0;
		if(!"admin".equals(username)) {  
			System.out.println("User name error");
			r = 1;
		}
		if(r == 0 && !"qcby0810".equals(password)) {
			System.out.println("Password error");
			r = 2;
		}
		if(r == 0) {
			// Login succeeded
			// Get the unique ID of the session storage user, eg: user name
			HttpSession session = request.getSession();
			session.setAttribute("username", username);
		}
		// TODO Auto-generated method stub
		response.getWriter().append(r+"");

(2) Change HomeServlet and add session statement

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// Get the session object and store the user information
		HttpSession session = request.getSession();
		// Get value according to the specified key
		Object username = session.getAttribute("username");
		if(username == null) {
			// There is no user information in the session, which proves that the user has not logged in
			// Redirect to login page
			response.sendRedirect("index.html");
		}else {
		        // User information in session
			// Redirect to home page
			response.sendRedirect("home.html");
	
	}

  --- At this time, the function of user identification can be realized

8. Here is a question: Enter http://localhost:8080/home You can't access the home page, but input http://localhost:8080/home.html You can visit the home page to solve the problem

(1) Change home.html to the lib file. The implementation cannot be accessed directly and needs to be forwarded in the background

(2) Modify HomeServlet

  9. Add user page to realize business processing code

(1) Create "user.html" under WEB-INF and "UserServlet" under servlet

(2) Paste the doGet code of the HomeServlet directly to the UserServlet, modify only the last sentence and the server forwarding statement

  10. Filter

Filter filter is used to intercept requests and filter responses.

(1) Create a new filter under src

(2) Specify the path to intercept

meaning:

 

  (3) Converting interfaces in doFilter

  (4) Login verification of replication HomeServlet

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		// place your code here

		// pass the request along the filter chain
      System.out.println("Execute at work");
		
		HttpServletRequest re = (HttpServletRequest) request;
		HttpServletResponse rq = (HttpServletResponse) response;
		String uri = re.getRequestURI();
		// StringBuffer
		String url = re.getRequestURL().toString();
		System.out.println("current path url: "+url);
		System.out.println("==================================================");
		
		       // Get the session object and store the user information
				HttpSession session = re.getSession();
				// Get value according to the specified key
				Object username = session.getAttribute("username");
				if(username == null) {
					// There is no user information in the session, which proves that the user has not logged in
					// Redirect to login page
					rq.sendRedirect("index.html");
				}else {
				        // User information in session
					// Redirect to home page
					chain.doFilter(request, response);
				}
		
	}

  (5) Comment out the verification of UserServlet and HomeServlet and replace it with filter verification

(6) At this time, all pages are blocked, including the login page. You need to release the login page

11. File upload function

(1) Add form paragraph to home.html

  (2) The new servlet is called FileUploadServlet

If the folder does not exist, it will be added automatically

(3) html add path

(4) Modify FileUploadServlet

(5) Add file upload comment

(6) An error is reported, so the html is modified

 (7)

  (8) File upload function completed

Posted by s4salman on Wed, 10 Nov 2021 21:29:06 -0800