Select summary

Servlet

What is Servlet?

  Servlet: Server applet: applet .Servlet server is the server receives a request for the client and responds to the client program.

  Servlet java program is run on a Web server or application server, it is used as an intermediate layer between the database or application server and HTTP requests from the Web browser or other HTTP clients. The use of Servlet, you can collect user data from web forms, showing records from a database or other source, you can also create dynamic web pages.

  In practice, the concept of Servlet, divided into narrow and broad.

  Narrow Servlet is a small program.

  In fact, the broad servlet is a Java class is a class that implements the Servlet interface.

The role of the Servlet?

Servlet performs the following major tasks:

  1. The client reads the information (the information transmission request header). (Client data acquisition)
  2. Processing information (processed data)
  3. Response data (return data: data service, in response to the header information).

How to achieve Servlet:

Servlet: Java class is a class that implements the Servlet.

  1. Creating a class

  2. Implement the interface Servlet

    package com.sxt.controller;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServlet;
    
    public class ServletDemo01 extends HttpServlet  {
    
    	private static final long serialVersionUID = -2597540888550505998L;
    	
    	@Override
    	public void init() throws ServletException {
    		System.out.println("====init====");
    	}
    
    
    	@Override
    	public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    		System.out.println("====service====");
    		// 读取谁的?
    	}
    
    	@Override
    	public void destroy() {
    		System.out.println("====destroy====");
    	}
    
    }
    
  3. Registration Servlet

  4. Servlet configured to provide access method

      <!-- 注册Servlet -->
      <servlet>
      	<!-- servlet别名 -->
      	<servlet-name>ergou</servlet-name>
      	<!-- Servlet类的全路径 -->
      	<servlet-class>com.sxt.controller.ServletDemo01</servlet-class>
      </servlet>
      
      <!-- 配置Servlet 提供访问方式 -->
      <servlet-mapping>
      	<!-- servlet别名 -->
      	<servlet-name>ergou</servlet-name>
      	<!-- servlet的访问地址  -->
      	<url-pattern>/ergou.html</url-pattern>
      </servlet-mapping>
    

Servlet life cycle

  In the Servlet, Servlet is a singleton Each Servlet class, and only one object.

  init method, the default will be performed at the first visit and perform only once, usually used to initialize the Servlet information.

  detory method, the default will be executed when the server is stopped and only once, Servlet target for destruction.

  service method performed by default every time there is an access request, each request will be executed for processing a request.

  init ----> service ----> detory This is the Servlet life cycle.

note:

  Servlet is a singleton, so Servlet is not thread safe. Generally when using Servlet, does not recommend the definition of member variables.

Servlet implementation process

Servlet functionality

Receiving client information: HttpServletRequest

Form information form

package com.sxt.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

public class RequestServlet extends HttpServlet {
	
	private static final long serialVersionUID = 4858130557364545084L;
	/**
	 * 当是  get请求时  执行
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("doGet");
//		String userName = req.getParameter("userName");
//		String password = req.getParameter("password");
//		String selectName = req.getParameter("selectName");
//		String[] likes = req.getParameterValues("like");
//		String sex = req.getParameter("sex");
//		String textName = req.getParameter("textName");
//		
//		System.out.println("userName: "+userName);
//		System.out.println("password: "+password);
//		System.out.println("selectName: "+selectName);
//		System.out.println("likes: "+Arrays.toString(likes));
//		System.out.println("sex: "+sex);
//		System.out.println("textName: "+textName);	
	}
	
	/**
	 * 当是 post请求时 执行
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");
		System.out.println("doPost");
		String userName = req.getParameter("userName");
		String password = req.getParameter("password");
		String selectName = req.getParameter("selectName");
		String[] likes = req.getParameterValues("like");
		String sex = req.getParameter("sex");
		String textName = req.getParameter("textName");
		
		System.out.println("userName: "+userName);
		System.out.println("password: "+password);
		System.out.println("selectName: "+selectName);
		System.out.println("likes: "+Arrays.toString(likes));
		System.out.println("sex: "+sex);
		System.out.println("textName: "+textName);
		
		// 获取所有表单数据的  name值
		Enumeration<String> parameterNames = req.getParameterNames();
		//遍历所有的name值
		while(parameterNames.hasMoreElements()) {
			System.out.println("name值:"+parameterNames.nextElement());
		}
		System.out.println("==========================");
		//将 所有的请求参数 封装成一个Map 集合
		Map<String, String[]> parameterMap = req.getParameterMap();
		//获取所有的key
		Set<String> names = parameterMap.keySet();
		for (String name : names) {
			System.out.println(name +":"+Arrays.toString(parameterMap.get(name)));
		}
		Map<String, Object> paramMap = paramMap(parameterMap);
		System.out.println("转化后的:"+paramMap);
		
	}
	
	/**
	 * 将存储封装一个map
	 * @return
	 */
	public Map<String,Object> paramMap(Map<String, String[]> parameterMap){
		Map<String,Object> map = new HashMap<String, Object>();
		//获取所有的key
		Set<String> keys = parameterMap.keySet();
		for (String key : keys) {
			String[] values = parameterMap.get(key);
			Object value = null;
			if(values != null &&values.length == 1 && values[0] != "") {
				value = values[0];
			}else if(values != null && values.length > 1) {
				List<String> data = new ArrayList<String>();
				for (String v : values) {
					data.add(v);
				}
				value = data;
			}
			map.put(key,value);
		}
		return map;
	}

}

Scope obtain information

package com.sxt.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

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

public class AttributeServlet extends HttpServlet {
	
	private static final long serialVersionUID = 4858130557364545084L;
	/**
	 * 当是  get请求时  执行
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("doGet");
		//getAttribute(name值) : 根据name值从 request 作用域中 获取对应值
		//getAttributeNames() : 获取作用域中,所有属性名称
		//setAttribute(name,value) : 设置request作用域中的属性值
		// 设置属性值
		req.setAttribute("key1", "value1");
		req.setAttribute("key2", "value2");
		req.setAttribute("key3", "value3");
		System.out.println(""+req.getAttribute("key1"));
		
		Enumeration<String> attributeNames = req.getAttributeNames();
		while(attributeNames.hasMoreElements()) {
			System.out.println(attributeNames.nextElement());
		}
	}
	
	/**
	 * 当是 post请求时 执行
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	}
	
}

For additional scope objects

package com.sxt.controller;

import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class ScopeServlet extends HttpServlet {
	
	private static final long serialVersionUID = 4858130557364545084L;
	/**
	 * 当是  get请求时  执行
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("doGet");
		//获取其他作用域 
		//获取session作用域
		HttpSession session = req.getSession();
		session.setAttribute("sessionKey", "sessionValue");
		// 获取 application 作用域
		ServletContext application = req.getServletContext();
		application.setAttribute("applicationKey", "applicationValue");
	}
	
	/**
	 * 当是 post请求时 执行
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	}
	
}

Access to network information request

package com.sxt.controller;

import java.io.IOException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class HttpInfoServlet extends HttpServlet {
	
	private static final long serialVersionUID = 4858130557364545084L;
	/**
	 * 当是  get请求时  执行
	 */
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 获取请求的方法  :  get   post
		String method = req.getMethod();
		System.out.println(method);
		// 获取请求的资源路径   
		String uri = req.getRequestURI();
		System.out.println(uri);
		// 获取请求URL地址  http://127.0.0.1:8080/sxt/servlet.do
		String url = req.getRequestURL().toString();
		System.out.println(url);
		// 请求端口
		int remotePort = req.getRemotePort(); //客户端端口
		System.out.println(remotePort);
		int localPort = req.getLocalPort(); //服务器本地端口
		System.out.println(localPort);
		String remoteHost = req.getRemoteHost(); //客户端IP
		String localAddr = req.getLocalAddr(); // 服务器IP
		System.out.println("remoteHost:"+remoteHost);
		System.out.println("localAddr:"+localAddr);
		//设置请求的编码
		req.setCharacterEncoding("UTF-8");
		//获取请求头信息 :  Map  :  key -- value
		String language = req.getHeader("Accept-Language");
		System.out.println(language);
	}
	
	/**
	 * 	当是 post请求时 执行
	 */
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	}
	
}

Internal redirects and forwards

//resp.sendRedirect("地址");  重定向
resp.sendRedirect("scope.jsp");
// 内部转发  req.getRequestDispatcher("scope.jsp").forward(req, resp); 
req.getRequestDispatcher("scope.jsp").forward(req, resp);

Getting file information

req.getPart("name") : 根据name值,获取对应part数据

Response data to the client: HttpServletResponse

package com.sxt.controller;

import java.io.IOException;

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

public class ResponseServlet  extends HttpServlet{
	private static final long serialVersionUID = -2958733507466419241L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 获取打印流
		//resp.getWriter();
		// 获取输出流
		resp.getOutputStream();
		// 设置 cookie
		resp.addCookie(new Cookie("name","value"));
		//设置编码
		resp.setCharacterEncoding("UTF-8");
		//设置响应头信息
		resp.addHeader("token", "xxxxx");	
	}
}

MVC model:

MVC initially present in the desktop program, M is a business model, the user interface means V, C is the controller, the purpose of use of MVC
is V and M to achieve separation of the code, so that the same program can be used different forms. For example, a number of statistics can be separately
histogram, pie chart to represent. The purpose is to ensure the presence of C M and V sync, once changed M, V should be synchronized.

  Model - View - Controller (MVC) is Xerox PARC in the 1980s as a software design pattern programming language Smalltalk-80 invention, has been widely used. It came to be recommended as Oracle's Sun's Java EE platform design patterns, and welcomed by more and more use of ColdFusion and PHP developers. Model - View - Controller pattern is a useful toolkit, it has many advantages, but there are some drawbacks.
  : Create a Web application design patterns MVC is a (- - Model View Controller Model View Controller) using the MVC
    Model (model) represents the core of the application (such as a database record list) (data model).
    View (View) display data (database record).
    Controller (controller) for input and output (written to the database record).
    MVC model while providing full control over HTML, CSS and JavaScript.

The Model : for processing the application is part of the application data logic.

  Data logical parts: data validation, data persistence-related processing.

View (View) : is the application part of the processing data.

Data processing: the display data, the input data (the interface).

Controller (Controller) : the application is part of the user interaction processing.

Interaction: interaction input and output for receiving information sent by the client, the client responds to...

In JavaWeb development, advantages and disadvantages of using a variety of techniques generally used:

  Servlet acts as a control layer.

JSP layer acts as a view

  Model-related Java code.

MVC model three-relations

The advantages of MVC model

  1. Reducing the coupling procedure
  2. Improved reusability of code
  3. Improve the maintainability of the program
  4. Improve the readability of the program
  5. Improved scalability
  6. Improve development efficiency

However, increasing the complexity of the program structure.

With the development of the development, from the MVC model, the evolution:

  MVP: mobile terminal

  MVVM:vue.js

Servlet summary

concept:

  .. Server Applet running an applet in the applet on the server for the data receiving client and the client may respond to the .Servlet narrow and broad points:

 In a narrow sense: Servlet applet

 Broadly: in Java, implements the Servlet interface registration configuration.

Life cycle:

init initialization is executed once

  service provision of services performed N times

  destory destroy executed once

Servlet is a singleton, non-thread-safe, do not define member variables.

Guess you like

Origin www.cnblogs.com/lyang-a/p/12562788.html