MVC pattern
Before explaining Servlet, first introduce the MVC pattern.
- M: model model corresponds to the data layer for storing data, such as a Java bean class one
- V: view view, corresponding to the page level, for displaying data, such as a web page html, or jsp
- C: controller controller, corresponding to the business layer, for data processing
Before we use JSP, which can also be used java small script for data processing.
However, we want to display data, but also data processing, code under the JSP file, the code will cause pollution, inconvenient to read and write.
This time, there have been MVC architecture for data processing, data display, data storage are separated, they can be better managed.
In this way, we can put a JavaWeb project is divided into three levels, JSP will be used to display data, Servlet used to process data, bean class used to store data.
Servlet Introduction
Java Servlet is a program running on the 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.
Briefly, Servlet can intercept request is then processed, followed by return of data, or a page navigation (request forwarding or redirection)
effect:
- Processing user request data
- In response to a user request
- Website navigator
- Traffic control processing logic
Filter Filters Introduction
The filter may dynamically intercept request and response, or to transform the information contained in the request or response.
One or more filters can be attached to a group or a Servlet Servlet. Filters can also be attached to the JavaServer Pages (JSP) files and HTML pages.
Filters are available for Java Servlet programming classes, can achieve the following purposes:
Before accessing the back-end resources to the client's request, to intercept these requests. Before being sent back to the client in the server's response, process the response.
Filter means before when a client requests some web assembly (JSP / Servlet) to a request to do some preprocessing operations, for example, form submission contains Chinese, whether the user has been logged, etc., you can filter data request do Chinese transcoding; determining whether the user login and other applications
The official recommended the following cases using filters;
- Authentication filter (Authentication Filters).
- Data Compression Filter (Data compression Filters).
- Filter encryption (Encryption Filters).
- Resource Access trigger event filter.
- The image conversion filter (Image Conversion Filters).
- Logging and auditing filters (Logging and Auditing Filters).
- MIME-TYPE chain filter (MIME-TYPE Chain Filters).
- Labeled filters (Tokenizing Filters).
- XSL / T filter (XSL / T Filters), converting XML content.
Lisenter introduce listeners
Listeners also called Listener, a Servlet listener, it can monitor the operation request, the server of the client and so on. By listening, you can automatically inspire some operations, such as monitor the number of online users.
Because used much, here on the first outline the listener which can be used on what features
Two ways, notes @WebListener and web.xml configuration listener
Servlet filter process
Servlet implementation
1. Preparation of a Class, inherited HTTPServlet, rewrite doGet and doPost methods
- processing user requests get doGet
- doPost post process the user's request
PS: If you are prompted not aware of this HTTPServlet class, adding it relies
package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author StarsOne
* @date Create in 2019/9/14 0014 20:14
* @description
*/
public class FirstServlet extends HttpServlet {
/**
* @param req 相当于request内置对象
* @param resp 相当于response内置对象
* @throws ServletException
* @throws IOException
*/
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//调用doPost方法
doPost(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//重定向页面
resp.sendRedirect(req.getContextPath()+"/hello.jsp");
}
}
2. Open web.xml, arranged Servlet, intercepts the request
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>FirstServlet</servlet-name>
<!--这里要指定Servlet的类,也就是我们之前第一步编写的那个类-->
<servlet-class>controller.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<!--这里的FirstServlet是与上面的servlet-name属性对应,可以任意取名-->
<servlet-name>FirstServlet</servlet-name>
<!--拦截的请求,请求为hello时,就会跳转到Servlet去执行-->
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>
Supplementary url-pattern of: see below
3. Test Description
My project defines two jsp, one is index.jsp
, the other is hello.jsp
index.jsp
there is a link:
<a href="hello">点击跳转</a>
After clicking the link above, it will be intercepted Servlet, after processing. Our Servlet is actually realized the page redirection operation, so, and then will jump to hello.jsp
the page
PS: web.xml embodiment except that the configuration of the outside, may also be used to mark annotations
Servlet used on that class @WebServlet
notes can be, the following code is the same as before in the web.xml file defines the effect, then click will jump to hello.jsp
go
@WebServlet("/hello")
public class FirstServlet{
...
}
url-pattern supplement
1. exact match:
form | Match url |
---|---|
/hello | http://localhost:8080/servletdemo/hello |
/hello.html | http://localhost:8080/servletdemo/hello.html |
Before we write the href attribute of a link, just write hello, in fact, visited url address ishttp://localhost:8080/servletdemo/hello
2. Path match:
** with a "/" character, and "/ *" matches the end of the string to the path **
form | Match url |
---|---|
/user/* | http://localhost:8080/user/hello http://localhost:8080/user/he http://localhost:8080/user/hello/aa |
/hello.html | http://localhost:8080/servletdemo/hello.html |
3. The extension matches:
Simply put, what the end of the url
form | Match url |
---|---|
*.do | http://localhost:8080/servletdemo/hello.do |
*.hello | http://localhost:8080/servletdemo/aa.hello |
*.action | http://localhost:8080/servletdemo/aa.action |
*.jsp | http://localhost:8080/servletdemo/aa.jsp |
4. Default match:
Which is equivalent to not write, match all the url
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Reference url-pattern matching rule of servlet
Filter filter implementation
1. To achieve Filter interface, override method
Create a new class, make it happen Filter interface
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* @author StarsOne
* @date Create in 2019/9/14 0014 21:35
* @description
*/
public class FirstFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
System.out.println("过滤器1已过滤...");
//必须要有doFilter方法,之后过滤结束就会跳转到匹配的url的Servlet中进行业务逻辑处理
filterChain.doFilter(servletRequest,servletResponse);
}
@Override
public void destroy() {
}
}
Web.xml configuration file
Servlet configuration rules and almost not too much to explain here
<filter>
<filter-name>FirstFilter</filter-name>
<filter-class>FirstFilter</filter-class>
</filter>
<!--如果有多个,过滤器的顺序就是按照web.xml中的过滤器顺序进行过滤 -->
<filter-mapping>
<filter-name>FirstFilter</filter-name>
<!--指定过滤全部的url -->
<url-pattern>/*</url-pattern>
</filter-mapping>
test
Test, you will find after clicking the link, the console output twice, and this is the side that redirects the request, the client makes a request twice