当前位置:网站首页>JSP and filter
JSP and filter
2022-07-03 13:13:00 【Tolerance speech】
1.JSP
1.1 summary
Java Server Pages:java Server page , And also Servlet equally , For dynamic Web technology .
The biggest feature :
- Write jsp It's like writing html equally
- difference :
- html Only static data is provided to users .html Comments of can be displayed on the client
- jsp Pages can be embedded java Code , Provide users with dynamic data .jsp The comment of cannot be seen on the client , But you can grab the bag .
1.2 principle
Work inside the server
- tomcat There is one of them. work Catalog
- idea Use in tomcat Will be in idea Of tomcat Produce one in work Catalog
Found that the page was converted into a java Program ,JSP It will eventually be transformed into a Java class . Browser sends request to server , No matter what resources are accessed , In fact, they are all visiting Servlet.
JSP In essence Servlet:
Some internal source code :
// initialization
public void _jspInit() {
}
// The destruction
public void _jspDestroy() {
}
//JSPService
public void _jspService(HttpServletRequest request, HttpServletResponse response)
public void _jspService(HttpServletRequest request, HttpServletResponse response)
Judge the request
Built in some objects
final jakarta.servlet.jsp.PageContext pageContext;// Page context final jakarta.servlet.ServletContext application; //application final jakarta.servlet.ServletConfig config; //config jakarta.servlet.jsp.JspWriter out = null; //out final java.lang.Object page = this; //page The current page HttpServletRequest request; // request HttpServletResponse response; // Respond to
Code added before the output page
response.setContentType("text/html; charset=UTF-8");// Set the page type of the response pageContext = _jspxFactory.getPageContext(this, request, response, null, false, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); out = pageContext.getOut(); _jspx_out = out;
These objects can be found in JSP Use directly on the page
stay jsp On the page :
As long as it is java The code will be output intact
html Code , Will be converted to the following format , Output to the front end
out.write("<html lang=\"en\">\r\n");
1.3 grammar
Every language has its own grammar ,JSP As java An application of Technology , It has some of its own extended syntax , It supports java All the grammar of .
1.3.1jsp expression
<%--
Used to convert the output of the program , Output to client
<%= Variables or expressions %>
--%>
<%= new java.util.Date()%>
1.3.2jsp Script snippets
<%
int sum=0;
for (int i = 1; i < 100; i++) {
sum+=i;
}
out.println("<h1>sum="+sum+"</h1>");
%>
1.3.3jsp Script fragment reproduction
<%
int x=1;
out.println(x);
%>
<p> This is a jsp file </p>
<%
int y=2;
out.println(y);
%>
<hr>
<%-- Embed... In the code html Elements --%>
<%
for (int i = 1; i <=3; i++) {
%>
<h1>hello world!<%= i%></h1>
<%
}
%>
1.3.4jsp Statement
Global variables :
<%!
static{
System.out.println("loading Servlet");
}
private int globalvar = 0;
public void m(){
System.out.println(" Into the method m");
}
%>
jsp The declaration will be compiled into jsp Generated java Class , Those above will be generated to _jspService In the method .
1.4 Instructions
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> Solve the Chinese garbled code
<%@ page errorPage="error/500.jsp" %> Custom error page
<%@page isErrorPage="true" %>
Extract public pages :
<%-- Three pages will be combined into one page --%>
<%@include file="common/header.jsp"%>
<h1> The main body of the page </h1>
<%@include file="common/footer.jsp"%>
<%--jsp label : Splicing pages , In essence, there are three pages --%>
<jsp:include page="/common/header.jsp"/>
<h1>1111111</h1>
<jsp:include page="/common/footer.jsp"/>
<error-page>
<error-code>500</error-code>
<location>/error/500.jsp</location>
</error-page>
<error-page>
<error-code>404</error-code>
<location>/error/404.jsp</location>
</error-page>
1.5 Nine built-in objects
1.5.1 summary
- PageContext To save things
- Request To save things
- Response
- Session To save things
- Application 【ServletContext】 To save things
- Config 【ServletConfig】
- Out
- Page 【 no need 】
- Exception
Schematic diagram :
request: Client sends request to server , Generate data , It's useless for users to read it , such as : Journalism
session: Client sends request to server , Generate data , The user will be useful after a while , such as : The shopping cart
application: Client sends request to server , Generate data , One user runs out , Another user can also use , such as : Chat data
<body>
<%-- Built-in objects --%>
<%
pageContext.setAttribute("name1","x1");// The saved data is only valid in one page
request.setAttribute("name2","x2");// The saved data is only valid in one request , Please forward this data
session.setAttribute("name3","x3");// The saved data is valid only in one session , From open browser to close browser
application.setAttribute("name4","x4");// The saved data is only valid in the server , From turning on the server to turning off the server
%>
<%-- The code in the script fragment , Will be generated intact to .jsp.java
requirement : The code here must guarantee java The correctness of grammar , Notes are also used java Notes // --%>
<%
// from pageContext Remove from , We look for ways to
// From the lower level to the higher level page-->request-->session-->application
String name1 = (String) pageContext.findAttribute("name1");
String name2 = (String) pageContext.findAttribute("name2");
String name3 = (String) pageContext.findAttribute("name3");
String name4 = (String) pageContext.findAttribute("name4");
String name5 = (String) pageContext.findAttribute("name5");// non-existent
%>
<%-- Use EL Expression output result ${} --%>
<h1> The value taken out is :</h1>
<h2>${name1}</h2>
<h3>${name2}</h3>
<h4>${name3}</h4>
<h5>${name4}</h5>
<h6>${name5}</h6>
<h6><%= name5%></h6>
</body>
Output results :
1.5.2 Scope
<%-- Scope (scope) Changes :--%>
<%pageContext.setAttribute("a","b",pageContext.SESSION_SCOPE);%>
Source code :
public void setAttribute(String name, Object attribute, int scope) {
switch(scope) {
case 1:
this.mPage.put(name, attribute);
break;
case 2:
this.mRequest.put(name, attribute);
break;
case 3:
this.mSession.put(name, attribute);
break;
case 4:
this.mApp.put(name, attribute);
break;
default:
throw new IllegalArgumentException("Bad scope " + scope);
}
}
<%-- Request forwarding --%>
<%
pageContext.forward("/index.jsp");
request.getRequestDispatcher("/index.jsp").forward(request,response);
%>
1.6 label
1.6.1JSP label
- jsp:include
- jsp:forward
- jsp:param
<%--http://localhost:8080/jsp/jsptag1.jsp?name= Xiao Ming &age=18--%>
<jsp:forward page="/jsptag2.jsp">
<jsp:param name="name" value=" Xiao Ming "/>
<jsp:param name="age" value="18"/>
</jsp:forward>
<%-- Take out the parameters --%>
name :<%= request.getParameter("name")%>
Age :<%= request.getParameter("age")%>
1.6.2JSTL label
1.6.2.1 summary
JSTL Tag library is used to make up for HTML The lack of labels ; It customizes many labels , It can be used by us , The function of tags and java code !
Use jstl Steps of label Library :
- Import corresponding jstl Tag library
- Use the method
- stay tomcat We also need to introduce our jstl Package, otherwise it will report an error !
pom.xml Packages that need to be imported in :
<!--jstl The dependency of expressions -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!--standard Tag library -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
1.6.2.2 Core tags
c:if
<%-- introduce jstl Core tag library , We can use jstl label --%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<h4>if test </h4>
<hr>
<form action="coretag.jsp" method="post">
<%--EL Expression to get the data in the form ${param. Parameter name } --%>
<input type="text" name="username" value="${param.username}">
<input type="submit" value=" Sign in ">
</form>
<%-- Judge if the submitted user name is administrator , Then login successfully --%>
<c:if test="${param.username == 'Admin'}" var="isAdmin">
<c:out value=" The administrator welcomes you "></c:out>
</c:if>
<c:out value="${isAdmin}"></c:out>
Output results :
c:choose
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%-- Define a variable score, The value is 85--%>
<c:set var="score" value="85"></c:set>
<c:choose>
<c:when test="${score>=90}">
<c:out value=" good "/>
</c:when>
<c:when test="${score>=80}">
commonly
</c:when>
<c:when test="${score>=70}">
<c:out value=" good "/>
</c:when>
<c:when test="${score>=60}">
<c:out value=" pass "/>
</c:when>
</c:choose>
c:foreach
<%
ArrayList<String> people = new ArrayList<>();
people.add(0," Zhao Yi ");
people.add(1," Li Er ");
people.add(2," That three ");
people.add(3," The king of the four ");
request.setAttribute("list",people);
%>
<%--
var: Variables obtained from each iteration
items: Object to traverse
--%>
<c:forEach var="people" items="${list}">
<c:out value="${people}"/><br>
</c:forEach>
<hr>
<c:forEach var="people" items="${list}" begin="1" end="3" step="2">
<c:out value="${people}"></c:out>
</c:forEach>
Output results :
1.6.3EL expression
${ }
- get data
- Perform an operation
- obtain web Develop common objects
1.7JavaBean
Entity class JavaBean There is a specific way of writing :
- There has to be a parameterless construct
- Property must be privatized
- There must be a corresponding get、set Method
- It is usually used to map the fields in the database ,ORM
ORM: Object mapping
- surface —> class
- Field —> attribute
- rows —> object
<%@ page import="moli.jsp.pojo.People" %>
<%
People people = new People();
people.setAddress(" heilongjiang ");
people.setAge(18);
people.setId(1);
people.setName(" Xiao Ming ");
String name = people.getName();
out.println(name);
%>
<hr/>
<jsp:useBean id="peole" class="moli.jsp.pojo.People" scope="page"/>
<jsp:setProperty name="peole" property="address" value=" heilongjiang "/>
<jsp:setProperty name="peole" property="name" value=" Xiao Ming "/>
<jsp:setProperty name="peole" property="age" value="18"/>
<jsp:setProperty name="peole" property="id" value="1"/>
<jsp:getProperty name="peole" property="name"/>
Output results :
2.MVC Three layer architecture
MVC:model view controller Model view controller
2.1 Earlier years
User direct access control layer , The control layer can directly operate the database
servlet-->CRUD--> database
disadvantages : The program is very bloated , Not conducive to maintenance
servlet In the code of : Processing requests , Respond to , View jump , Handle JDBC, Deal with business code , Processing logic code
framework : Nothing can't be solved by adding a layer
The programmer calls --JDBC--MySQL,Oracle,sqlServlet...
2.2 Now?
View
- Display data
- Provide connection , launch Servlet request (a,form,img……)
Controller(Servlet)
- Accept user requests (req Request parameters ,session Information ……)
- Give it to the business layer to process the corresponding code
- Control view jump
Model
- Business processing : Business logic (Service)
- Data persistence layer :CRUD(Dao)
Sign in --- Receive user login request --- Handle user requests ( Get user login parameters ,username,password)--- Give it to the business layer to handle the login business ( Determine whether the user name and password are correct ; Business )---Dao The layer queries whether the user name and password are correct --- database
3.Filter And the monitor
3.1Filter
filter : It's used to filter the data of the website
- Solve the Chinese garbled code
- validate logon ……
filter Development steps :
Guide pack ( It must be javax.servlet Under the Filter Interface )
Write filters
chain chain , Let our request go on , So that the program can be handed over to the next part ; If you don't write , Our program will be blocked and stopped here .
package filter; import javax.servlet.*; import java.io.IOException; public class characterEncodingFilter implements Filter { // Initialization and web Start the server together , Wait for the filter object to appear at any time @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("characterEncodingFilter Already initialized "); } // All code in the filter will be executed when filtering specific requests // The filter must be allowed to move forward chain.doFilter(request,response); @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=UTF-8"); System.out.println("characterEncodingFilter Before execution "); chain.doFilter(request,response); System.out.println("characterEncodingFilter After execution "); } // The destruction ,web When the server is down , The filter will be destroyed @Override public void destroy() { System.out.println("characterEncodingFilter It has been destroyed "); } }
public class showServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.getWriter().write(" Hello "); } }
Configure filter web.xml
<servlet> <servlet-name>showServlet</servlet-name> <servlet-class>moli.showServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>showServlet</servlet-name> <url-pattern>/show</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>showServlet</servlet-name> <url-pattern>/moli/show</url-pattern> </servlet-mapping> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>filter.characterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <!-- As long as it is /moli All requests are filtered --> <url-pattern>/moli/*</url-pattern> </filter-mapping>
At this time, enter the address in the browser :http://localhost:8080/f/show It's still garbled , But input http://localhost:8080/f/moli/show There will be no more random code .
3.2 Monitor
Implement a listener interface (N Kind of ):
// Count the number of people online : Statistics session
public class OlinerCountListener implements HttpSessionListener {
// establish session monitor : Watch every move of the client
// Once created session This event will be triggered once
@Override
public void sessionCreated(HttpSessionEvent se) {
ServletContext sc = se.getSession().getServletContext();
System.out.println(se.getSession().getId());
Integer onlineCount = (Integer) sc.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = new Integer(1);
}else {
onlineCount = new Integer(onlineCount+1);
}
sc.setAttribute("OnlineCount",onlineCount);
}
// The destruction session monitor
// Once destroyed session This event will be triggered once
@Override
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext sc = se.getSession().getServletContext();
Integer onlineCount = (Integer) sc.getAttribute("OnlineCount");
if (onlineCount==null){
onlineCount = new Integer(0);
}else {
onlineCount = new Integer(onlineCount-1);
}
sc.setAttribute("OnlineCount",onlineCount);
}
}
<h1>
The current is <span style="color: bisque">
<%= this.getServletConfig().getServletContext().getAttribute("OnlineCount")%>
</span> People online
</h1>
<!-- Register listener -->
<listener>
<listener-class>listener.OlinerCountListener</listener-class>
</listener>
Output results :
Application of monitoring :
public class TestPanel {
public static void main(String[] args) {
Frame frame = new Frame(" Primordial winter ");// Create a new form
Panel panel = new Panel(null);// panel
frame.setLayout(null);
frame.setBounds(300,300,500,500);
frame.setBackground(new Color(0,99,23));
panel.setBounds(50,50,300,300);
panel.setBackground(new Color(100,0,0));
frame.add(panel);
frame.setVisible(true);
// Listen for off events
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
3.3 application
Users can enter the home page only after logging in , After the user logs off, he can't enter the home page .
The login page :
<form action="/moli/login" method="post">
<input type="text" name="username">
<input type="submit">
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// Get the parameters of the front-end request
String username = req.getParameter("username");
if (username.equals("admin")){
req.getSession().setAttribute("USER_SESSION",req.getSession().getId());
resp.sendRedirect("/sys/success.jsp");
}else {
resp.sendRedirect("/error.jsp");
}
}
}
Login success page
<h1> Home page </h1>
<p><a href="/moli/logout"> Cancellation </a></p>
logout
public class logoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object user_session = req.getSession().getAttribute("USER_SESSION");
if (user_session!=null){
req.getSession().removeAttribute("user_session");
resp.sendRedirect("/login.jsp");
}
}
}
Login failure page
<h1> error </h1>
<h2> No permission or wrong user name </h2>
<a href="/login.jsp"> Return to landing page </a>
filter
public class SysFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
if (request.getSession().getAttribute("user_session") == null) {
response.sendRedirect("/error.jsp");
}
chain.doFilter(req,resp);
}
@Override
public void destroy() {
}
}
边栏推荐
- Leetcode234 palindrome linked list
- Sword finger offer 15 Number of 1 in binary
- SSH login server sends a reminder
- Logback 日志框架
- 【数据库原理及应用教程(第4版|微课版)陈志泊】【第七章习题】
- [exercise 5] [Database Principle]
- 35道MySQL面试必问题图解,这样也太好理解了吧
- Quickly learn member inner classes and local inner classes
- 【数据挖掘复习题】
- The 35 required questions in MySQL interview are illustrated, which is too easy to understand
猜你喜欢
35道MySQL面试必问题图解,这样也太好理解了吧
Dojo tutorials:getting started with deferrals source code and example execution summary
我的创作纪念日:五周年
February 14, 2022, incluxdb survey - mind map
【数据库原理及应用教程(第4版|微课版)陈志泊】【SQLServer2012综合练习】
2022-02-11 heap sorting and recursion
【数据库原理及应用教程(第4版|微课版)陈志泊】【第六章习题】
Flink SQL knows why (XIV): the way to optimize the performance of dimension table join (Part 1) with source code
(first) the most complete way to become God of Flink SQL in history (full text 180000 words, 138 cases, 42 pictures)
Image component in ETS development mode of openharmony application development
随机推荐
Flink SQL knows why (XIV): the way to optimize the performance of dimension table join (Part 1) with source code
The 35 required questions in MySQL interview are illustrated, which is too easy to understand
Cadre de logback
35道MySQL面试必问题图解,这样也太好理解了吧
My creation anniversary: the fifth anniversary
18W word Flink SQL God Road manual, born in the sky
【数据库原理复习题】
Differences and connections between final and static
Fabric. JS three methods of changing pictures (including changing pictures in the group and caching)
The upward and downward transformation of polymorphism
Mysqlbetween implementation selects the data range between two values
mysqlbetween实现选取介于两个值之间的数据范围
Simple use and precautions of kotlin's array array and set list
【数据库原理及应用教程(第4版|微课版)陈志泊】【第四章习题】
【判断题】【简答题】【数据库原理】
php:&nbsp; The document cannot be displayed in Chinese
Slf4j log facade
Create a dojo progress bar programmatically: Dojo ProgressBar
2022-01-27 redis cluster technology research
剑指 Offer 15. 二进制中1的个数