Servlet & JSP & Filter

Servlet & JSP & Filter

graph TB B [Servlet] C [JSP] B -> D [Basic principle and implementation process <br> init / service / do.] B -> H [service & reflecting] B -> I [Singleton] C -> E [implicit object] C -> F [JSTL & EL] C -> G [session <br> JavaBean]

Servlet

Servlet is an object running on the server side, web servers (such as Tomcat) based on the user's access link route the request to the Servlet by a different process and their response is returned, the general routing configuration in web.xml, of course be used in the form of annotations.

Feature

  • Singleton
  • Servlet examples of the initialization request

Fundamental

The following is an example of HTML & servlet & web.xml

HTML (note action and method values):

...
<form action="login" method="post">
账号: <input type="text" name="name"> <br>
密码: <input type="password" name="password"> <br>
<input type="submit" value="登录">
</form>
...

web.xml (Note Servlet mapping between the path and url):

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>LoginServlet</servlet-class>
        <load-on-startup>10</load-on-startup> 
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>  
</web-app>

Servlet:

public class LoginServlet extends HttpServlet{
    // @Override // 当前函数的作用见下
    // public void service(HttpServletRequest request, HttpServletResponse response){...}
    // public void init(ServletConfig config) {...} // 继承于父类,Servlet 的构造函数执行后会自动执行此函数,只会执行一次
 	// 处理 GET 请求
    public void doGet(HttpServletRequest request, HttpServletResponse response){
        try {
            response.getWriter().println("<h1>Hello Servlet!</h1>");
            response.getWriter().println(new Date().toLocaleString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    // 处理 POST 请求
    public void doPost(HttpServletRequest request, HttpServletResponse response){
        try{
            String name = request.getParameter("name");
        	String password = request.getParameter("password");
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Each Servlet needs to inherit HttpServlet . HttpServlet has a service member function, the method determines the default service request and to invoke doGet or doPost method according to the current function method (GET or POST). Filter & rewritable binding service & reflections may implement a different servlet processing request, as follows:

Filter resolved using the user's request, the following code section Filter object taken from:

// 假设请求的方法是 ***/admin_category_list
if(uri.startsWith("/admin_")){		
	String servletPath = StringUtils.substringBetween(uri,"_", "_") + "Servlet"; // 确定 Servlet
	String method = StringUtils.substringAfterLast(uri,"_" );
	request.setAttribute("method", method); // 确定方法
	req.getRequestDispatcher("/" + servletPath).forward(request, response); // 执行 Servlet
	return;
}

Override function and service selection and execution Servlet using a reflection method (at this time and does not require doGet doPost):

@Override
public void service(HttpServletRequest request, HttpServletResponse response) {
    ...
    try {
        /*借助反射,调用对应的方法*/
        String method = (String) request.getAttribute("method");
        Method m = this.getClass().getMethod(method, javax.servlet.http.HttpServletRequest.class,
                                             javax.servlet.http.HttpServletResponse.class,Page.class);
        String redirect = m.invoke(this,request, response,page).toString();
    }
    ...
}

A common method

  • Jump
    • Server Jump (Jump response returns content but do not change the browser's address):request.getRequestDispatcher("success.html").forward(request, response);
    • Jump client (the server sends a redirect address to the client):response.sendRedirect("fail.html");
  • Servlet from the start
    • In web.xml configuration <load-on-startup>10</load-on-startup>can be achieved since the launch of the Servlet

JSP

JSP, a Java technology can write code directly in the HTML class, JSP will eventually be translated into Servlet. JSP inherited from HttpJspBase, while the latter inherited from HttpServlet.

JSP examples

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
<%
    List<String> words = new ArrayList<String>();
    words.add("today");
    words.add("is");
    words.add("great");
%>
<table width="200px" align="center" border="1" cellspacing="0">
<%for (String word : words) {%>
<tr>
    <td><%=word%></td>
</tr>
<%}%>
</table>

Page output:

today
is
great

JSP composition

JSP pages these elements:

  1. Static content, html, css, javascript etc.
  2. Instructions to <%@开始 %>end, such as<%@page import="java.util.*"%>
  3. Expressions <%=%>for the output section of html, <%="hello jsp"%>similar to<%out.println("hello jsp");%>
  4. Scriptlet, in <%%>between, you can write any java code
  5. Statement in <%!%>between can declare a field or method. But not recommended.
  6. Action <jsp:include page="Filename" >in jspcontaining another page page.
  7. Note <%-- -- %>, unlike html comment <!-- -->through jspthe comment, the browser can not see the corresponding code corresponds commented out in the servlet

Implicit Objects

No explicit definition objects can be used. A total of nine JSP implicit objects, namely:

  • request, response, out, out of the output
  • pageContext, session, application, representing the current page, session, global scope objects
  • JSP is compiled into a Servlet class, when running a Servlet instance. page that is representative of this
  • config, config can get some initialization parameters in web.xml
  • exception, the exception object, the specified page in order to use exception handling

JSTL

JSTL JSP Standard Tag Library, JSTL allows the development of Java as open can function in a JSP as using HTML tags.

Common functions Tags: fmt, fn

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%-- 指明后续的标签使用都会以<c: 开头 --%>

<c:set var="name" value="${'gareen'}" scope="request" />
通过标签获取name: <c:out value="${name}" /> <br> <%-- 类似<%=request.getAttribute("name")%> --%>

<c:remove var="name" scope="request" /> <br>
通过标签获取name: <c:out value="${name}" /> <br>

<c:set var="hp" value="${3}" scope="request" /> <%-- 循环示例 --%>
<c:choose>
    <c:when test="${hp<5}">
        <p>这个英雄要挂了</p>
    </c:when>
    <c:otherwise>
        <p>这个英雄觉得自己还可以再抢救抢救</p>
    </c:otherwise>
</c:choose>

EL expression

EL expression from pageContext, request, session, application scope taken to a value four, if four scopes have the same attributes, obtains EL descending order of priority:pageContext > request > session > application

JSP common usage

  • include
    • Command the include: <%@include file="footer.jsp" %>, the current JSP inserted into the command line position
    • Action the include: <jsp:include page="footer.jsp" />, the footer.jsp footer_jsp.java not be converted in the form of Servlet execution result footer_jsp.java the inserted position command
  • Jump
    • Client Jump:<%response.sendRedirect("hello.jsp");%>
    • Jump server:<jsp:forward page = "hello.jsp"/>

JavaBean

The standard JavaBean

  1. Providing public constructor with no arguments (provided by default)
  2. Each attribute has a public getter and setter
  3. If the property is boolean, then the correspondence is and setter methods

Session

Session is a session. Session refers to a user opening a browser to access a website from the beginning, regardless visit this site how many pages, how many clicked on the link, all belong to the same session, until the user closes the browser so far.

Servlet + JSP \(\approx\) MVC

Servlet easy to write Java code, JSP pages easy to write the code, combining the characteristics of both, business-related use of Servlet write code using JSP on display.

Servlet, save data to implicit object in

public class HeroEditServlet extends HttpServlet {
 
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        Hero hero = new HeroDAO().get(id);
        request.setAttribute("hero", hero); // 设置属性后 JSP 使用 EL 语言 ${hero.id},获得数据
        request.getRequestDispatcher("editHero.jsp").forward(request, response);
    }
}

JSP, the implicit objects obtained data

<form action='updateHero' method='post'>
    名字 : <input type='text' name='name' value='${hero.name}'> <br>
    血量 :<input type='text' name='hp' value='${hero.hp}'> <br>
    伤害: <input type='text' name='damage' value='${hero.damage}'> <br>
    <input type='hidden' name='id' value='${hero.id}'>
    <input type='submit' value='更新'>
</form>

Application examples

  • Using the display data paging
    • Return data back within the specified range, the front end of the display

Filter

Filter a checkpoint as a user's request needs to Filter, you may be provided a plurality Filter

graph LR A [User Access] A -> B ((Filter 1)) B -> C ((Filter 2)) C -> D ((Filter ..)) D -> E [Servlet]

Guess you like

Origin www.cnblogs.com/jiahu-Blog/p/11596259.html