JavaWeb Jump and Session Tracking

Servlet jump

     1.forward---RequestDispatcher interface

          forward(ServletRequest request, ServletResponse response)---This method is used to transfer the request from one Servlet to another Web resource [Servlet program/html/JSP]. [Request forwarding]

          forward belongs to the RequestDispatcher interface

          The Http Servlet Request interface inherits a method RequestDispatcher getRequestDispatcher (String path) to obtain the RequestDispatcher object from the Servlet Request interface.

          Parameter String path---target path [must start with "/" to indicate the root directory of the current web application]

          It should be noted that the contents of the WEB-INF directory are also visible to the RequestDispatcher object. Therefore, the resource passed to the getRequestDispatcher(String path) method can be a file in the WEB-INF directory

          RequestDispatcher interface object=Http Servlet Request interface object.getRequestDispatcher (String path);

          RequestDispatcher接口对象.forward(ServletRequest request,ServletResponse response).

          Passing data through the HttpServletRequest object.

          Methods of the HttpServletRequest object

          void setAttribute(String name,Object o) is used to associate an object with a name and store it in the ServletRequest object

          Object getAttribute(String name) is used to return the attribute object with the specified name from the ServletRequest object

          void removeAttribute(String name) is used to remove the attribute of the specified name from the ServletRequest object

    

E.g:

package com.wangxing.servlet;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OneServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("------------------");
		//forward(ServletRequest request,ServletResponse response);该方法用于将请求从一个servlet传递给另一个web资源【Servlet程序/html/JSP】
		//forward(ServletRequest req,ServletRresponse resp)方法是RequestDispatcher中的方法
		//HttpServletRequest中有获得RequestDispatcher对象的方法
		//getRequestDispatcher();
		/*
		RequestDispatcher requestDispatcher = req.getRequestDispatcher("/test.html");
		requestDispatcher.forward(req, resp);
		
		req.getRequestDispatcher("/onther").forward(req, resp);
		*/
		//void setAttribute(String name,Object o);用于将一个对象与另一对象关联后存储到ServletRequest对象中
		req.setAttribute("name", "zhangsan");
		
		req.getRequestDispatcher("/other").forward(req, resp);
	}
	
}
package com.wangxing.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OtherServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//Object getAttribute(String name);用于从ServletRequest对象中返回指定名称的属性对象
		String name = (String) req.getAttribute("name");
		System.out.println("OtherServlet----name==" + name);
	}
	
}

      2.Redirect----HttpServletRespone.sendRedirect()[Redirect]

            The HttpServletResponse interface defines a sendRedirect(String path) method. The request is passed from one Servlet to another Web resource [Servlet program/html/JSP]

E.g:

package com.wangxing.servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OneServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("---------------");
		//sendRedirect(String path);方法请求从一个Servlet传递给另一个Web资源【Servlet程序/html/JSP】
		//resp.sendRedirect("test.html");
		//resp.sendRedirect("/test.html");错误
		
		req.setAttribute("name", "lisi");
		resp.sendRedirect("other");
	}
	
}
package com.wangxing.servlet;


import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class OtherServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//Object getAttribute(String name);用于从ServletRequest对象中返回指定名称的属性值
		String name = (String) req.getAttribute("name");
		//sendRedirect不能传递数据因为他是重定位
		System.out.println("OtherServlet--name=="+name);
		
	}
	
}

            The above test is to access Html/other Servlet by the Servlet program

            Can we access the Servlet program through html?

            Yes, there are three ways

            1. Through html form elements

            2. Hyperlink via html

            3. Send asynchronous request through javascript ajax

      E.g:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户登录</title>
</head>
<body>
<!-- 
	<center>
		<form action="login" method="post">
			<table border="1px">
				<tr align="center">
					<td colspan="2"><h1>用户登录</h1></td>
				</tr>
				<tr align="center">
					<td>账号:</td>
					<td><input type="text" name="username"/></td>
				</tr>
				<tr align="center">
					<td>密码:</td>
					<td><input type="password" name="password"/></td>
				</tr>
				<tr align="center">
					<td colspan="2"><input type="submit" value="登录"/></td>
				</tr>
			</table>
		</form>
	</center>
	 -->
	 <h1><a href="login?username=zhangsan&password=123">用户登录</a></h1>
</body>
</html>

package com.wangxing.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//得到账号和密码
		String  name=req.getParameter("username");
		String  pass=req.getParameter("password");
		System.out.println("name=="+name+" "+"pass=="+pass);
	}
}

the difference:

RequestDispatcher.forward(req, resp)

HttpServletRespone.sendRedirect()

Request forwarding

Redirect

The same request object is used

Different request objects are used

The url in the browser address bar will not change

The url in the browser address bar will change

Data can be passed through the HttpServletRequest object

Can not pass data through the HttpServletRequest object

When setting the target path, "/" can be written or not written

"/" must not be written when setting the target path

Rely on ServletRequest interface

Rely on HttpServletRespone object

Session tracking

     1. Why do you need session tracking?

          Use the http request sent by the browser . The http request uses the http protocol, and the http protocol is a stateless protocol . It will not actively record who the user using the http protocol is. Once the request is sent successfully, the server will make After the response, the link between the browser and the server will disappear at this time, and the server does not know where the request comes from and who sent it. So at this time we need to record/save the status of the request/link. The process of realizing this record/save request/link status is called session tracking .

     2. What is session tracking?

          The process by which the server handler realizes the recording/saving of the request/link status is called session tracking .

     3. What are the four session tracking technologies , and their respective advantages and disadvantages?

          1. URL rewriting: rewrite the id information of the user Session into the URL address to identify different users on the server side.

               https://blog.csdn.net/qq_33098039/article/details/78184535?sessionid=123456

               URL rewriting can still work when the client disables cookies or does not support cookies.

          2. Hide the form field: add the id information of the user session to the HTML form element <input type="hidden" name="" value=""/ > and submit it to the server. This form element is not displayed on the client side. When browsing I can't see it, there is in the source code.              

          3.Cookie

               Cookie is a small piece of information sent by the web server to the client. The client can read the information and send it to the server when requested by the client to identify the user. The server is created and saved on the browser side, cannot cross domain names, and is limited in size and quantity . The client can save this Cookie object in two ways. One method is to save it in the client's memory, called a temporary cookie, which will disappear after the browser is closed. Another way is to save it on the client's disk, called a permanent cookie. In the future, as long as the client visits the website, the cookie will be sent to the server again, provided that the cookie is within the validity period. In this way, the tracking of customers is realized. Cookies can be banned.

          4.Session

               Each user has a different session, which cannot be shared between users. It is exclusive to each user. Information can be stored in the session. Save it on the server side. Need to solve the problem of sharing among multiple servers. If the content of the Session is too complex, it may cause memory overflow when a large number of clients access the server. Therefore, the information in the Session should be as concise as possible.

               Session relies on Cookie. If Cookie is disabled, session will also be invalid.

               When a user first transmits an http request to the server, the server creates a session object, to generate a sessionID to identify the session object, and then put into the sessionID Cookie sent to the client, sending the next http request to the server when , The http request will be sent to the server together with the sessionID obtained for the first time , and different users will be identified on the server side.

          The above session tracking process is similar to the process of storing items in the lockers at the entrance of the supermarket when we go to the supermarket.

     4. What is the difference between Session and Cookie ?

Cookie

Session

The data is created by the server and saved on the browser side

Data on the server

cookies are not very secure

Session is safe

Cookies should be used to reduce server performance.

Do not consider reducing server performance . Can use Session

The data saved by a single cookie cannot exceed 4K

no limit

 

Session relies on Cookie. If Cookie is disabled, session will also be invalid.

     5. Common methods of HttpSession

          HttpSession interface in Servlet

               1. Get the HttpSession interface object through the getSession() method of the HttpServletRequest object

               2. Common methods of HttpSession interface objects

Method declaration

Function description

String  getId()

This method is used to get the sessionID

long  getCreationTime()

This method is used to get the creation time of the session object [ms]

long getLastAccessedTime()

This method is used to get the last access time of the session [ms]

int getMaxInactiveInterval()

This method is used to get the maximum inactivity time of the session [sec]

boolean isNew()

This method is used for whether the session object is a new session object

void setAttribute(String args0, Object  args1);

This method is used to save data to the created session object

Object getAttribute(String args0);

This method is used to obtain the specified data saved in the session object

void

removeAttribute(String args0);

This method is used to remove the specified data stored in the session object

void invalidate()

This method is used to destroy the session object

For example: the login operation uses the HttpSession object

package com.wangxing.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
 * 绘制登录界面的Servlet
 * @author Administrator
 *
 */
public class LoginUIServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//设置字符集
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		//得到输出流
		PrintWriter out = resp.getWriter();
		out.println("<!DOCTYPE html> "); 
		out.println("<html>"); 
		out.println("<head>"); 
		out.println("<meta charset=\"UTF-8\">"); 
		out.println("<title>用户登录</title>"); 
		out.println("</head>"); 
		out.println("<body>"); 
		out.println("<center>"); 
		//得到session对象
		HttpSession session = req.getSession();
		//显示session信息
		showsessioninfo(out,session);
		out.println("<hr>");
		Object errorobj = req.getSession().getAttribute("error");
		if(errorobj != null){
			out.println("<font color=\"red\">"+(String)errorobj+"</font>");
		}
		out.println("<form action=\"login\" method=\"post\">"); 
		out.println("<table border=\"1px\">"); 
		out.println("<tr align=\"center\">"); 
		out.println("<td colspan=\"2\"><h1>用户登录</h1></td>"); 
		out.println("</tr>"); 
		out.println("<tr align=\"center\">"); 
		out.println("<td>账号:</td>"); 
		out.println("<td><input type=\"text\" name=\"username\"/></td>"); 
		out.println("</tr>"); 
		out.println("<tr align=\"center\">"); 
		out.println("<td>密码:</td>"); 
		out.println("<td><input type=\"password\" name=\"password\"/></td>"); 
		out.println("</tr>"); 
		out.println("<tr align=\"center\">"); 
		out.println("<td colspan=\"2\"><input type=\"submit\" value=\"登录\"/></td");
		out.println("</tr>"); 
		out.println("</table>"); 
		out.println("</form>"); 
		out.println("</center>"); 
		out.println("</body>"); 
		out.println("</html>"); 
		out.close();	
	}
	/**
	 * 显示session信息
	 * @param out
	 * @param session
	 */
	private void showsessioninfo(PrintWriter out, HttpSession session) {
		out.println("<table border=\"1px\">");
		out.println("<tr align=\"center\">");
		out.println("<td colspan=\"2\">");
		out.println("<h1>session信息</h1>");
		out.println("</td>");
		out.println("</tr>");
		out.println("<tr align=\"center\">");
		out.println("<td>sessionID:</td>");
		out.println("<td>"+session.getId()+"</td>");
		out.println("</tr>");
		out.println("<tr align=\"center\">");
		out.println("<td>session对象的创建时间:</td>");
		out.println("<td>"+gettime(session.getCreationTime())+"</td>");
		out.println("</tr>");
		out.println("<tr align=\"center\">");
		out.println("<td>session的最后访问时间:</td>");
		out.println("<td>"+gettime(session.getLastAccessedTime())+"</td>");
		out.println("</tr>");
		out.println("<tr align=\"center\">");
		out.println("<td>session的最大不活动时间:</td>");
		out.println("<td>"+session.getMaxInactiveInterval()+"秒</td>");
		out.println("</tr>");
		out.println("<tr align=\"center\">");
		out.println("<td>session对象是否为新:</td>");
		out.println("<td>"+session.isNew()+"</td>");
		out.println("</tr>");
		out.println("</table>");	
	}
	/**
	 * 得到时间
	 * @param creationTime
	 * @return
	 */
	private String gettime(long creationTime) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
		return sdf.format(new Date(creationTime));
	}
	
}
package com.wangxing.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理登录业务
 * @author Administrator
 *
 */
public class LoginServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//得到账号和密码
		String name = req.getParameter("username");
		String pass = req.getParameter("password");
		if("zhangsan".equals(name) & "123456".equals(pass)){
			//req.setAttribute("username", name);
			//req.getRequestDispatcher("success").forward(req, resp);
			req.getSession().setAttribute("username", name);
			resp.sendRedirect("success");
		}else{
			//req.setAttribute("error", "用户名密码有误");
			//req.getRequestDispatcher("loginui").forward(req, resp);
			req.getSession().setAttribute("error", "用户名密码有误!");
			resp.sendRedirect("loginui");
		}
	}
	
}
package com.wangxing.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
 * 绘制登录成功页面的Servlet
 * @author Administrator
 *
 */
public class SuccessUIServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		resp.setCharacterEncoding("utf-8");
		PrintWriter out = resp.getWriter();
		out.println("<!DOCTYPE html>");
		out.println("<html>");
		out.println("<head>");
		out.println("<meta charset=\"UTF-8\">");
		out.println("<title>登录成功</title>");
		out.println("</head>");
		out.println("<body>");
		out.println("<center>");
		Object userObj = req.getSession().getAttribute("username");
		if(userObj == null){
			//req.getRequestDispatcher("loginui");
			resp.sendRedirect("loginui");
		}else{
			out.println("<h1>"+(String)userObj+",登录成功</h1>");
		}
		out.println("</center>");
		out.println("</body>");
		out.println("</html>");
		out.close();
	}
	
}
package com.wangxing.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 处理退出业务 
 * @author Administrator
 *
 */
public class LogoutServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.getSession().invalidate();
		resp.sendRedirect("loginui");
	}
	
}

               3. The difference between Get and Post?

Get

Post

get transmitted through the address bar

Post is transmitted through messages and can also receive data in the address bar

The get parameter has a length limit (limited by the length of the url)

There is no limit to post, it must be post when uploading files

GET generates a TCP packet

The browser will send the http header and data together, and the server will respond with 200 (return data);

POST generates two TCP packets

The browser sends the header first, the server responds with 100 continue, the browser sends data, and the server responds with 200 ok (return data).

Safety difference

Good security

When querying data, it is recommended to use the Get method

When adding, modifying or deleting data, it is recommended to use the Post method

GET is harmless when the browser rolls back

POST will submit the request again when the browser rolls back

The URL address generated by GET can be Bookmarked

The URL address generated by POST cannot be Bookmarked

GET requests will be actively cached by the browser

POST will not be actively cached by the browser unless it is manually set.

GET requests can only be url-encoded

POST supports multiple encoding methods.

GET request parameters will be completely retained in the browser history

The request parameters in the POST will not be kept in the browser history.

The data type of the parameter, GET only accepts ASCII characters

POST has no limits

GET parameters are passed through the URL

POST放在Request body中

               4.中文乱码的处理

                   网页----<meta charset="utf-8">

                    Eclipse---window-->preferences--->General---->workspace---->Text file encoding

                    Tomcat---默认的字符编码“iso8859-1”

                   服务器/conf目录/server.xml文件

                    <Connector port="8080" protocol="HTTP/1.1"

                    connectionTimeout="20000"

                    redirectPort="8443"  URIEncoding="UTF-8"/>

               1.页面提交到Servlet处理程序中的中文为乱码

                    Post提交方式  request.setCharacterEncoding(“utf-8”);

                   GET方式  String name = new String(name.getBytes(“iso8859-1”),“utf-8”);

               2.Servlet处理程序向页面输出的中文为乱码

                    response.setCharacterEncoding("utf-8"); response.setHeader("Content-Type","text/html;charset=utf-8");

Guess you like

Origin blog.csdn.net/m0_49935332/article/details/115017642