Servlet Notes 2

One: request forwarding, redirection

 

 

1. Forward:

I. Page jump: request.getRequestDispatcher("target url-pattern").forward(request,response);

 

 

II. When forward jumping, jumping inside the server, the address bar remains unchanged, it belongs to the same request

 

III. Data transfer: //forward represents a request, the address bar remains unchanged, and jumping inside the server can share the data in the request scope.

1). Request scope: It has space to store data, and the scope is valid for one request (a request can be forwarded multiple times, and once it is responded, it will end).

a. After the data is stored in the request, it can be obtained at any position during a request.

b. Any data can be passed (basic data types, objects, collections, arrays).

2). Save data: request.setAttribute("key", value); //Store in the request scope in the form of a key-value pair. The key is of type String, and the value is of type Object.

3). Get data: request.getAttribute("key"); //Access the value of Object type through the key of String type.

 

2. Redirect:

I. Page jump: response.sendRedirect("target URI");

 

 

II. When redirect jumps, the address bar changes, which means that the client resends the request to the server, which belongs to two requests, and the data cannot be shared.

 

III. Data transfer:

1). The response has no scope and can pass some simple text data in the form of URL splicing.

2). Data transfer: response.sendRedirect("project name + resource name?key="+value); //must be this text

3). Get data: request.getParameter("key");

 

3. Use basis: According to whether data needs to be passed between the two servlets, if the data needs to be passed, select forwarding; if there is no need to pass data, select redirection.



Two: The server records the user status

1. Concept: Web applications (websites) can identify users.

 

2. Common applications:

I. No login required.

II. Record the username and password.

III. Identify the user who owns the shopping cart.

3. Cookie technology

I. Concept: Text data is sent by the server to the client and stored in the user's local computer (browser, local file). User identifiable.

II. Creation of Cookies:

Cookie c = new Cookie("key" , "value");

 

III. Set the maximum survival time:

c.setMaxAge(60*60*24*7);

 //Set cookie lifetime (negative number: not created), (zero: browser closed), (positive number: seconds)

 

IV. Setting the path:

c.setPath("/cookie access path");

//The default path is the path of the servlet that created this cookie.

 

V. Sending Cookies:

response.addCookie(c);

 

VI. Obtaining Cookies:

Cookie[] cks = request.getCookies();

 //Get all cookies sent by this website

VII. Questions:

1). Plaintext storage, insecure (cannot store important data).

2). Can be disabled by Client.

3). Storage capacity 4KB.

4). Chinese is not supported by default (use the following methods to decode and encode Chinese in cookies)

java.net.URLEncoder.encode();解码。

java.net.URLDecoder.decode();编码

 

VIII.使用场景:辅助功能。



4.HttpSession


①. javax.servlet.http.HttpSession接口,由Tomcat提供实现。

②. 更安全的记录用户的状态。

③. Session原理:服务器会为每一次会话,分配一个HttpSession对象;同一个浏览器发起的多次请求,同属于一次会话(HttpSession)。

 

 

④.session作用域:拥有存储数据的空间,作用范围是一次会话有效(使用同一浏览器发出的多次请求,一旦关闭浏览器,则结束)。

I.可以将数据存入session中,在一次会话的所有请求中进行获取。

II.可传递任何数据(基本数据类型、对象、集合、数组)。

 

 

⑤. 数据存取:

I.获得HttpSession对象:HttpSession session = request.getSession();

 

II.存数据:session.setAttribute("key" , value); //以键值对形式存储在request作用域中key为String类型,value为Object类型。

 

III.取数据:session.getAttribute("key"); //通过String类型的key访问Object类型的value。

 

⑥. Session对比Request:

I. request一次请求有效,请求改变,则request改变。

II. session一次会话有效,浏览器改变,则session改变。

 

⑦. Session的生命周期:

I. 开始:第一次使用到Session的请求产生,则创建Session。

II. 结束:

1). 浏览器关闭,则失效。

2). Session超时,则失效。

session.setMaxInactiveInterval( seconds ); // [ ɪn'æktɪv ] 设置最大存活时间(单位:秒)

3). 手工销毁,则失效。

session.invalidate(); //登录退出、注销

 

⑧.Session的实现原理【重点】:首次使用到HttpSession时,会自动创建Session,并创建Cookie将SessionId发送回客户端。

 

注意:Cookie被禁用的话,无法保存JSESSIONID,也就无法找到原有的Session对象。

⑨url重写:(客户端禁用Cookie时,我们可以使用URL重写的方式找到Session)

1.response.encodeURL("url"); //会在原有的url后面以拼接特殊参数,由tomcat识别。

 

2.重写方式:

<a href="response.encodeURL('url')"></a>

<form action="response.encodeURL('url')"></form>

 

3.注意:url重写是嵌套了一段Java代码,和标签一并动态生成,无法使用HTML静态页面完成,必须使用Servlet或JSP。

4.转发无需URL重写、重定向必须URL重写。


5. 资源访问:

①. URL:在整个互联网中定位一个资源

(protocol://ip:port/app/source)地址栏、外部超链接

http://localhost:8088/AccountSystem/showAllAction

http://localhost:8088/AccountSystem/login.html

 

②. URI:在一台服务器中定位一个资源(/app/source)

内部超链接、表单、sendRedirect();

/AccountSystem/showAllAction

/AccountSystem/login.html

 

③. url-pattern:在一个项目中定位一个资源

(/source)request.getRequestDispatcher(url-pattern)

/showAllAction

/login.html



六:Session和Cookie实战

①用户第二次登录时,Cookie自动为表单添加存储在本地的ID和PWD

public class ManagerLoginJsp extends HttpServlet {

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		
		String id ="";
		String pwd ="";
		
		//获取Cookie中的值  ->实现记录登录账号的密码
		Cookie[] cookie=request.getCookies();
		if(cookie!=null && cookie.length>0){
			for(Cookie c:cookie){
				if(c.getName().equals("id"))
					id=c.getValue();
				if(c.getName().equals("pwd"))
					pwd=c.getValue();
			}
		}
		//设置响应页面		
		Writer out=response.getWriter();
		out.write("<html>");
		out.write("<body>");
		out.write("<form action='/BankManager/managerLogin' method='post'> ");
		out.write("id:<input type='text' name='id' value='" +id + "'/><br/>");
		out.write("pwd<input type='password' name='pwd' value='" + pwd + "'/><br/>");
		out.write("<img src='code'  />");
		//指向绘制验证码的Servlet

		out.write("<input type='submit' value='提交'/>");
		out.write("</form>");
		out.write("</body>");
		out.write("</html>");
		
		out.close();
		
	}
	
}

②:Cookie记录用户登录密码和Session用户登录状态

public class ManagerLoginAction extends HttpServlet {
	private static final ManagerService service=new ManagerServiceImpl();
	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");    response.setContentType("text/html;charset=UTF-8");
		/*
		 * 1:设置请求数据的解码方式和响应页面的编码方式
		 * (必要时设置请求的urIEncoding->TomCat的配置文件)
		 * 2:获取请求的参数
		 * 3:调用Service层方法处理业务。一个业务对应一个功能。
		 * 4:页面跳转根据是否需要传值 选择请求转发或请求重定向。
		 * 
		 */
		String id=request.getParameter("id");
		String pwd=request.getParameter("pwd");

		Manager manager=service.login(id);
		 
		if(manager!=null && pwd.equals(manager.getPwd())){
			Cookie cook1=new Cookie("id",id);
			Cookie cook2=new Cookie("pwd",pwd);
			cook1.setMaxAge(60*60*24*7);
			cook2.setMaxAge(60*60*24*7);
			response.addCookie(cook1);
			response.addCookie(cook2);
			//通过请求获取Session、Cookie
			//登陆成功后记录用户的登录状态
			HttpSession session=request.getSession();
			session.setAttribute("admin", manager);
			response.sendRedirect("/BankManager/showAllAction");
		}else{
			response.sendRedirect("/BankManager/Login.html");
		}
		
		
	}

}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325461064&siteId=291194637