JSP
-
jsp file unified character encoding
Set the encoding of jsp file (pageEncoding attribute in jsp file): jsp -- java
Set the encoding for browsing and reading jsp files (content attribute in jsp files)
Generally, the above codes are set to be consistent. It is recommended to use: utf-8
-
Deploy tomcat
- On the Servers panel, first create a new tomcat instance, and then deploy the project in the instance (right click - add - add the project to run). Then you can run
It is recommended to keep the configuration information of tomcat in eclipse consistent with that of local tomcat: set tomcat in eclipse to managed mode:
[first time] after creating a tomcat instance, double-click the tomcat instance in the Server, and then select the second item of Server Location
-
JSP page elements: HTML, java code (Scriptlet), instructions, comments.
Script Scriptlet
-
<% Define local variables and write java sentence %>
-
<%! Define global variables and methods %>
-
<%= Output expression %>
-
In general, modify the web XML, configuration file and java code. You need to restart tomcat service, but if you modify Jsp\html\css\js, you don't need to restart.
-
Note: out Println() cannot wrap output, want to wrap:
<br/>
out. HTML code can be directly parsed in print (), <% =% >. For example, if < BR is added to it, there will be line feed
instructions
-
page instruction
Properties specified by page
language: JSP The script language used on the page is generally the default java No need to change import: Use when importing classes pageEncoding: JSP File code contentType: Browser parsing JSP Code of: its value is determined JSP Page response MIME Type and JSP Encoding of page characters contentType of charset Refers to the content encoding when the server sends it to the client <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.Date" %> JSP After two "coding", the first stage will use pageEncoding,The second stage will use utf-8 to utf-8,The third stage is by Tomcat Out of the web page, using contentType. The first stage is jsp Compile into java It will be based on pageEncoding Setting reading of jsp,The result is translated by the specified coding scheme into a unified one UTF-8 JAVA Source code (i.e.java),If pageEncoding If the setting is wrong or not set, what comes out is Chinese garbled code. The second stage is by JAVAC of JAVA Source code to java byteCode Compilation of Regardless JSP What coding scheme is used when writing, and the results of this stage are all UTF-8 of encoding of java Source code. JAVAC use UTF-8 of encoding read java Source code, compiled into UTF-8 encoding Binary code of (i.e.class),This is JVM Constant digit string in binary code( java encoding)Specification of internal expression. The third stage is Tomcat(Or its application container)From load and run phase II JAVA Binary code The output result, which is seen on the client, is hidden in the parameters of phase I and phase II contentType It worked
-
notes
html notes:<!-- --> ,Right click the browser to view the source code. The client is invisible in the following two ways: java notes:// , /* */ jsp notes:<%-- --%>
-
Chapter 1: JSP Foundation
-
JSP comments
-
Syntax:
<%--jsp Page usage notes--%>
-
When viewing the source code in the client browser, HTML comments can be viewed. JSP comments cannot be viewed on the client
<!-- HTML Note: will be JSP Translation engine translate to Servlet of out.write()in --> <%--JSP Note: will be JSP Translation engine ignored, in Servlet You can't see it in --%>
-
-
What is JSP?
JSP technology is a kind of file formed after inserting "java code fragment" and "JSP tag" into the traditional static web page HTML file.
-
java code block in JSP (in <%% >
-
Code blocks in JSP, also known as "JSP scripts", are enclosed by <%% >, in which java code blocks can be written.
-
The code written in the java code block will be put into the Servlet by the JSP translation engine_ Appears as a java statement in the jspService() method
-
java statements in <%% > must begin with ";" ending
-
<%% > can be defined anywhere in the JSP file
-
The java statement in <%% > will be put into the method, so the following contents cannot appear in it
- Declared variables cannot be added with access control characters.
- Method cannot be defined
- Static code blocks cannot be defined
<% double price = 2.5; //Access control characters cannot be added to java code blocks, and methods cannot be defined. /* private int dd ; public void print(){ System.out.println("Printing method "); } */ %>
-
-
Declaration statement block in JSP (put in <%!% >
-
In the JSP interface, use <%!% > Enclosed is called: declaration statement block. The content in the life statement block will be translated into the class body of the Servlet by the JSP engine and will not be included in the method
-
The declaration statement block of JSP can declare instance variables, instance methods, static methods, static code blocks, etc. Everything declared in the "declaration statement block" can be accessed in the java statement block because they are in the same class body.
<%! //You can add access control characters when declaring variables private int dd ; //Methods can be defined public void print(){ System.out.println("Printing method"); } //Static code blocks can be defined static{ System.out.println("Static code block executed"); } %> <% //It can be accessed here print(); %>
-
However, it is not recommended to declare instance variables in the declaration statement block. Because JSP runs in the environment of "single instance multithreading", instance variables will cause thread safety problems.
-
In the declaration statement block, ordinary java statements cannot be written. Otherwise: these statements will appear directly in the Servlet class body.
-
The declaration statement block can also be defined anywhere in the JSP page, and multiple statements can be defined.
-
-
Expression block in JSP (<% =% >
- The part enclosed by <% =% > in JSP interface is called expression block.
- You can output variables and constants in JSP pages. And the values of various expressions
- Notice the expression! Not a statement, no semicolon.
- The expression will be translated into by the JSP engine_ Out. In jspService() method Output in the write () method.
-
<% int amount = 3; %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <%! //You can add access control characters when declaring variables private int dd ; //Methods can be defined public void print(){ System.out.println("Printing method"); } //Static code blocks can be defined static{ System.out.println("Static code block executed"); } %> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <% double price = 2.5; //Access control characters cannot be added to java code blocks, and methods cannot be defined. /* private int dd ; public void print(){ System.out.println("Printing method "); } */ %> </head> <% double count = 0; %> <body> Hello JSP World! <!-- HTML Note: will be JSP Translation engine translate to Servlet of out.write()in --> <%--JSP Note: will be JSP Translation engine ignored, in Servlet You can't see it in --%> <% System.out.println("java code snippet"); System.out.println("java code snippet"); %> <% count = amount * price; %> <%=count %> </body> </html> <% System.out.println("count:"+count); print(); %>
JSP 9 built-in objects (self-contained objects that can be used without new)
out: Output object, output content to client request: Request object; Store "request information sent by client to server" response Response object pageContext JSP Page container session Session object qpplicaton Global object config Configuration object (server configuration information) page current JSP Page object (equivalent to java Medium this) exception Exception object.
-
requset: request object, which stores the "request information sent by the client to the server"
-
Common methods of request object
String getParameter(String name): According to the requested field key(input Tagged name Property), return the field value value String[] getParameterValues(String name):According to the requested field key,Return multiple field values value(value Attribute value) (For example: check box checkbox (return of value) void setCharacterEncoding("utf-8"): set up post Request code of mode (tomcat7 Previously default: iso-8859-1,tomcat8 Later changed to utf-8) getRequestDispatcher().forward(request,response); : Jump to the page by requesting forwarding For example: A ——-> B,stay A On the page, getRequestDispatcher("b.jsp").forward(request,response) ServlectContext getServerContext(): Get the of the project ServletContext object
-
Registration cases
http://localhost:8080/01-jsp-primary/show.jsp?uname=ls&upwd=123&uage=18 connect/File? Ref. 1=Parameter 1&Ref. 2=Parameter 2&Ref. 3=Parameter 3 get Submission method: method="get",Address bar, hyperlink(<a href="xx")Request method method By default, all belong to get Submission method get And post Differences in request methods: get In this way, the request information is displayed in the address bar (but the information that the address bar can hold is limited, 4-5KB;If there are large files, pictures, videos, etc. in the requested data, there will be an error that the address bar cannot hold all the data post Not displayed, and the request method for uploading files must be: post,and post More secure. Therefore, it is generally recommended post Request mode.
-
Unified request encoding request
get Method request. If there is garbled code, solve it: - Unify the coding of each variable, as long as there is one variable value For Chinese, operations are required, such as: String name = request.getParameter("uname"); new String(name.getBytes("iso-8859-1"),"utf-8"); - modify server.xml One time change tomcat default get Code of submission method( utf-8) Recommended use tomcat Time, now server.xml Chinese unification get Coding method: Add the following at the end of the line where the port number is set: URIEncoding="utf-8". post Method request, garbled code,Set encoding type: request.setCharacterEncoding("utf-8");
-
register.jsp
<form action="show.jsp" method="post"> user name:<input type="text" name ="uname"/><br> password:<input type="password" name ="upwd"/><br> Age:<input type="text" name ="uage"/><br> Hobbies: <input type="checkbox" name="uhobbies" value="sing"/> sing <input type="checkbox" name="uhobbies" value="dance"/> jump <input type="checkbox" name="uhobbies" value="rap"/> rap <input type="checkbox" name="uhobbies" value="blueball"/> Basketball<br> <input type="submit" value="register"> </form>
-
show.jsp
<% //Set code request.setCharacterEncoding("utf-8"); String name = request.getParameter("uname"); //request.getParater("uage") actually returns a string. The number type is required to be stored in the background database //Use the static int parseInt(Strings s) static method and pass the parameter String to return int int age = Integer.parseInt(request.getParameter("uage")); String pwd = request.getParameter("upwd"); String[] hobbies = request.getParameterValues("uhobbies"); %> The registration is successful. The information is as follows:<br> full name:<%=name %><br> Age:<%=age %><br> password:<%=pwd %><br> Hobbies:<br> <% //When traversing, the array cannot be empty. If it is empty, an error will be reported, so a judgment is added here if(hobbies != null){ for(String hobby:hobbies){ out.print(hobby+" "); } } %>
-
-
Response: response object
-
Methods provided
void addCookie(Cookie cookie); The server adds to the client cookie object void sendRedirect(String location) throws IOException; A way of page Jump (redirection) void setConterType(String type); Set the response code of the server (set the response code of the server) contentType (type)
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-eb4gcmpa-1622360006642) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 1. Request: the data is valid for the same request. PNG)]
-
Example: Login
login. jsp---->check. JSP - if successful, jump to: success jsp
login.jsp
<form action="check.jsp" method="post"> user name:<input type="text" name="uname"><br> password:<input type="password" name="upwd"><br> <input type="submit" value="Sign in"> </form>
check.jsp
<% request.setCharacterEncoding("utf-8"); String name = request.getParameter("uname"); String pwd = request.getParameter("upwd"); if(name.equals("zs") && pwd.equals("abc")){//Suppose the user name is zs and the password is abc //redirect //response.sendRedirect("success.jsp"); Page Jump: redirect. Resulting in data loss //Request forwarding: data can be obtained without changing the address bar. (still keep the page check. JSP when forwarding) request.getRequestDispatcher("success.jsp").forward(request,response); }else{ //Login failed out.println("Wrong user name or password!"); } %>
success.jsp
Login succeeded!<br> Welcome: <% String name=request.getParameter("uname"); out.print(name); %>
-
Jump page
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-nx29r2u5-1622360006645) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 2. Request forwarding. PNG)]
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (IMG fgyeknif-1622360006647) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 3. Redirection. PNG)]
Request forwarding redirect Is the address bar changed unchanged(check.jsp) change(success.jsp) Do you want to keep the data from the first request retain Not reserved Number of requests 1 2 Where the jump occurs The server jumps internally The second request from the client to jump
-
Forwarding and redirection
Forwarding: one request and one server response Zhang San (client) -> [Service window A(Server) -> Service window B ] Redirection: two requests and two server responses Zhang San (client) -> Service window A(Server) -> It can't be solved. Let's find it B Zhang San (client) -> Service window B(Server)
-
-
session (server), Cookie (client, not built-in object): cookies are generated by the server and sent to the client for saving.
-
Cookie is equivalent to the function of local cache: after the server sends a file to the client, the file will be cached locally, and the file may be accessed directly from the local machine (client) for the second time
Advantages and disadvantages: improve the efficiency of accessing the server, but the security is poor.
Cookie: name=value cookie adopt javax.servlet.http.Cookie Class to create an object public Cookie(String name,String value) String getName():obtain name String getValue():obtain value void setMaxAge(int expiry); Maximum validity period (seconds) 1,Server preparation Cookie: response.addCookie(Cookie cookie) 2,Page Jump (forwarding, redirection) 3,Client acquisition Cookie: request.getCookies(); be careful: a,Server side increase Cookie: use response Object, client get object: Using request object b,You can't get a single object directly. You can only get all the objects at one time Coolie Object get
-
Through f12, you can find that in addition to the cookie object you set yourself, there is also a cookie with the name JSESSIONID
response_addCookie.jsp
<% //Server Cookie cookie1 = new Cookie("name","zs"); Cookie cookie2 = new Cookie("pwd","abc"); response.addCookie(cookie1); response.addCookie(cookie2); //Page Jump to the client (forwarding and redirection are OK) response.sendRedirect("result.jsp"); %>
result.jsp
<% //client Cookie[] cookies = request.getCookies(); for(Cookie cookie :cookies){ out.print(cookie.getName()+"---"+cookie.getValue()+"<br>"); } %>
-
Cookie is used to realize the function of "remembering user name", and the validity period is used
It is recommended that cookie s only save English and numbers, otherwise they need to be encoded and decoded
login.jsp
<%! //Define global variables String uname; %> <% //Default flash boolean flag=false; //Get Cookie Cookie[] cookies = request.getCookies(); //Got all the cookies, traversal for(Cookie cookie :cookies){ //If the name of the cookie is "uname", it is the user name if(cookie.getName().equals("uname")){ //This is the user name we entered last time in the cache and assigned to uname uname = cookie.getValue(); //After caching, the cookie must take effect flag = true; } } if(!flag){//If flag is false,! If false is true, the cookie is invalid out.print("cookie Invalid"); }else{ //If the cache is still in effect, the user name is output out.print("cookie:"+uname); } %> <form action="check.jsp" method="post"> user name:<input type="text" name="uname" value="<%=(uname==null?"":uname)%>"> <br> password:<input type="password" name="upwd"><br> <input type="submit" value="Sign in"> </form>
check.jsp
<% //Set encoding method request.setCharacterEncoding("utf-8"); //Get the user name entered by the user and assign it to the name variable String name = request.getParameter("uname"); //Obtain the password entered by the user and assign it to the pwd variable String pwd = request.getParameter("upwd"); //Add user name to Cookie (name,value) Cookie cookie = new Cookie("uname",name); //Cache expires after 10 seconds cookie.setMaxAge(10); //The server prepares cookie s response.addCookie(cookie); //Redirect to A.jsp response.sendRedirect("A.jsp"); %>
A.jsp
There's nothing written in it, just a simple jump
-
-
Session: Session: from the beginning to the end of a session.
a. Browse the website: start - close
b. Shopping: browse, pay, exit
c. Email: browse, write, exit.
a. The session is stored on the server
b. session is shared when requested by the same user (customer)
c. session implementation mechanism:
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-qrvlaiob-1622360006649) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 4. Session: share in the same session. PNG)]
When the client requests the server for the first time( JSESSIONID matching sessionid,If there is no match, the server will generate a session Object (used to save customer information); And each session Object, there will be a unique sessionID(Used to distinguish other session);The server will generate another one cookie,And this cookie of ename=JSESSIONID,value=Server sessionID Value of. Then, while responding to the client, the server will cookie Send it to the client. So far, the client has one cookie(JSESSIONID), Therefore: client cookie You can communicate with the server session One to one correspondence( JSESSIONID-sessionID) Customer second/n When requesting the server for the second time: the server uses the client first cookie Medium JSESSIONID To the server session Medium matching sessionID,If the match is successful( cookie of JSESSIONID and session Medium sessionID Same), indicating that this user is not accessing for the first time, so there is no need to log in again.
example
client: customer Server Mall - bag storage Customer's first deposit: deposit place Judge whether this person has saved a bag(See if you have a key in your hand). If there is no key, assign a key to the customer, and the key will correspond to the cabinet one by one. The second time, continue to judge at the bag storage office. If you have a key, you don't need to assign it again. The key in your hand will correspond to the cabinet one by one.
-
session method
String getId() : obtain sessionId boolean isNew() : Determine whether this is the first visit void invalidate():send session Fail (exit)/(logout) void setAttribute(String name,Object value) By value/Name to store the new value Object getAttribute(String name) Get attribute value by name void setMaxInactiveInterval(second) : Set maximum effective, inactive time int getMaxInactiveInterval(second) : Get the maximum valid inactive time
Example: login:
When the client requests the server for the first time, if the server finds that there is no JSESSIONID in the request, it will create a cookie with name=JSESSIONID and return it to the client.
Cookie: it is not a built-in object and must use new. However, the server will automatically generate a cookie with name=JSESSIONID (New cookie on the server) and return it to the client.
login.jsp
<form action="check.jsp" method="post"> user name:<input type="text" name="uname"><br> password:<input type="password" name="upwd"><br> <input type="submit" value="Sign in"> </form>
check.jsp
<% request.setCharacterEncoding("utf-8"); String name = request.getParameter("uname"); String pwd = request.getParameter("upwd"); if(name.equals("zs") && pwd.equals("abc")){//Suppose the user name is zs and the password is abc //Login succeeded. Assign a session session.setAttribute("uname",name); session.setAttribute("upwd",pwd); System.out.println("sessionID:"+session.getId()); //If there is no activity for more than 10 seconds, the session fails. //Inactive time refers to the time when there is no operation on the web page, the keyboard and mouse do not move, and the session fails after 10 seconds session.setMaxInactiveInterval(10); //Generate a cookie Cookie cookie = new Cookie("uname",name); response.addCookie(cookie); request.getRequestDispatcher("welcome.jsp").forward(request,response); }else{ //Login failed response.sendRedirect("login.jsp"); } %>
welcome.jsp
Welcome: <% String name = (String)session.getAttribute("uname"); //If you visit this page directly instead of logging in, you should return to the login interface //If you are not logged in, the obtained name is null if(name!=null){ out.print(name); %> <a href="invalidate.jsp">cancellation</a> <% }else{//If there is no login, you should jump to the login interface response.sendRedirect("login.jsp"); } %>
invalidate.jsp
<% //Delete all user names / passwords. This method is generally used to delete, because only one information will not be deleted when logging out session.invalidate(); //session failure response.sendRedirect("login.jsp"); //Delete only the user name or another one //session.removeAttribute("uname"); %>
a.jsp
<% out.print(session.getAttribute("uname")); Cookie[] cookies = request.getCookies(); for(Cookie cookie :cookies){ if(cookie.getName().equals("JSESSIONID")){ System.out.println("JSESSIONID:"+cookie.getValue()); } } %>
-
-
The difference between cookie and session
session cookie Save location Server client Security Safer Less safe Saved content Object String
-
Application global object
-
Common methods
String getContextPath() : Get virtual path String getRealPath(String name): Absolute path (absolute path relative to virtual path): pass in the virtual path of the absolute path to be obtained, that is, a virtual path needs to be passed in.
-
Examples
<%= "Virtual path of current project:"+application.getContextPath()%> <%="Absolute path of current project:"+application.getRealPath(": /01-jsp-primary") %>
-
-
Four range objects (small - > large)
pageContext JSP Page container (page Object) The current page is valid request Request object The same request is valid session Session object The same session is valid appliation Global object Globally valid(The whole project is valid)
Methods shared by the above four objects:
Object getAttribute(String name) : Get the attribute value according to the attribute name void setAttribute(String name,Object obj) : Set attribute value (add, modify) setAttribute("a","b"); //If the a object does not exist before, create a new a object; If the a object already exists, the value of a is changed to b void removeAttribute(String name); : Delete the object according to the attribute name
-
pageContext current page is valid (invalid after page Jump)
pageContext.jsp
<% pageContext.setAttribute("hello","world"); request.getRequestDispatcher("pc1.jsp").forward(request,response); %> <%= pageContext.getAttribute("hello") %>
pc1.jsp cannot get
pc1.jsp<br> <%= pageContext.getAttribute("hello") %>
-
Request the same request is valid; Other requests are invalid (valid after the request is forwarded; invalid after the reset)
request.jsp
<% request.setAttribute("hello","world"); request.getRequestDispatcher("rq1.jsp").forward(request,response); %> <%= request.getAttribute("hello") %>
rq1.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> rq1.jsp<br> <%= request.getAttribute("hello") %> </body> </html>
-
Session the same session is valid (no matter how you jump, it is valid; it is invalid after closing / switching the browser)
From login - > exit, all valid
session.jsp
<% session.setAttribute("hello","world"); request.getRequestDispatcher("ss1.jsp").forward(request,response); %> <%= session.getAttribute("hello") %>
ss1.jsp
ss1.jsp<br> <%= session.getAttribute("hello") %>
-
The application global variable is valid during the whole project operation (it is still valid when switching browsers). It is invalid when the service is closed / other projects are started
application.jsp
<% application.setAttribute("hello","world"); request.getRequestDispatcher("al1.jsp").forward(request,response); %> <%= application.getAttribute("hello") %>
al1.jsp
al1.jsp<br> <%= application.getAttribute("hello") %>
-
After multiple projects are shared and restarted, they still need to take effect: JNDI
be careful:
- The above four range objects are assigned by setAttribute() and valued by getAttribute();
- For the above range objects, try to use the minimum range. Because the larger the range of objects, the greater the performance loss.
-
JSP accessing database
-JSP Access database jsp Is in html Nested in java,java The code can be written in jsp Medium(<% %>) Package guide operation: java Project: -jar Copy to project -Right click the jar Package ->bulid path —>add to bulid path web Project: jar Copy to WEB/INF/lib Folder Core: will java Medium JDBC Code to JSP Medium<% %>in
-
User login
index.jsp
<form action="check.jsp" method="post"> user name:<input type="text" name="uname"/><br> password:<input type="password" name="upwd"/><br> <input type="submit" value="Sign in"/><br> </form>
check.jsp
<%@ page import="java.sql.*"%> <% //The login is defined as a method, and the user name and password are passed in as parameters //Mark boolean flag = false; //Connect database Connection conn = null; PreparedStatement ps= null; ResultSet rs = null; try{ //Register driver Class.forName("com.mysql.cj.jdbc.Driver"); //Get connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/datas","root","1051976202"); //Get database operation object String sql = "select * from t_user where loginName=? and loginPwd = ?"; //precompile ps = conn.prepareStatement(sql); //Get data to variable String name = request.getParameter("uname"); String pwd = request.getParameter("upwd"); //Value transmission ps.setString(1,name); ps.setString(2,pwd); //implement rs = ps.executeQuery(); //Process query result set if(rs.next()){ //If it can be executed here, it means that the query data is found, which proves that the login is successful flag = true; } out.print(flag ?"Login successful":"Login failed"); }catch(ClassNotFoundException e){ e.printStackTrace(); }catch(SQLException e){ e.printStackTrace(); }finally{ //close resource if(rs != null){ try{ rs.close(); }catch(SQLException e){ e.printStackTrace(); } } if(ps != null){ try{ ps.close(); }catch(SQLException e){ e.printStackTrace(); } } if(conn != null){ try{ conn.close(); }catch(SQLException e){ e.printStackTrace(); } } } %>
-
Put the login verification code into the java file of the web project and access it through the method
index.jsp
<form action="checkJavaLoginDao.jsp" method="post"> user name:<input type="text" name="uname"/><br> password:<input type="password" name="upwd"/><br> <input type="submit" value="Sign in"/><br> </form>
checkJavaLoginDao.jsp
//When importing a package of java class, the imported package must have a package name, otherwise an error will be reported <%@ page import= "login.LoginDao" %> <% String name = request.getParameter("uname"); String pwd = request.getParameter("upwd"); //Call the login method in java LoginDao dao = new LoginDao(); boolean flag =dao.login(name,pwd); out.print( flag? "Login successful":"Login failed"); %>
LoginDao.java
package login; import java.sql.*; public class LoginDao { //Return true to indicate login success, and false to indicate login failure. public boolean login(String name ,String pwd) { //The login is defined as a method, and the user name and password are passed in as parameters //Mark boolean flag = false; //Connect database Connection conn = null; PreparedStatement ps= null; ResultSet rs = null; try{ //Register driver Class.forName("com.mysql.cj.jdbc.Driver"); //Get connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/datas","root","1051976202"); //Get database operation object String sql = "select * from t_user where loginName=? and loginPwd = ?"; //precompile ps = conn.prepareStatement(sql); //Get data to variable //The request object here is the built-in object of jsp and cannot be used here. We can pass in the user name and password as parameters // String name = request.getParameter("uname"); // String pwd = request.getParameter("upwd"); //Value transmission ps.setString(1,name); ps.setString(2,pwd); //implement rs = ps.executeQuery(); //Process query result set if(rs.next()){ //If it can be executed here, it means that the query data is found, which proves that the login is successful flag = true; } //The out here can only be used in jsp //out.print(flag "login succeeded": "login failed"); }catch(ClassNotFoundException e){ e.printStackTrace(); }catch(SQLException e){ e.printStackTrace(); }finally{ //close resource if(rs != null){ try{ rs.close(); }catch(SQLException e){ e.printStackTrace(); } } if(ps != null){ try{ ps.close(); }catch(SQLException e){ e.printStackTrace(); } } if(conn != null){ try{ conn.close(); }catch(SQLException e){ e.printStackTrace(); } } } //Return marked return flag; } }
-
Note: if an error occurs in the jsp: Xxx type is not resolved... / the import xxx cannot be resolved
Try the following steps: a,(Maybe Jdk,tomact Version problem): right click the item——>build path->Report the error libary or Lib Re import after deletion b,Empty various caches: right click the item——>Clean tomact... clean(menu bar Project —clean Or enter tomcat Directory, delete the contents work (subdirectories of) c,Delete previous tomcat,Re decompress and configure tomcat,Restart the computer d,If there is no package before the class, add the class to the package.
-
JavaBean
-
What is a JavaBean?
Just now, we transferred the code of login operation in JSP to LoginDao In Java, the LoginDao class is called JavaBean.
-
Functions of JavaBeans:
- Reduce jsp complexity
- Improve code reuse. (login operations anywhere in the future can be implemented by calling the LoginDao class
-
Definition of javaBean (javaBean is a class):
-
Public modified class, public modified parameterless construction method
-
If there are attributes in this class, all attributes are private and set/get is provided (if the return value is Boolean, get can be replaced by is)
public class User{ private boolean flag; public User(){} public boolean isFlag(){//For attributes of boolean type, isXxx() is equivalent to getXxx() return isFlag; } public void setFlag(boolean Flag){ this.flag = flag; } }
-
-
At the use level, JavaBean s are divided into two categories:
-
javaBean encapsulating business logic (LoginDao.java encapsulates login logic)
You can encapsulate the JDBC code in jsp into logindao Java class (LoginDao.java)
-
JavaBean s (entity classes, Student.java, PerSon.java) that encapsulate data
Corresponds to a table in the database
Login login = new Login(name, pwd) / / the login object encapsulates two data (user name, password)
example:
Use the Login class to encapsulate the user name and password. When calling LoginDao2, just pass an object of Login type
index.jsp
<form action="checkLogin.jsp" method="post"> user name:<input type="text" name="uname"/><br> password:<input type="password" name="upwd"/><br> <input type="submit" value="Sign in"/><br> </form>
LoginDao2.java
package login; import java.sql.*; import entity.Login; public class LoginDao2 { //Return true to indicate login success, and false to indicate login failure. public boolean login(Login login) { //The login is defined as a method, and the user name and password are passed in as parameters //Mark boolean flag = false; //Connect database Connection conn = null; PreparedStatement ps= null; ResultSet rs = null; try{ //Register driver Class.forName("com.mysql.cj.jdbc.Driver"); //Get connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/datas","root","1051976202"); //Get database operation object String sql = "select * from t_user where loginName=? and loginPwd = ?"; //precompile ps = conn.prepareStatement(sql); //Get data to variable //The request object here is the built-in object of jsp and cannot be used here. We can pass in the user name and password as parameters // String name = request.getParameter("uname"); // String pwd = request.getParameter("upwd"); //Value transmission ps.setString(1,login.getName()); ps.setString(2,login.getPwd()); //implement rs = ps.executeQuery(); //Process query result set if(rs.next()){ //If it can be executed here, it means that the query data is found, which proves that the login is successful flag = true; } //The out here can only be used in jsp //out.print(flag "login succeeded": "login failed"); }catch(ClassNotFoundException e){ e.printStackTrace(); }catch(SQLException e){ e.printStackTrace(); }finally{ //close resource if(rs != null){ try{ rs.close(); }catch(SQLException e){ e.printStackTrace(); } } if(ps != null){ try{ ps.close(); }catch(SQLException e){ e.printStackTrace(); } } if(conn != null){ try{ conn.close(); }catch(SQLException e){ e.printStackTrace(); } } } //Return marked return flag; } }
Login.java
package entity; public class Login { private String name; private String pwd; public Login() { } public Login(String name,String pwd) { this.name= name; this.pwd=pwd; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPwd() { return pwd; } public void setPwd(String pwd) { this.pwd = pwd; } }
checkLogin.jsp
<%@ page import= "login.LoginDao2" %> <%@ page import= "entity.Login" %> <% String name = request.getParameter("uname"); String pwd = request.getParameter("upwd"); Login login = new Login(name,pwd); //Call the login method in java LoginDao2 dao = new LoginDao2(); boolean flag =dao.login(login); out.print( flag? "Login successful":"Login failed"); %>
-
-
Note: the JavaBean encapsulating data corresponds to a table (Login(name,pwd)) in the database
JavaBeans that encapsulate business logic are used to operate a JavaBean that encapsulates data
It can be found that JavaBean s can be simplified, code (jsp - > jsp + Java) and code reuse (LoginDao.java)
MVC and Servlet
-
MVC design mode:
M: Model: a function implemented with JavaBean s
5: V iew View: it is used to display and interact with users. It is implemented by front-end technologies such as html, js, css, jsp and jquery
C: Controller: receive the request and jump the request to the model for processing; After the model is processed, the processing result is returned to the request. It can be implemented with JSP, but it is generally recommended to use Servlet to implement the controller
[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-jrnnl045-1622360006650) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ picture \ 5, MVC design mode. PNG)]
JSP Code——>Translate into java Code (Translated) jsp Code is a Servlet)->Compile into JS
-
Servlet:
java classes must conform to certain specifications:
-
Must inherit: javax servlet. http. HttpServlet
-
You must override the doGet() or doPost() methods
doGet(): receive and process all get submission requests, doPost(): receive and process all Post submission requests
To use servvet, you must configure:
-
Servlet2.5: web.xml
-
Servlet3.0: @webServlet
-
Root directory of Web project: WebContent, src
-
Servlet2.5 configuration process:
Required labels
<servlet> <servlet-name> </servlet-name> <servlet-class> </servlet-class> </servlet> <servlet-mapping> <servlet-name> </servlet-name> <url-pattern> </url-pattern> </servlet-mapping>
Specific process:
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-orb6am4r-1622360006652) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 6. Mapping of Servlet2.5. PNG)]
Request——> cover web.xml Medium<url-pattern>Intercepted——>Then according to the<servlet-mapping>Sibling labels in labels<servlet-name>De matching<servlet>In label<servlet-name>,these two items. name It must be consistent to match successfully. There is no special naming rules, as long as the consistent match can be found——>After the matching is successful, the peer label is found<servlet-class>Medium java File, and finally submit the request to the<servlet-class>implement
-
Servlet2.5 configuration and Implementation
index.jsp
<--! here href="HelloServlet"Where jsp Yes WebContent Directory, therefore, the request issued HelloServlet,Is to request the root directory of the project. --> <a href="HelloServlet">HelloServlet</a> <form action="HelloServlet" method="post"> <input type="submit"/> </form>
HelloServlet
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doGet..."); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("doPost..."); //this.doGet(req, resp); This is usually written. You can only deploy the value in one method } }
web. Configuration of XML file (only add things, and add all contents to the web app tag)
<servlet> <--! there sevlet-name Must be compatible with servlet-name bring into correspondence with,Can match successfully--> <servlet-name>HelloServlet</servlet-name> <--! Here is the requested java file--> <servlet-class>servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <--! there sevlet-name Must be consistent with the above servlet-name bring into correspondence with,Can match successfully--> <servlet-name>HelloServlet</servlet-name> <--! there url-pattern Intercept the request, and then according to the peer label servlet-name De matching servlet In label servlet-name --> <url-pattern>/HelloServlet</url-pattern> </servlet-mapping>
-
Review creating the first Servlet
Write a class, inherit HttpServlet, override doGet() and doPost() methods, and then write web servlet mapping in XML.
-
Quickly generate servlets with Eclipse
Directly create a new Servlet! (inheritance, rewriting and web.xml can be generated automatically with the help of Eclipse)
Right click to create a new Servlet, and then fill in the corresponding package name and class name consistent with next. The two methods, getdottweb.Servlet and getdottwet, are automatically overridden Automatically configure the relevant contents of the Servlet in XML.
-
Servlet3. Configuration of 0
-
Servlet3.0 and servlet2 5 difference between
Servlet3.0 does not need to be on the web XML, but you need to write comments on the definition of servlet class: @ WebSerlet(""), where the value is the value originally placed in the URL pattern tag
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-xknpi7d2-1622360006653) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 7. Mapping of Servlet3.0. PNG)]
-
Servlet3.0 configuration specific implementation (no longer configured in web.xml)
index.jsp
<a href="HelloServlet">HelloServlet</a> <form action="HelloServlet" method="post"> <input type="submit"/> </form>
HelloServlet.java
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/HelloServlet") public class HelloServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("Servlet3.0 implement"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
-
Matching process: the requested address matches the value in @ WebServlet. If the matching is successful, it means that the class corresponding to the annotation is requested
-
-
Root directory of the project: WebContent, src (all construction paths)
-
If you want to set other folders as the root path, right-click the folder - > bulid path - > use as source folder, or directly right-click - > New - > source folder on src folder
-
If there is a file index. In WebContent JSP, src has a servlet java
If: index.jsp Medium request<a href="abc">...</a>,Then the search scope: will be src Find it in the root directory, and it will also be found in the WebContent Found in root directory abc If: index.jsp Medium request<a href="a/abc">...</a>,Search scope: first src or WebContent Search in a Directory, and then in a Find in directory abc be careful: web.xml Medium/:Represents the root path of the project /Represents http://localhost:8080/Servlet25Project/ jdp Medium/: Server root path http://localhost:8080/
-
-
Five life cycles of Servlet
The first stage: loading.
The second stage: initialization. init(), which will be executed after the Servlet is loaded and the instance object is
The third stage: service. service()——doGet(),doPost()
The fourth stage: destruction. destroy() is executed when the Servlet is recycled by the system.
The fifth stage: uninstall.
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-2emp6tcm-1622360006654) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 8. Servlet life cycle. PNG)]
-
init(): Servlet2. Both 5 and 3.0 are default. They will be executed when accessing the servlet for the first time (only this time)
It can be modified to execute automatically when Tomcat starts.
-
Servlet2.5: On the web Add the following to the servlet tag in the XML file:
<servlet> <load-on-startup> 1 </load-on-startup> </servlet> be careful: Where "1" indicates the first execution. Because there may be more than one in a project Servlet Class, if you want to Tomcat When loading at startup, there needs to be a sequence, and the following values are: 2, 3, 4, etc., and so on.
-
Servlet3.0: continue to add in the above annotation of the class
@WebServlet(value="/HelloServlet",loadOnStartup=1) be careful: When the annotation has only one value, the previous value Can save. Cannot be omitted when there are multiple values @WebServlet("/HelloServlet")
-
-
service() - > doget(), doPost(): call several times and execute several times
-
destroy(): execute once when the tomcat service is closed.
demonstration
index.jsp
<a href="HelloServlet">HelloServlet</a> <form action="HelloServlet" method="post"> <input type="submit"/> </form>
HelloServlet.java
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(value="/HelloServlet",loadOnStartup=1) public class HelloServlet extends HttpServlet { public void init() throws ServletException{ System.out.println("init..."); } @Override public void destroy() { System.out.println("destroy...."); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("service Concrete implementation of(doGet()...doPost()...)"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
-
-
-
Servlet API: it consists of two software packages: the package corresponding to HTTP protocol and the package corresponding to other software packages except HTTP protocol. That is, the servlet API can be applied to any communication protocol.
The Servlet we study is located in javax Servlet. The classes and interfaces in the HTTP package are the basic HTTP protocol.
-
Servlet inheritance
[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-25gllpsx-1622360006654) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 9. Servlet inheritance. PNG)]
ServletConfig: Interface
-
Common methods
ServletContext getServletContext(): obtain Servlet Context object application The global object is the ServletContext Class String getInitParameter(String name): At present Servlet Within the scope, get the name name Parameter value of (initialization parameter) ServletContext Methods in classes (and application The method of global object is the same, because the object is instantiated through this class): getContextPath(): Get relative path getRealPath(): Get absolute path serAttribute(),getAttribute() __________ String getInitParameter(String name):At present Web Within the scope of the container, get the name name Parameter value of (initialization object). web Containers include servlet,So this range is relatively large.
-
Servlet2.5 get servlet parameters and get the parameters of name in the web
index.jsp
web.xml<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <!-- Throughout web Set initialization parameters in container --> <context-param> <param-name>globalParam</param-name> <param-value>global value...</param-value> </context-param> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>servlet.HelloServlet</servlet-class> <!-- In this servlet Set initialization parameters in --> <init-param> <param-name>servletParamname</param-name> <param-value>servletParamValue...</param-value> </init-param> <!-- Set automatic initialization when the server starts servlet,This setting is best written in servlet Last line of label --> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HelloServlet</servlet-name> <url-pattern>/HelloServlet</url-pattern> </servlet-mapping> </web-app>
HelloServlet.java
package servlet; import java.io.IOException; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloServlet extends HttpServlet { @Override public void init() throws ServletException{ System.out.println("init..."); //Get the initialization parameters of the current servlet //getInitParameter is the method of interface ServletConfig, which is implemented by its subclass GenericServlet, //HttpServlet inherits genericservlet, and our custom class now inherits HttpServlet //Therefore, it can be called directly with super. String value = super.getInitParameter("servletParamname"); System.out.println("current Servlet Parameters of servletparamname The values are:"+value); //Gets the initialization parameters of the current Web container. //Get servlet context object using method ServletContext servletContext = super.getServletContext(); //Get value using method String globalValue = servletContext.getInitParameter("globalParam"); System.out.println("current Web Container parameters globalValue The values are:"+globalValue); } @Override public void destroy() { System.out.println("destroy...."); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("service Concrete implementation of(doGet()...doPost()...)"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
-
Servlet3.0 set the initial value for the current servlet:
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebInitParam; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; //Note: this annotation only belongs to a specific servlet, so the initialization parameters cannot be set for the entire web container (if you want to set the initialization parameters of the web container through 3.0, you still need to set them in web.xml) @WebServlet(value="/HelloServlet",loadOnStartup=1,initParams= { //The servlet initial value is set here @WebInitParam(name = "Servletparaname30", value = "Servletparavalue30") } ) public class HelloServlet extends HttpServlet { public void init() throws ServletException{ System.out.println("init..."); //obtain String value = super.getInitParameter("Servletparaname30"); System.out.println("current servlet Initialization parameters for servletparaname30 Value of"+value); } @Override public void destroy() { System.out.println("destroy...."); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("service Concrete implementation of(doGet()...doPost()...)"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
-
Methods in HttpServletRequest: (same as request). Example: setAttrite(), getCookies(), getMethod()
Methods in HttpServletResponse: the same as response
[the external chain image transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-t8wl5u2v-1622360006655) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 10, ServletRequeset and servletreply. PNG)]
-
Many methods of the GenericServlet class are empty implementations
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-wobgcqwk-1622360006655) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 11. Empty implementation. PNG)]
-
Servlet usage level:
In the Eclipse project, create a Servlet in src, and then rewrite doGet() and doPost(). (doGet(), doPost only write one, and the other can call the one written)
-
MVC case
-
MVC case (the jar package of jdbc should be imported into the project and the lib folder in the WEB-INF folder in the WebContent folder)
[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-efl9prk3-1622360006656) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ picture \ 12, MVC case. PNG)]
login.jsp (View layer)
<form action="loginServlet"> user name:<input type="text" name="uname"><br> password:<input type="password" name="upwd"><br> <input type="submit" value="Sign in"> </form>
LoginDao.java (Model layer: Model encapsulating logic: function)
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import entity.Login; //The model layer is used to process login: query the database public class LoginDao { //Sign in public static boolean login(Login login) { //Make a mark boolean flag = false; Connection conn = null; PreparedStatement ps= null; ResultSet rs= null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/datas","root","1051976202"); String sql = "select * from t_user where loginName=? and loginPwd=?"; ps = conn.prepareStatement(sql); ps.setString(1,login.getUname()); ps.setString(2,login.getUpwd()); rs = ps.executeQuery(); if(rs.next()) { flag=true; } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch(SQLException e) { e.printStackTrace(); }finally { if(rs != null) { try { rs.close(); }catch(SQLException e){ e.printStackTrace(); } } if(ps != null) { try { ps.close(); }catch(SQLException e){ e.printStackTrace(); } } if(conn != null) { try { conn.close(); }catch(SQLException e){ e.printStackTrace(); } } } return flag; } }
Login.java (Model layer: Model encapsulating data: entity class) - equivalent to a table in the database
package entity; public class Login { private int id; private String uname; private String upwd; //Construction method public Login() { } public Login(String uname, String upwd) { this.uname = uname; this.upwd = upwd; } public Login(int id, String uname, String upwd) { this.id = id; this.uname = uname; this.upwd = upwd; } //get and set methods public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUname() { return uname; } public void setUname(String uname) { this.uname = uname; } public String getUpwd() { return upwd; } public void setUpwd(String upwd) { this.upwd = upwd; } }
LoginServlet.java (Controller: login Controller)
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import dao.LoginDao; import entity.Login; //Controller layer: receive the view request and distribute it to Model for processing public class loginServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Process login request.setCharacterEncoding("utf-8"); String name = request.getParameter("uname"); String pwd = request.getParameter("upwd"); Login login = new Login(name,pwd); //Call the login function of the model layer boolean flag = LoginDao.login(login); //System.out.println(flag "login succeeded": "login failed"); if(flag) { //Log in successfully and jump to the welcome interface response.sendRedirect("welcome.jsp"); }else { //Login failed. Return to the login interface again response.sendRedirect("login.jsp"); } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
welcome.jsp
Welcome
flow chart
[the external chain image transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-djgoci8y-1622360006657) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 13. MVC login instance understanding. PNG)]
Three tier architecture
-
Three tier architecture
-
The three-tier architecture is consistent with the goal of MVC design pattern: to understand coupling and improve code reuse.
Difference: different perspectives on project understanding
-
Three layer composition:
Presentation layer (USL: User Show Layer, view layer), generally located in XXX Servlet package
- Front desk: corresponding MVC Medium View,Used for user interaction and interface display jsp,js,html,css,jquery etc. web front-end technology - Background: for MVC in Controller,It is used to control the jump and call the business logic layer. Servlet(SpringMVC,Struts2)
Business Logic Layer (BLL: Business Logic Layer, service layer), generally located in XXX Service package (or: xxx.manager, xxx.bll)
- Receive requests and calls from the presentation layer - Assemble the data access layer and perform logical operations (add, delete, modify, query, delete: query)+(deleted), can be further divided
Data Access Layer (DAL: Data Access Layer, Dao layer), generally located in XXX Dao package
Direct access to the database, atomic operations (addition, deletion, modification and query), can not be further divided
-
Three tier architecture diagram
[the external chain image transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-hnoy2ukb-1622360006658) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 14. Understanding of three-tier architecture. PNG)]
-
The difference between three-tier architecture and MVC is illustrated
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-9gfbcnz8-1622360006659) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 15. The difference between MVC and three-tier architecture. PNG)]
-
The relationship between the three layers: the upper layer passes the request to the lower layer, and the lower layer returns it to the upper layer after processing.
The upper layer depends on the lower layer. Dependency: the code is understood to hold member variables, or it is understood that the premise of A is that there must be B first (there must be A database before there can be A DAO layer, and the DAO layer depends on the database)
-
Note: one Servlet corresponds to one function. Therefore, if there are five functions of adding, deleting, modifying and querying (querying multiple and single), five servlets need to be created.
-
request.getParameter() and request Setattribute() difference
(1)request.getParameter()Through the implementation of container to achieve similar post,get Data passed in by other methods request.setAttribute()and getAttribute()Just in web The internal flow of the container is only the request processing stage. (2)request.getParameter()The data passed by the method will be transferred from Web Client to Web Server side, representative HTTP Request data. request.getParameter()Method return String Type of data. request.setAttribute()and getAttribute()The data passed by the method will only exist in Web Inside container HttpServletRequest Class has setAttribute()Method, but not setParameter()method. For example, suppose two WEB When there is a link relationship between pages, it means to start from 1.jsp Link to 2.jsp When, the linked is 2.jsp Can pass getParameter()Method to obtain the request parameters. Suppose 1.jsp Inside <form name="form1" method="post" action="2.jsp"> Please enter user name:<input type="text" name="username"> <input type="submit" name="Submit" value="Submit"> </form> In 2.jsp Passed in request.getParameter("username")Method to obtain the request parameters username: <% String username=request.getParameter("username"); %> But if two WEB When the is a forwarding relationship, the forwarding purpose WEB Can use getAttribute()Method and transfer source WEB share request Data in scope For example: Have 1.jsp And 2.jsp 1.jsp,Hope to 2.jsp Pass the current user name - First in 1.jsp The following is called setAttribute()method: <% String username=request.getParameter("username"); request.setAttribute("username",username); %> <jsp:forward page="2.jsp" />//Forward to 2 interface In 2.jsp Passed in getAttribute()Method to get the user name: <% String username=(String)request.getAttribute("username"); %>
-
The difference between setAttribute method of request object and session object
setAttribute This method, in JSP Built in object session and request All have this method. The function of this method is to save data, and then it can be used getAttribute Method to remove. Like now User Object, Usercurruser=newUser("zhangsan",20,"male"); 1,request.setAttribute("curruser",curruser)This method is to curruser This object is saved in request In the scope, and then you can get your value on the forwarded page. If you know some frames, those frame tags can also be obtained, such as struts Labels, and jstl. If you can't do any of this, you can jsp Page writing java Little foot originally obtained:<%Usermyuser=(User)request.getAttribute("curruser")%>,stay jsp Page display value:<%=myuser.getName()%>. 2,session.setAttribute("curruser",curruser). The only difference between this method and the above method is the scope, which is when you start the whole program session If the data is saved in, you can get this value at any time no matter which page you are on. It is global, as long as your program is started. session The default expiration time is 30 minutes, which is invalid. You can modify this value. request.getSession().setAttribute("Binding name,Binding value); The meaning of this code is: get session object,Then the object to be bound/Set the value session A session of a user on an object shares one session Object.
-
Three layer case: student information management system
Student management system diagram
[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-22bsdmpu-1622360006659) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ picture \ 16, student management system. PNG)]
Three layer structure diagram of student management system
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-ipzrl6lx-1622360006660) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 18, three-tier architecture process. PNG)]
Diagram of coding setting in out response
[the external link image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-zxrb3gi0-1622360006661) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 17. out response. PNG)]
Student.java
package entity; public class Student { private int sno; private String sname; private int sage; private String saddress; public Student() { } public Student(String sname, int sage, String saddress) { this.sname = sname; this.sage = sage; this.saddress = saddress; } public Student(int sno, String sname, int sage, String saddress) { this.sno = sno; this.sname = sname; this.sage = sage; this.saddress = saddress; } public int getSno() { return sno; } public void setSno(int sno) { this.sno = sno; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public int getSage() { return sage; } public void setSage(int sage) { this.sage = sage; } public String getSaddress() { return saddress; } public void setSaddress(String saddress) { this.saddress = saddress; } @Override public String toString() { return "Student [sno=" + sno + ", sname=" + sname + ", sage=" + sage + ", saddress=" + saddress + "]"; } }
StudentDao.java
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import entity.Student; //Data access layer: addition, deletion, modification and query of atomic layer public class StudentDao { //Defined separately, it can be applied to multiple methods private final String URL = "jdbc:mysql://localhost:3306/datas"; private final String USERNAME = "root"; private final String PASSWORD = "1051976202"; //Add students according to student number public boolean addStudent(Student student) { boolean flag = false; Connection conn = null; PreparedStatement ps = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); //Increase students String sql = "insert into student(sno,sname,sage,saddress) values(?,?,?,?) "; ps =conn.prepareStatement(sql);//precompile //For? Transfer value ps.setInt(1,student.getSno()); ps.setString(2,student.getSname()); ps.setInt(3,student.getSage()); ps.setString(4, student.getSaddress()); //Returns the number of successful inserts int count = ps.executeUpdate(); //If the number of successful entries is 1, the addition is successful. if(count==1) { flag = true; } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally {//close resource if(ps != null) { try { ps.close(); }catch(SQLException e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); }catch(SQLException e) { e.printStackTrace(); } } } return flag; } //Delete students according to student number public boolean deleteStudentBySno(int sno) { boolean flag = false; Connection conn = null; PreparedStatement ps = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); String sql = "delete from student where sno=? "; ps =conn.prepareStatement(sql); ps.setInt(1, sno); int count = ps.executeUpdate(); if(count==1) { flag = true; } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { if(ps != null) { try { ps.close(); }catch(SQLException e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); }catch(SQLException e) { e.printStackTrace(); } } } return flag; } /** * Modify student information according to student number * @param sno Pass in the student number of the student to be modified * @param student This is the information of the student to be modified */ public boolean updateStudentBySno(int sno,Student student) { boolean flag = false; Connection conn = null; PreparedStatement ps = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); //modify String sql = "update student set sname=?,sage=?,saddress=? where sno=? "; ps =conn.prepareStatement(sql);//precompile //For? Transfer value //Contents to be modified ps.setString(1,student.getSname()); ps.setInt(2,student.getSage()); ps.setString(3, student.getSaddress()); //Who modified it ps.setInt(4,sno); //Returns the number of successful inserts int count = ps.executeUpdate(); //If the number of successful entries is 1, the addition is successful. if(count==1) { flag = true; } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally {//close resource if(ps != null) { try { ps.close(); }catch(SQLException e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); }catch(SQLException e) { e.printStackTrace(); } } } return flag; } //Judge whether there is a student according to the student number public boolean isExist(int sno) { //Call the method of querying students according to student number. If it is blank, the student does not exist; otherwise, the student exists. return queryStudentBysno(sno)==null?false:true; } //Query students according to student number public Student queryStudentBysno(int sno) { //New student object Student student = null; //Connect database Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); String sql = "select * from student where sno=? "; ps =conn.prepareStatement(sql); ps.setInt(1,sno); rs = ps.executeQuery(); //Return if there is data if(rs.next()) { int no = rs.getInt("sno"); String name = rs.getString("sname"); int age = rs.getInt("sage"); String address = rs.getString("saddress"); //Encapsulate data student = new Student(no,name,age,address); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { if(rs != null) { try { rs.close(); }catch(SQLException e) { e.printStackTrace(); } } if(ps != null) { try { ps.close(); }catch(SQLException e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); }catch(SQLException e) { e.printStackTrace(); } } } return student; } //Query all students (many) public List<Student> queryAllStudents() { //Create a collection to store student information List<Student> students = new ArrayList<>(); //New student object Student student = null; //Connect database Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); String sql = "select * from student"; ps =conn.prepareStatement(sql);//precompile rs = ps.executeQuery(); //implement //Use loops to put student objects into a collection while(rs.next()) { int no = rs.getInt("sno"); String name = rs.getString("sname"); int age = rs.getInt("sage"); String address = rs.getString("saddress"); //Encapsulate data student = new Student(no,name,age,address); //Put objects into collection students.add(student); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { if(rs != null) { try { rs.close(); }catch(SQLException e) { e.printStackTrace(); } } if(ps != null) { try { ps.close(); }catch(SQLException e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); }catch(SQLException e) { e.printStackTrace(); } } } return students; } }
StudentService.java
package service; import java.util.List; import dao.StudentDao; import entity.Student; //Business logic layer: add, delete, modify and check logically, and assemble dao layer public class StudentService { //Create a StudentDao object to assemble StudentDao studentDao = new StudentDao(); //Method of adding (add: query + add) public boolean addStudent(Student student) { //First judge whether it exists, and then add if it exists if(!studentDao.isExist(student.getSno())) { //If the student does not exist, add the student. /*studentDao.addStudent(student); flag = true; */ //The addStudent method that is merged and called directly returns a Boolean value. Just return return studentDao.addStudent(student); } return false; } //Deletion method public boolean deleteStudentBySno(int sno) { //First judge whether this person exists, and delete it if it exists if(studentDao.isExist(sno)) { return studentDao.deleteStudentBySno(sno); } return false; } //Method of change public boolean updateStudentBySno(int sno,Student student) { if(studentDao.isExist(sno)) { return studentDao.updateStudentBySno(sno, student); } return false; } //Check students according to student number public Student queryStudentBySno(int sno) { return studentDao.queryStudentBysno(sno); } //Query all students public List<Student> queryAllStudents(){ return studentDao.queryAllStudents(); } }
AddstudentServlet.java
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.Student; import service.StudentService; //Add student Servlet public class AddstudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Sets the encoding type of the request request.setCharacterEncoding("utf-8"); //Receive add JSP user input int no = Integer.parseInt(request.getParameter("sno")); String name = request.getParameter("sname"); int age = Integer.parseInt(request.getParameter("sage")); String address = request.getParameter("saddress"); //Encapsulate this data into a Student object Student student = new Student(no,name,age,address); //Create a service object to call the function of adding students StudentService studentService = new StudentService(); //Add student boolean isAddSuccess = studentService.addStudent(student); /* * jsp Built in objects: out, request, session, application * In the servlet, these built-in objects can be obtained as follows: * out: PrintWriter out = response.getWriter(); * session: request.getSession(); * application: request.getServletContext(); */ //Set the encoding type when responding response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("utf-8"); //Respond after setting the encoding type //Get out object in servlet PrintWriter out = response.getWriter(); //Phase I // if(isAddSuccess) { // //If the addition is successful, re query all students // out.print("increase succeeded"); // }else { // out.println("add failed"); // } //Phase II // if(isAddSuccess) { // //If the addition is successful, re query all students // //out.print("increase succeeded"); // response.sendRedirect("QueryAllStudentServlet"); // }else { // out.println("add failed"); // } //Stage 3: new tips //Pass a value to the request field if(isAddSuccess) { request.setAttribute("isSuccess","Increase success"); }else{ request.setAttribute("isSuccess","Add failed"); } //In any case, go to the all student information interface //Because data needs to be transmitted, the method of request forwarding is used request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
DeleteStudentServlet.java
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import service.StudentService; //Delete student's Servlet public class DeleteStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Sets the encoding type of the request request.setCharacterEncoding("utf-8"); //Accept the student number from the front end int no = Integer.parseInt(request.getParameter("sno")); //Create a new Service object StudentService service = new StudentService(); //Call the method to delete the student boolean isDeleteSuccess = service.deleteStudentBySno(no); //Set the encoding type when responding response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("utf-8"); //Phase I // if(isDeleteSuccess) { // //Get out object in servlet // /*PrintWriter out = response.getWriter(); // out.print("");*/ // //Merge // response.getWriter().print("deletion succeeded"); // }else { // response.getWriter().print("deletion failed"); // } //Phase II // if(isDeleteSuccess) { // //After the deletion is successful, re query all student information, namely: // //Redirect to QueryAllStudentServlet // response.sendRedirect("QueryAllStudentServlet"); // }else { // response.getWriter().print("deletion failed"); // } //Stage 3: add or delete prompt information if(isDeleteSuccess) { request.setAttribute("isSuccess","Deleted successfully"); }else{ request.setAttribute("isSuccess","Delete failed"); } //In any case, go to the all student information interface //Because data needs to be transmitted, the method of request forwarding is used request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
QueryAllStudentServlet.java
package servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.Student; import service.StudentService; //Query all students public class QueryAllStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //Call service logic StudentService service = new StudentService(); //Call the method to query all students List<Student> students = service.queryAllStudents(); //Save data request.setAttribute("students",students); //Because there is data in the request, you need to jump through request forwarding (redirection will lose the request field) //Although using the session object, redirection and forwarding will not lose data, but the session consumes more resources //Ranking of resources: pagecontext (valid for the same page) < request (valid for the same time)< //< session < application request.getRequestDispatcher("index.jsp").forward(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
QueryStudentBySnoServlet.java
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.Student; import service.StudentService; //Query students by student number public class QueryStudentBySnoServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); int no = Integer.parseInt(request.getParameter("sno")); StudentService service = new StudentService(); Student student = service.queryStudentBySno(no); //System.out.println(student); //When querying all the information of the student, display the student through the JSP on the front desk: studentinfo jsp //Save the student's information to the reuqest field first request.setAttribute("student",student); //If there is no data in the request field, use redirect response sendRedirect(); //If there is data in the request field, use the method of request forwarding request.getRequestDispatcher("studentInfo.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
UpdateStudentServlet.java
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.Student; import service.StudentService; //Methods of modifying student information public class UpdateStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Sets the encoding type of the request request.setCharacterEncoding("utf-8"); //Obtain the student number of the student to be modified int no = Integer.parseInt(request.getParameter("sno")); //Get the content that needs to be modified and encapsulate it into an entity class (java bean) String name = request.getParameter("sname"); int age = Integer.parseInt(request.getParameter("sage")); String address = request.getParameter("saddress"); //Encapsulate the modified content into Student Student student = new Student(name,age,address); //Create a new Service object StudentService service = new StudentService(); //Call student's method boolean isUpdateSuccess = service.updateStudentBySno(no, student); //Set the encoding type when responding response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("utf-8"); //Phase I // if(isUpdateSuccess) { // //response.getWriter().print("modified successfully"); // }else { // response.getWriter().print("modification failed"); // } //Phase II // if(isUpdateSuccess) { // //After the modification is successful, re query all student information, that is, redirect to QueryAllStudentServlet // response.sendRedirect("QueryAllStudentServlet"); // }else { // response.getWriter().print("modification failed"); // } if(isUpdateSuccess) { request.setAttribute("isSuccess","Modified successfully"); }else{ request.setAttribute("isSuccess","Modification failed"); } //In any case, go to the all student information interface //Because data needs to be transmitted, the method of request forwarding is used request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
index.jsp
<%@page import="java.util.List"%> <%@page import="entity.Student" %> <%@page import="java.lang.String" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <script type="text/javascript" src="js/jquery-1.8.3.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("tr:odd").css("background-color","lightgray"); }); </script> <meta charset="UTF-8"> <title>Student information</title> </head> <body> <!-- When you're here, you have to do it first QueryAllStudentServlet because index This is needed in the servlet Return data, otherwise index Just execute it null So put QueryAllStudentServlet Put on web.xml First in<welcome-file> In the label, server This will be executed after startup servlet,Then jump to by forwarding Should index in --> <!-- Problems needing attention during running: you cannot right-click to run on this page, - Right click in the project list to run - Or in QueryAllStudentServlet Right click Run --> <!-- Phase III: each increase/modify/Prompt whether the deletion is successful or not --> <% //Get the prompt to judge whether it is successful String success =(String)request.getAttribute("isSuccess"); /* "".equals()Can avoid null pointers If you simply show whether the operation is successful, you can use this method to subtract the judgment of null pointer After adding / deleting / modifying successfully, pass in yes and vice versa: no if("yes".equals(success)){ out.print("Operation succeeded "); }else if("no".equals(success)){ out.print("Operation failed ''); } */ //Use the method of intercepting string to judge //(Master) The String substring(int beginIndex) parameter is the starting subscript intercepted string //System.out.println("http://www.baidu.com".substring(7)); //www.baidu.com //(Master) String substring(int beginIndex,int endIndex) intercepts some strings //beginIndex start position (including) endIndex end position (excluding) //System.out.println("http://www.baidu.com".substring(7,10)); //www /* if(success != null){ if("Success ". equals(success.substring(2))){ out.print(success); }else if("Failed ". equals(success.substring(2))){ out.print(success); } } */ //Two other methods: //(Master) boolean contains(CharSequence s) //Judge whether the previous string contains the following string, including: return true, excluding: return false //Here, success. Is called at the bottom of contains ToString () method, so null pointers should also be processed here. If they are not null, they can be executed again /* if(success != null){ if("Added successfully deleted successfully modified successfully ". contains(success)){ out.print(success); }else if("Adding failed deleting failed modifying failed ". contains(success)){ out.print(success); } } */ //(Master) boolean endsWith(String suffix) //Determines whether the current string ends with a string if(success != null){ if(success.endsWith("success")){ out.print(success); }else if(success.endsWith("fail")){ out.print(success); } } %> <table border="1px"> <tr> <th>Student number</th> <th>full name</th> <th>Age</th> <!-- <th>address</th> --> <th>operation</th> </tr> <% //Use getAttribute to get the data in the requset field //Because the return value of this method is of type Object, cast is used List<Student> students = (List<Student>)request.getAttribute("students"); //Traverse the data in the output set for(Student student:students){ //One person's data is output in each cycle, which is separated by java code blocks %> <!-- Intermediate use java Expression to get --> <tr> <!-- Click the student number to display all the information of the student --> <td><a href="QueryStudentBySnoServlet?sno=<%=student.getSno()%>"><%=student.getSno()%></a></td> <td><%=student.getSname() %></td> <td><%=student.getSage() %></td> <%-- Don't display all of them first. Click the student number and then display all the details <td><%=student.getSaddress() %></td>--%> <!-- You can delete each student's information record here Using hyperlinks, go to the deleted servlet, The parameter transmitted is the student number of this message. This message can be deleted by the student number ?Pass the student number behind sno,Continue calling getSno Methods obtain the student number of the student --> <td> <a href="DeleteStudentServlet?sno=<%=student.getSno()%>">delete</a> </td> <!-- After the deletion is successful, you need to query all students again servlet in If the deletion is successful, redirect to QueryAllStudentServlet this servlet in Then this servlet It will be forwarded here again after execution index Show all student information in --> </tr> <% } %> </table> <a href="add.jsp">newly added</a> </body> </html>
add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="js/jquery-1.8.3.js"></script> <script type="text/javascript"> $(document).ready(function(){ }); function check(){ //onsubmit: ruturn true the form is submitted normally, return false the form is not submitted var sno = $("#sno").val(); var sname = $("#sname").val(); var sage = $("#sage").val(); var saddress = $("#saddress").val(); if(sno < 0){ alert("Student number is incorrect, please re-enter") return false; } if(!(sname.length>1 && sanme.length<5)){ alert("Name must be in 2-10 position"); return false; } //if(){return false} return true; } </script> </head> <body> <!-- add to submit Event, verification form --> <form action = "AddstudentServlet" method="post" οnsubmit="return check()"> Student number:<input type="text" name="sno" id="sno"><br> full name:<input type="text" name="sname" id="sname"/><br> Age:<input type="text" name="sage" id="sage"/><br> Address:<input type="text" name="saddress" id="saddress"><br> <input type="submit" value="newly added"/><br> </form> <a href="QueryAllStudentServlet">return</a> </body> </html>
studentInfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="entity.Student" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% //Get the data saved in the requset field first Student student = (Student)request.getAttribute("student"); %> <!-- Use forms to display student information, so that you can directly add the function of modification In addition, the data forms that need to be submitted during modification are all available, so they can be submitted directly to UpdateStudentServlet In the middle, here again servlet Definition in: if the modification is successful Go directly to the one who inquires all student information servlet in --> <form action="UpdateStudentServlet"> <!-- Because it is modified through the student number, the student number is set to read-only: readonly="readonly"--> <!-- When reading, you need to pass name Read, so here name Write it down --> Student number:<input type="text" name="sno" value=<%=student.getSno() %> readonly="readonly"><br> full name:<input type="text" name="sname" value=<%=student.getSname() %>><br> Age:<input type="text" name="sage" value=<%=student.getSage() %>><br> Address:<input type="text" name="saddress" value=<%=student.getSaddress() %>><br> <!-- Add modification function --> <input type="submit" value="modify"> <a href="QueryAllStudentServlet">return</a> </form> </body> </html>
Three layer optimization
Optimization diagram
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-cfbesm3w-1622360006662) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 19, three-tier optimization. png)]
-
Join the interface. It is suggested that interface oriented development: interface first, and then implement class
-service,dao Join interface Naming specification of interface and implementation classes Interface(interface): I Entity class+Package name format: I Implementation class Service Package of interface: xxx.service,xx.dao Example: IStudentService,IStudentDao Implementation class(implements): Entity class+Package name Impl Format: entity class ServiceImpl Package of implementation class: xx.service.impl,xx.dao.impl Example: StudentServiceImpl,StudentDaoImpl Future writing: use polymorphism //Interface xx = new implementation class (); IStudentDao studentDao = new StudentDaoImpl(); IStudentService studentService = new StudentServiceImpl();
-
DBUtil's general database help class can simplify the amount of code in Dao layer. General suggestions for help are written in: XX Util package
A{ a(){ B.connection } } B{ static Connection connection =.. b{ } } Method Refactoring: extract the common code of multiple methods, write it separately in a method, and then introduce the method a(){ .. c(); .. } b(){ .. c(); .. } c(){ [ .. ] }
-
Difference between DBUtil and DBUtil
dao Is a database operation class that handles specific classes: DBUtil Is a general database operation class
-
Optimized project:
Entity class: Student
package entity; public class Student { private int sno; private String sname; private int sage; private String saddress; public Student() { } public Student(String sname, int sage, String saddress) { this.sname = sname; this.sage = sage; this.saddress = saddress; } public Student(int sno, String sname, int sage, String saddress) { this.sno = sno; this.sname = sname; this.sage = sage; this.saddress = saddress; } public int getSno() { return sno; } public void setSno(int sno) { this.sno = sno; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public int getSage() { return sage; } public void setSage(int sage) { this.sage = sage; } public String getSaddress() { return saddress; } public void setSaddress(String saddress) { this.saddress = saddress; } @Override public String toString() { return "Student [sno=" + sno + ", sname=" + sname + ", sage=" + sage + ", saddress=" + saddress + "]"; } }
DBUtil tool class
package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import entity.Student; //General database operation method public class DBUtil { //Defined separately, it can be applied to multiple methods private static final String URL = "jdbc:mysql://localhost:3306/datas"; private static final String USERNAME = "root"; private static final String PASSWORD = "1051976202"; public static Connection conn = null; public static PreparedStatement ps = null; public static ResultSet rs = null; //Get database connection public static Connection getConnection() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.cj.jdbc.Driver"); return DriverManager.getConnection(URL,USERNAME,PASSWORD); } //Pass values to parameters public static PreparedStatement createPreapredStatement(String sql,Object[] params) throws ClassNotFoundException, SQLException { ps =getConnection().prepareStatement(sql); if(params != null) {//If the collection is empty, the value transfer operation will not be performed for(int i=0;i<params.length;i++) { //i+1 indicates to? The first value of is passed to the first value of the array, that is, the element with subscript 0 ps.setObject(i+1,params[i]); } } return ps; } //Method of closing connection public static void closeAll(ResultSet rs ,Statement stmt ,Connection connection) { if(rs != null) { try { rs.close(); }catch(SQLException e) { e.printStackTrace(); } } if(ps != null) { try { ps.close(); }catch(SQLException e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); }catch(SQLException e) { e.printStackTrace(); } } } //General database addition, deletion and modification public static boolean executeUpdate(String sql,Object[] params) { boolean flag = false; try { //Get database connection using method // Class.forName("com.mysql.cj.jdbc.Driver"); // conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); //Object obs = {name,age,x,...,xx}; For delivery? Value of //String sql = " update student set name=?,age=?,x=? where xx=? "; // ps =getConnection().prepareStatement(sql); //ps.setInt(1, sno); //The number of setXxx() methods is the same as that of? The number of has been,? The number of params is actually the number of params in the array //The number of setXxx() methods is consistent with the number of array params // If (params! = null) {/ / if the collection is empty, no value transfer operation will be performed // for(int i=0;i<params.length;i++) { // //i+1 indicates to? The first value of is passed to the first value of the array, that is, the element with subscript 0 // ps.setObject(i+1,params[i]); // } // } ps = createPreapredStatement(sql,params); int count = ps.executeUpdate(); if(count==1) { flag = true; } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { closeAll(null,ps,conn); // if(ps != null) { // try { // ps.close(); // }catch(SQLException e) { // e.printStackTrace(); // } // } // if(conn != null) { // try { // conn.close(); // }catch(SQLException e) { // e.printStackTrace(); // } // } } return flag; } //General query: the return value is a set (student, list < student >, null > //Because of decoupling, the collection of student objects cannot be returned, but the object of ResultSet type should be returned public static ResultSet executeQuery(String sql,Object[] params) { try { // Class.forName("com.mysql.cj.jdbc.Driver"); // conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); //String sql = "select * from student"; String ename,job from xx where... // ps =getConnection().prepareStatement(sql);// precompile //If so? Then pass value // If (params! = null) {/ / if the collection is empty, no value transfer operation will be performed // for(int i=0;i<params.length;i++) { // ps.setObject(i+1, rs); // } // } ps = createPreapredStatement(sql,params); rs = ps.executeQuery(); //implement //To be common to all queries, you need to remove the coupled code /* * //Use a loop to put the student object into the collection while (rs.next()) {int no = rs.getint ("SnO"); string name= * rs.getString("sname"); int age = rs.getInt("sage"); String address = * rs.getString("saddress"); //Encapsulated data student = new Student(no,name,age,address); * //Put the object into the collection students add(student); } */ } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } //Because rs wants to return, it cannot be closed at last /* * finally { if(rs != null) { try { rs.close(); }catch(SQLException e) { * e.printStackTrace(); } } if(ps != null) { try { ps.close(); * }catch(SQLException e) { e.printStackTrace(); } } if(conn != null) { try { * conn.close(); }catch(SQLException e) { e.printStackTrace(); } } } */ //Because of decoupling, the collection of student objects cannot be returned, but the object of ResultSet type should be returned //return students; return rs; } }
IStudentDao.java interface
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import entity.Student; public interface IStudentDao { public boolean addStudent(Student student); //Delete students according to student number public boolean deleteStudentBySno(int sno); /** * Modify student information according to student number * @param sno Pass in the student number of the student to be modified * @param student This is the information of the student to be modified */ public boolean updateStudentBySno(int sno,Student student); //Judge whether there is a student according to the student number public boolean isExist(int sno); //Query students according to student number public Student queryStudentBysno(int sno); //Query all students (many) public List<Student> queryAllStudents(); }
StudentDao implementation class
package dao.impl; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import dao.IStudentDao; import entity.Student; import util.DBUtil; //Data access layer: addition, deletion, modification and query of atomic layer public class StudentDaoImpl implements IStudentDao{ //Defined separately, it can be applied to multiple methods private final String URL = "jdbc:mysql://localhost:3306/datas"; private final String USERNAME = "root"; private final String PASSWORD = "1051976202"; //Add students according to student number /* * public boolean addStudent(Student student) { * * boolean flag = false; Connection conn = null; PreparedStatement ps = null; * try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = * DriverManager.getConnection(URL,USERNAME,PASSWORD); //Add student String sql= * "insert into student(sno,sname,sage,saddress) values(?,?,?,?) "; ps * =conn.prepareStatement(sql);//Precompiled / / as? Pass the value ps.setInt(1,student.getSno()); * ps.setString(2,student.getSname()); ps.setInt(3,student.getSage()); * ps.setString(4, student.getSaddress()); //Returns the number of successful inserts int count= * ps.executeUpdate(); //If the number of successful entries is 1, the addition is successful. if(count==1) { flag = true; } } catch * (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { * e.printStackTrace(); }finally {//Close resource if (PS! = null) {try {ps.close(); * }catch(SQLException e) { e.printStackTrace(); } } if(conn != null) { try { * conn.close(); }catch(SQLException e) { e.printStackTrace(); } } } return * flag; } */ //Use tool classes to simplify code public boolean addStudent(Student student) { String sql = "insert into student(sno,sname,sage,saddress) values(?,?,?,?) "; Object[] params = {student.getSno(),student.getSname(),student.getSage(),student.getSaddress()}; return DBUtil.executeUpdate(sql, params); } //Delete students according to student number // public boolean deleteStudentBySno(int sno) { // boolean flag = false; // Connection conn = null; // PreparedStatement ps = null; // try { // Class.forName("com.mysql.cj.jdbc.Driver"); // conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); // // String sql = "delete from student where sno=? "; // ps =conn.prepareStatement(sql); // ps.setInt(1, sno); // int count = ps.executeUpdate(); // if(count==1) { // flag = true; // } // // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } catch (SQLException e) { // e.printStackTrace(); // }finally { // if(ps != null) { // try { // ps.close(); // }catch(SQLException e) { // e.printStackTrace(); // } // } // if(conn != null) { // try { // conn.close(); // }catch(SQLException e) { // e.printStackTrace(); // } // } // } // return flag; // } //Use tool classes to simplify code public boolean deleteStudentBySno(int sno) { String sql = "delete from student where sno=? "; Object[] params = {sno}; return DBUtil.executeUpdate(sql, params); } /** * Modify student information according to student number * @param sno Pass in the student number of the student to be modified * @param student This is the information of the student to be modified */ /* * public boolean updateStudentBySno(int sno,Student student) { boolean flag = * false; Connection conn = null; PreparedStatement ps = null; try { * Class.forName("com.mysql.cj.jdbc.Driver"); conn = * DriverManager.getConnection(URL,USERNAME,PASSWORD); //Modify String sql= * "update student set sname=?,sage=?,saddress=? where sno=? "; ps * =conn.prepareStatement(sql);//Precompiled / / as? Pass the value / / what needs to be modified * ps.setString(1,student.getSname()); ps.setInt(2,student.getSage()); * ps.setString(3, student.getSaddress()); //Modify who's ps.setInt(4,sno); * //Returns the number of successful inserts. int count = ps.executeUpdate()// If the number of successful entries is 1, the addition is successful. if(count==1) * { flag = true; } } catch (ClassNotFoundException e) { e.printStackTrace(); } * catch (SQLException e) { e.printStackTrace(); }finally {//Close resource if (PS! = null) * { try { ps.close(); }catch(SQLException e) { e.printStackTrace(); } } if(conn * != null) { try { conn.close(); }catch(SQLException e) { e.printStackTrace(); * } } } return flag; } */ //Use tool classes to simplify code public boolean updateStudentBySno(int sno,Student student) { String sql = "update student set sname=?,sage=?,saddress=? where sno=? "; Object[] params = {student.getSname(),student.getSage(),student.getSaddress(),sno}; return DBUtil.executeUpdate(sql, params); } //Judge whether there is a student according to the student number public boolean isExist(int sno) { //Call the method of querying students according to student number. If it is blank, the student does not exist; otherwise, the student exists. return queryStudentBysno(sno)==null?false:true; } //Query students according to student number public Student queryStudentBysno(int sno) { //New student object Student student = null; //Connect database Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); String sql = "select * from student where sno=? "; ps =conn.prepareStatement(sql); ps.setInt(1,sno); rs = ps.executeQuery(); //Return if there is data if(rs.next()) { int no = rs.getInt("sno"); String name = rs.getString("sname"); int age = rs.getInt("sage"); String address = rs.getString("saddress"); //Encapsulate data student = new Student(no,name,age,address); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { if(rs != null) { try { rs.close(); }catch(SQLException e) { e.printStackTrace(); } } if(ps != null) { try { ps.close(); }catch(SQLException e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); }catch(SQLException e) { e.printStackTrace(); } } } return student; } //Query all students (many) /* * public List<Student> queryAllStudents() { //Create a collection to store student information list < student > * students = new ArrayList<>(); //New student object student = null// Connect database * Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try * { Class.forName("com.mysql.cj.jdbc.Driver"); conn = * DriverManager.getConnection(URL,USERNAME,PASSWORD); String sql = * "select * from student"; ps =conn.prepareStatement(sql);//Precompiled rs= * ps.executeQuery(); //Execute / / use the loop to put the student object into the collection while (rs.next()) {int no= * rs.getInt("sno"); String name = rs.getString("sname"); int age = * rs.getInt("sage"); String address = rs.getString("saddress"); //Encapsulated data student * = new Student(no,name,age,address); //Put the object into the collection students add(student); } * * } catch (ClassNotFoundException e) { e.printStackTrace(); } catch * (SQLException e) { e.printStackTrace(); }finally { if(rs != null) { try { * rs.close(); }catch(SQLException e) { e.printStackTrace(); } } if(ps != null) * { try { ps.close(); }catch(SQLException e) { e.printStackTrace(); } } if(conn * != null) { try { conn.close(); }catch(SQLException e) { e.printStackTrace(); * } } } return students; } */ //simplify public List<Student> queryAllStudents() { //Create a collection to store student information List<Student> students = new ArrayList<>(); //New student object Student student = null; //Connect database ResultSet rs = null; try { String sql = "select * from student"; rs = DBUtil.executeQuery(sql, null); //Use loops to put student objects into a collection while(rs.next()) { int no = rs.getInt("sno"); String name = rs.getString("sname"); int age = rs.getInt("sage"); String address = rs.getString("saddress"); //Encapsulate data student = new Student(no,name,age,address); //Put objects into collection students.add(student); } }catch (SQLException e) { e.printStackTrace(); }finally { DBUtil.closeAll(rs,DBUtil.ps,DBUtil.conn); // if(rs != null) { // try { // rs.close(); // }catch(SQLException e) { // e.printStackTrace(); // } // } // if(DBUtil.ps != null) { // try { // DBUtil.ps.close(); // }catch(SQLException e) { // e.printStackTrace(); // } // } // if(DBUtil.conn != null) { // try { // DBUtil.conn.close(); // }catch(SQLException e) { // e.printStackTrace(); // } // } } return students; } }
IStudentService interface
package service; import java.util.List; import entity.Student; public interface IStudentService { //Method of adding (add: query + add) public boolean addStudent(Student student); //Deletion method public boolean deleteStudentBySno(int sno); //Method of change public boolean updateStudentBySno(int sno,Student student); //Check students according to student number public Student queryStudentBySno(int sno); //Query all students public List<Student> queryAllStudents(); }
StudentService implementation class
package service.impl; import java.util.List; import dao.IStudentDao; import dao.impl.StudentDaoImpl; import entity.Student; import service.IStudentService; //Business logic layer: add, delete, modify and check logically, and assemble dao layer public class StudentServiceImpl implements IStudentService{ //Create a StudentDao object to assemble //Interface xx = new implementation class (); IStudentDao studentDao = new StudentDaoImpl(); //Method of adding (add: query + add) public boolean addStudent(Student student) { //First judge whether it exists, and then add if it exists if(!studentDao.isExist(student.getSno())) { //If the student does not exist, add the student. /*studentDao.addStudent(student); flag = true; */ //The addStudent method that is merged and called directly returns a Boolean value. Just return return studentDao.addStudent(student); } return false; } //Deletion method public boolean deleteStudentBySno(int sno) { //First judge whether this person exists, and delete it if it exists if(studentDao.isExist(sno)) { return studentDao.deleteStudentBySno(sno); } return false; } //Method of change public boolean updateStudentBySno(int sno,Student student) { if(studentDao.isExist(sno)) { return studentDao.updateStudentBySno(sno, student); } return false; } //Check students according to student number public Student queryStudentBySno(int sno) { return studentDao.queryStudentBysno(sno); } //Query all students public List<Student> queryAllStudents(){ return studentDao.queryAllStudents(); } }
AddServlet
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.Student; import service.IStudentService; import service.impl.StudentServiceImpl; //Add student Servlet public class AddstudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Sets the encoding type of the request request.setCharacterEncoding("utf-8"); //Receive add JSP user input int no = Integer.parseInt(request.getParameter("sno")); String name = request.getParameter("sname"); int age = Integer.parseInt(request.getParameter("sage")); String address = request.getParameter("saddress"); //Encapsulate this data into a Student object Student student = new Student(no,name,age,address); //Create a service object to call the function of adding students //Use polymorphic interface: xx = new implementation class IStudentService studentService = new StudentServiceImpl(); //Add student boolean isAddSuccess = studentService.addStudent(student); /* * jsp Built in objects: out, request, session, application * In the servlet, these built-in objects can be obtained as follows: * out: PrintWriter out = response.getWriter(); * session: request.getSession(); * application: request.getServletContext(); */ //Set the encoding type when responding response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("utf-8"); //Respond after setting the encoding type //Get out object in servlet PrintWriter out = response.getWriter(); //Phase I // if(isAddSuccess) { // //If the addition is successful, re query all students // out.print("increase succeeded"); // }else { // out.println("add failed"); // } //Phase II // if(isAddSuccess) { // //If the addition is successful, re query all students // //out.print("increase succeeded"); // response.sendRedirect("QueryAllStudentServlet"); // }else { // out.println("add failed"); // } //Stage 3: new tips //Pass a value to the request field if(isAddSuccess) { request.setAttribute("isSuccess","Increase success"); }else{ request.setAttribute("isSuccess","Add failed"); } //In any case, go to the all student information interface //Because data needs to be transmitted, the method of request forwarding is used request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
DeleteServlet
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import service.IStudentService; import service.impl.StudentServiceImpl; //Delete student's Servlet public class DeleteStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Sets the encoding type of the request request.setCharacterEncoding("utf-8"); //Accept the student number from the front end int no = Integer.parseInt(request.getParameter("sno")); //Create a new Service object //Use polymorphic interface: xx = new implementation class IStudentService service = new StudentServiceImpl(); //Call the method to delete the student boolean isDeleteSuccess = service.deleteStudentBySno(no); //Set the encoding type when responding response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("utf-8"); //Phase I // if(isDeleteSuccess) { // //Get out object in servlet // /*PrintWriter out = response.getWriter(); // out.print("");*/ // //Merge // response.getWriter().print("deletion succeeded"); // }else { // response.getWriter().print("deletion failed"); // } //Phase II // if(isDeleteSuccess) { // //After the deletion is successful, re query all student information, namely: // //Redirect to QueryAllStudentServlet // response.sendRedirect("QueryAllStudentServlet"); // }else { // response.getWriter().print("deletion failed"); // } //Stage 3: add or delete prompt information if(isDeleteSuccess) { request.setAttribute("isSuccess","Deleted successfully"); }else{ request.setAttribute("isSuccess","Delete failed"); } //In any case, go to the all student information interface //Because data needs to be transmitted, the method of request forwarding is used request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
QueryAllServlet
package servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.Student; import service.IStudentService; import service.impl.StudentServiceImpl; //Query all students public class QueryAllStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //Call service logic //Use polymorphic interface: xx = new implementation class IStudentService service = new StudentServiceImpl(); //Call the method to query all students List<Student> students = service.queryAllStudents(); //Save data request.setAttribute("students",students); //Because there is data in the request, you need to jump through request forwarding (redirection will lose the request field) //Although using the session object, redirection and forwarding will not lose data, but the session consumes more resources //Ranking of resources: pagecontext (valid for the same page) < request (valid for the same time)< //< session < application request.getRequestDispatcher("index.jsp").forward(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
QueryBySnoServlet
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.Student; import service.IStudentService; import service.impl.StudentServiceImpl; //Query students by student number public class QueryStudentBySnoServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); int no = Integer.parseInt(request.getParameter("sno")); //Use polymorphic interface: xx = new implementation class IStudentService service = new StudentServiceImpl(); Student student = service.queryStudentBySno(no); //System.out.println(student); //When querying all the information of the student, display the student through the JSP on the front desk: studentinfo jsp //Save the student's information to the reuqest field first request.setAttribute("student",student); //If there is no data in the request field, use redirect response sendRedirect(); //If there is data in the request field, use the method of request forwarding request.getRequestDispatcher("studentInfo.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
UpdateServlet
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.Student; import service.IStudentService; import service.impl.StudentServiceImpl; //Methods of modifying student information public class UpdateStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Sets the encoding type of the request request.setCharacterEncoding("utf-8"); //Obtain the student number of the student to be modified int no = Integer.parseInt(request.getParameter("sno")); //Get the content that needs to be modified and encapsulate it into an entity class (java bean) String name = request.getParameter("sname"); int age = Integer.parseInt(request.getParameter("sage")); String address = request.getParameter("saddress"); //Encapsulate the modified content into Student Student student = new Student(name,age,address); //Create a new Service object //Use polymorphic interface: xx = new implementation class IStudentService service = new StudentServiceImpl(); //Call student's method boolean isUpdateSuccess = service.updateStudentBySno(no, student); //Set the encoding type when responding response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("utf-8"); //Phase I // if(isUpdateSuccess) { // //response.getWriter().print("modified successfully"); // }else { // response.getWriter().print("modification failed"); // } //Phase II // if(isUpdateSuccess) { // //After the modification is successful, re query all student information, that is, redirect to QueryAllStudentServlet // response.sendRedirect("QueryAllStudentServlet"); // }else { // response.getWriter().print("modification failed"); // } if(isUpdateSuccess) { request.setAttribute("isSuccess","Modified successfully"); }else{ request.setAttribute("isSuccess","Modification failed"); } //In any case, go to the all student information interface //Because data needs to be transmitted, the method of request forwarding is used request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
add.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="js/jquery-1.8.3.js"></script> <script type="text/javascript"> $(document).ready(function(){ }); function check(){ //onsubmit: ruturn true the form is submitted normally, return false the form is not submitted var sno = $("#sno").val(); var sname = $("#sname").val(); var sage = $("#sage").val(); var saddress = $("#saddress").val(); if(sno < 0){ alert("Student number is incorrect, please re-enter") return false; } if(!(sname.length>1 && sanme.length<5)){ alert("Name must be in 2-10 position"); return false; } //if(){return false} return true; } </script> </head> <body> <!-- add to submit Event, verification form --> <form action = "AddstudentServlet" method="post" οnsubmit="return check()"> Student number:<input type="text" name="sno" id="sno"><br> full name:<input type="text" name="sname" id="sname"/><br> Age:<input type="text" name="sage" id="sage"/><br> Address:<input type="text" name="saddress" id="saddress"><br> <input type="submit" value="newly added"/><br> </form> <a href="QueryAllStudentServlet">return</a> </body> </html>
studentInfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="entity.Student" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% //Get the data saved in the requset field first Student student = (Student)request.getAttribute("student"); %> <!-- Use forms to display student information, so that you can directly add the function of modification In addition, the data forms that need to be submitted during modification are all available, so they can be submitted directly to UpdateStudentServlet In the middle, here again servlet Definition in: if the modification is successful Go directly to the one who inquires all student information servlet in --> <form action="UpdateStudentServlet"> <!-- Because it is modified through the student number, the student number is set to read-only: readonly="readonly"--> <!-- When reading, you need to pass name Read, so here name Write it down --> Student number:<input type="text" name="sno" value=<%=student.getSno() %> readonly="readonly"><br> full name:<input type="text" name="sname" value=<%=student.getSname() %>><br> Age:<input type="text" name="sage" value=<%=student.getSage() %>><br> Address:<input type="text" name="saddress" value=<%=student.getSaddress() %>><br> <!-- Add modification function --> <input type="submit" value="modify"> <a href="QueryAllStudentServlet">return</a> </form> </body> </html>
index.jsp
<%@page import="java.util.List"%> <%@page import="entity.Student" %> <%@page import="java.lang.String" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <script type="text/javascript" src="js/jquery-1.8.3.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("tr:odd").css("background-color","lightgray"); }); </script> <meta charset="UTF-8"> <title>Student information</title> </head> <body> <!-- When you're here, you have to do it first QueryAllStudentServlet because index This is needed in the servlet Return data, otherwise index Just execute it null So put QueryAllStudentServlet Put on web.xml First in<welcome-file> In the label, server This will be executed after startup servlet,Then jump to by forwarding Should index in --> <!-- Problems needing attention during running: you cannot right-click to run on this page, - Right click in the project list to run - Or in QueryAllStudentServlet Right click Run --> <!-- Phase III: each increase/modify/Prompt whether the deletion is successful or not --> <% //Get the prompt to judge whether it is successful String success =(String)request.getAttribute("isSuccess"); /* "".equals()Can avoid null pointers If you simply show whether the operation is successful, you can use this method to subtract the judgment of null pointer After adding / deleting / modifying successfully, pass in yes and vice versa: no if("yes".equals(success)){ out.print("Operation succeeded "); }else if("no".equals(success)){ out.print("Operation failed ''); } */ //Use the method of intercepting string to judge //(Master) The String substring(int beginIndex) parameter is the starting subscript intercepted string //System.out.println("http://www.baidu.com".substring(7)); //www.baidu.com //(Master) String substring(int beginIndex,int endIndex) intercepts some strings //beginIndex start position (including) endIndex end position (excluding) //System.out.println("http://www.baidu.com".substring(7,10)); //www /* if(success != null){ if("Success ". equals(success.substring(2))){ out.print(success); }else if("Failed ". equals(success.substring(2))){ out.print(success); } } */ //Two other methods: //(Master) boolean contains(CharSequence s) //Judge whether the previous string contains the following string, including: return true, excluding: return false //Here, success. Is called at the bottom of contains ToString () method, so null pointers should also be processed here. If they are not null, they can be executed again /* if(success != null){ if("Added successfully deleted successfully modified successfully ". contains(success)){ out.print(success); }else if("Adding failed deleting failed modifying failed ". contains(success)){ out.print(success); } } */ //(Master) boolean endsWith(String suffix) //Determines whether the current string ends with a string if(success != null){ if(success.endsWith("success")){ out.print(success); }else if(success.endsWith("fail")){ out.print(success); } } %> <table border="1px"> <tr> <th>Student number</th> <th>full name</th> <th>Age</th> <!-- <th>address</th> --> <th>operation</th> </tr> <% //Use getAttribute to get the data in the requset field //Because the return value of this method is of type Object, cast is used List<Student> students = (List<Student>)request.getAttribute("students"); //Traverse the data in the output set for(Student student:students){ //One person's data is output in each cycle, which is separated by java code blocks %> <!-- Intermediate use java Expression to get --> <tr> <!-- Click the student number to display all the information of the student --> <td><a href="QueryStudentBySnoServlet?sno=<%=student.getSno()%>"><%=student.getSno()%></a></td> <td><%=student.getSname() %></td> <td><%=student.getSage() %></td> <%-- Don't display all of them first. Click the student number and then display all the details <td><%=student.getSaddress() %></td>--%> <!-- You can delete each student's information record here Using hyperlinks, go to the deleted servlet, The parameter transmitted is the student number of this message. This message can be deleted by the student number ?Pass the student number behind sno,Continue calling getSno Methods obtain the student number of the student --> <td> <a href="DeleteStudentServlet?sno=<%=student.getSno()%>">delete</a> </td> <!-- After the deletion is successful, you need to query all students again servlet in If the deletion is successful, redirect to QueryAllStudentServlet this servlet in Then this servlet It will be forwarded here again after execution index Show all student information in --> </tr> <% } %> </table> <a href="add.jsp">newly added</a> </body> </html>
Database Paging
web debugging
And java Code debugging differences: different startup methods stay servers In the window tomcat Right click up—— debug index.jsp compile-> index_jsp.java compile->index_jsp.class jsp file ->java file->class file jsp Translated into Java And compiled class File exists in tomcat Medium work In the directory
-
Paging database
1,MySQL Pagination of MySQL: Count from 0 The first n page start end ---------------------------------------------- 0 Article 0 data Article 9 data 1 Article 10 data Article 19 data 2 Article 20 data Article 29 data ... ..... ...... n The first n*10 Data bar The first(n+1)*10-1 Data bar MySQL Realize paging sql: limit From which article,How many; Page 0: select * from student limit 0,10; Page 1: select * from student limit 10,10; Page 2: select * from student limit 20,10; Page 3: select * from student limit 30,10; MySQL Pagination statement: select * from student limit n*10,10; select * from student limit the number of pages*Page size; 2, SQLServser/Oracle : The number of data pieces is counted from 1 The first n page start end ---------------------------------------------- 1 Article 1 data Article 10 data 2 Article 11 data Article 20 data 3 Article 21 Data Article 30 data ... ..... ...... n The first(n-1)*10+1 Data bar The first n*10 Data bar Pseudo column: SELECT @rownum:=@rownum+1 AS rownum, s.* FROM (SELECT @rownum:=0) r,student s SELECT @rownum:=@rownum+1 AS rownum, s.* FROM (SELECT @rownum:=0) r,student s where sno>=(n-1)*10+1 and son<=n*10; The premise of this writing method: it must be id The value is continuous and cannot be intermittent in the middle. Otherwise, it cannot meet the requirement of displaying 10 pieces of data per page select * from student where sno>=(the number of pages-1)*10+1 and sno<=the number of pages*10; Such paging SQL Strict dependence sno Data, once sno If there is a gap (crack), it cannot meet the requirements of 10 items per page Paging: 5 variables (properties) 1.Total data( select count(*) from xxx ,(check database) 2.Page size (page capacity, number of data displayed per page) ((user defined) 3.PageCount (Automatic calculation) 800:10= 80 page PageCount = Total data /Page size 802:10= 800/10 +1 ; PageCount = Total data /Page size + 1; -->General formula PageCount = Total data % Page size==0 ?Total data /Page size:Total data /Page size + 1; Note: timing of automatic calculation: when the total number of data and page size are assigned, the total number of pages will be calculated automatically. 4.Current page number (user defined) 5.Entity class object collection (data collection of the current page): dependent on the database (Check database) Assumption: 10 per page (page size)=10)
The database displays student information in pages (paging on the basis of 30% optimization)
Pagination diagram
[the external link image transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-5ecnoz7t-1622360006664) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 20, database paging. png)]
Student entity
package entity; public class Student { private int sno; private String sname; private int sage; private String saddress; public Student() { } public Student(String sname, int sage, String saddress) { this.sname = sname; this.sage = sage; this.saddress = saddress; } public Student(int sno, String sname, int sage, String saddress) { this.sno = sno; this.sname = sname; this.sage = sage; this.saddress = saddress; } public int getSno() { return sno; } public void setSno(int sno) { this.sno = sno; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public int getSage() { return sage; } public void setSage(int sage) { this.sage = sage; } public String getSaddress() { return saddress; } public void setSaddress(String saddress) { this.saddress = saddress; } @Override public String toString() { return "Student [sno=" + sno + ", sname=" + sname + ", sage=" + sage + ", saddress=" + saddress + "]"; } }
Page entity
package entity; import java.util.List; //Paging help class public class Page { // Current page: currentPage private int currentPage; // Page size: pageSize private int pageSize; // Total data: totalCount private int totalCount; // Total pages: totalPage private int totalPage; // Data collection of the current page: students private List<Student> students; //Construction method public Page() { } public Page(int currentPage, int pageSize, int totalCount, int totalPage, List<Student> students) { this.currentPage = currentPage; this.pageSize = pageSize; this.totalCount = totalCount; this.totalPage = totalPage; this.students = students; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getPageSize() { return pageSize; } /** * Total pages = total data% page size = = 0? Total data / page size: total data / page size + 1; * * When we call set() of the total number of data and set() of the page size, the total number of pages is calculated automatically * Pay attention to the order: first set the total number of data, and then set the page size, */ public void setPageSize(int pageSize) { this.pageSize = pageSize; //Automatically calculate the total number of pages //Total pages = total data% page size = = 0? Total data / page size: total data / page size + 1; this.totalPage = this.totalCount%this.pageSize==0?this.totalCount/this.pageSize:this.totalCount/this.pageSize+1; } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { this.totalCount = totalCount; } public int getTotalPage() { return totalPage; } //Assign a value to the total number of pages // public void setTotalPage(int totalPage) { // this.totalPage = totalPage; // } public List<Student> getStudents() { return students; } public void setStudents(List<Student> students) { this.students = students; } }
IStudentDao interface
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import entity.Student; public interface IStudentDao { public boolean addStudent(Student student); //Delete students according to student number public boolean deleteStudentBySno(int sno); /** * Modify student information according to student number * @param sno Pass in the student number of the student to be modified * @param student This is the information of the student to be modified */ public boolean updateStudentBySno(int sno,Student student); //Judge whether there is a student according to the student number public boolean isExist(int sno); //Query students according to student number public Student queryStudentBysno(int sno); //Query all students (many) public List<Student> queryAllStudents(); //Method of querying the total number of data public int getTotalCount(); /** * Query a page of student data and return the students on this page in the form of array * @param currentPage : Current page (page number) * @param pageSize : Page size (number of data pieces displayed per page) * @return */ public List<Student> queryStudentsByPage(int currentPage,int pageSize); }
Dataimpl class implementation
package dao.impl; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import dao.IStudentDao; import entity.Student; import util.DBUtil; //Data access layer: addition, deletion, modification and query of atomic layer public class StudentDaoImpl implements IStudentDao{ //Defined separately, it can be applied to multiple methods private final String URL = "jdbc:mysql://localhost:3306/datas"; private final String USERNAME = "root"; private final String PASSWORD = "1051976202"; //Add students according to student number /* * public boolean addStudent(Student student) { * * boolean flag = false; Connection conn = null; PreparedStatement ps = null; * try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = * DriverManager.getConnection(URL,USERNAME,PASSWORD); //Add student String sql= * "insert into student(sno,sname,sage,saddress) values(?,?,?,?) "; ps * =conn.prepareStatement(sql);//Precompiled / / as? Pass the value ps.setInt(1,student.getSno()); * ps.setString(2,student.getSname()); ps.setInt(3,student.getSage()); * ps.setString(4, student.getSaddress()); //Returns the number of successful inserts int count= * ps.executeUpdate(); //If the number of successful entries is 1, the addition is successful. if(count==1) { flag = true; } } catch * (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { * e.printStackTrace(); }finally {//Close resource if (PS! = null) {try {ps.close(); * }catch(SQLException e) { e.printStackTrace(); } } if(conn != null) { try { * conn.close(); }catch(SQLException e) { e.printStackTrace(); } } } return * flag; } */ //Use tool classes to simplify code public boolean addStudent(Student student) { String sql = "insert into student(sno,sname,sage,saddress) values(?,?,?,?) "; Object[] params = {student.getSno(),student.getSname(),student.getSage(),student.getSaddress()}; return DBUtil.executeUpdate(sql, params); } //Delete students according to student number // public boolean deleteStudentBySno(int sno) { // boolean flag = false; // Connection conn = null; // PreparedStatement ps = null; // try { // Class.forName("com.mysql.cj.jdbc.Driver"); // conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); // // String sql = "delete from student where sno=? "; // ps =conn.prepareStatement(sql); // ps.setInt(1, sno); // int count = ps.executeUpdate(); // if(count==1) { // flag = true; // } // // } catch (ClassNotFoundException e) { // e.printStackTrace(); // } catch (SQLException e) { // e.printStackTrace(); // }finally { // if(ps != null) { // try { // ps.close(); // }catch(SQLException e) { // e.printStackTrace(); // } // } // if(conn != null) { // try { // conn.close(); // }catch(SQLException e) { // e.printStackTrace(); // } // } // } // return flag; // } //Use tool classes to simplify code public boolean deleteStudentBySno(int sno) { String sql = "delete from student where sno=? "; Object[] params = {sno}; return DBUtil.executeUpdate(sql, params); } /** * Modify student information according to student number * @param sno Pass in the student number of the student to be modified * @param student This is the information of the student to be modified */ /* * public boolean updateStudentBySno(int sno,Student student) { boolean flag = * false; Connection conn = null; PreparedStatement ps = null; try { * Class.forName("com.mysql.cj.jdbc.Driver"); conn = * DriverManager.getConnection(URL,USERNAME,PASSWORD); //Modify String sql= * "update student set sname=?,sage=?,saddress=? where sno=? "; ps * =conn.prepareStatement(sql);//Precompiled / / as? Pass the value / / what needs to be modified * ps.setString(1,student.getSname()); ps.setInt(2,student.getSage()); * ps.setString(3, student.getSaddress()); //Modify who's ps.setInt(4,sno); * //Returns the number of successful inserts. int count = ps.executeUpdate()// If the number of successful entries is 1, the addition is successful. if(count==1) * { flag = true; } } catch (ClassNotFoundException e) { e.printStackTrace(); } * catch (SQLException e) { e.printStackTrace(); }finally {//Close resource if (PS! = null) * { try { ps.close(); }catch(SQLException e) { e.printStackTrace(); } } if(conn * != null) { try { conn.close(); }catch(SQLException e) { e.printStackTrace(); * } } } return flag; } */ //Use tool classes to simplify code public boolean updateStudentBySno(int sno,Student student) { String sql = "update student set sname=?,sage=?,saddress=? where sno=? "; Object[] params = {student.getSname(),student.getSage(),student.getSaddress(),sno}; return DBUtil.executeUpdate(sql, params); } //Judge whether there is a student according to the student number public boolean isExist(int sno) { //Call the method of querying students according to student number. If it is blank, the student does not exist; otherwise, the student exists. return queryStudentBysno(sno)==null?false:true; } //Query students according to student number public Student queryStudentBysno(int sno) { //New student object Student student = null; //Connect database Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { Class.forName("com.mysql.cj.jdbc.Driver"); conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); String sql = "select * from student where sno=? "; ps =conn.prepareStatement(sql); ps.setInt(1,sno); rs = ps.executeQuery(); //Return if there is data if(rs.next()) { int no = rs.getInt("sno"); String name = rs.getString("sname"); int age = rs.getInt("sage"); String address = rs.getString("saddress"); //Encapsulate data student = new Student(no,name,age,address); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { if(rs != null) { try { rs.close(); }catch(SQLException e) { e.printStackTrace(); } } if(ps != null) { try { ps.close(); }catch(SQLException e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); }catch(SQLException e) { e.printStackTrace(); } } } return student; } //Query all students (many) /* * public List<Student> queryAllStudents() { //Create a collection to store student information list < student > * students = new ArrayList<>(); //New student object student = null// Connect database * Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try * { Class.forName("com.mysql.cj.jdbc.Driver"); conn = * DriverManager.getConnection(URL,USERNAME,PASSWORD); String sql = * "select * from student"; ps =conn.prepareStatement(sql);//Precompiled rs= * ps.executeQuery(); //Execute / / use the loop to put the student object into the collection while (rs.next()) {int no= * rs.getInt("sno"); String name = rs.getString("sname"); int age = * rs.getInt("sage"); String address = rs.getString("saddress"); //Encapsulated data student * = new Student(no,name,age,address); //Put the object into the collection students add(student); } * * } catch (ClassNotFoundException e) { e.printStackTrace(); } catch * (SQLException e) { e.printStackTrace(); }finally { if(rs != null) { try { * rs.close(); }catch(SQLException e) { e.printStackTrace(); } } if(ps != null) * { try { ps.close(); }catch(SQLException e) { e.printStackTrace(); } } if(conn * != null) { try { conn.close(); }catch(SQLException e) { e.printStackTrace(); * } } } return students; } */ //simplify public List<Student> queryAllStudents() { //Create a collection to store student information List<Student> students = new ArrayList<>(); //New student object Student student = null; //Connect database ResultSet rs = null; try { String sql = "select * from student"; rs = DBUtil.executeQuery(sql, null); //Use loops to put student objects into a collection while(rs.next()) { int no = rs.getInt("sno"); String name = rs.getString("sname"); int age = rs.getInt("sage"); String address = rs.getString("saddress"); //Encapsulate data student = new Student(no,name,age,address); //Put objects into collection students.add(student); } }catch (SQLException e) { e.printStackTrace(); }finally { DBUtil.closeAll(rs,DBUtil.ps,DBUtil.conn); // if(rs != null) { // try { // rs.close(); // }catch(SQLException e) { // e.printStackTrace(); // } // } // if(DBUtil.ps != null) { // try { // DBUtil.ps.close(); // }catch(SQLException e) { // e.printStackTrace(); // } // } // if(DBUtil.conn != null) { // try { // DBUtil.conn.close(); // }catch(SQLException e) { // e.printStackTrace(); // } // } } return students; } //Total data queried @Override public int getTotalCount() { String sql = "select count(1) from student"; return DBUtil.getTotalCount(sql); } //Paging query data @Override public List<Student> queryStudentsByPage(int currentPage, int pageSize) { //Paging sql statement String sql = "select * from student limit ?,?"; //Pass in array? Value of Object[] params = {currentPage*pageSize,pageSize}; //Create a collection to receive data List<Student> students = new ArrayList<>(); //Call method to query data ResultSet rs = DBUtil.executeQuery(sql,params); try { while(rs.next()) { //Create a new student object and get the value through the get method Student student =new Student(rs.getInt("sno"),rs.getString("sname"),rs.getInt("sage"),rs.getString("Saddress")); //Add the object to the collection students.add(student); } } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return students; } }
IStudentService interface
package service; import java.util.List; import entity.Student; public interface IStudentService { //Method of adding (add: query + add) public boolean addStudent(Student student); //Deletion method public boolean deleteStudentBySno(int sno); //Method of change public boolean updateStudentBySno(int sno,Student student); //Check students according to student number public Student queryStudentBySno(int sno); //Query all students public List<Student> queryAllStudents(); //Total number of query data public int getTotalCount(); //Paging query data public List<Student> queryStudentsByPage(int currentPage,int pageSize); }
StudentServiceImpl implementation class
package service.impl; import java.util.List; import dao.IStudentDao; import dao.impl.StudentDaoImpl; import entity.Student; import service.IStudentService; //Business logic layer: add, delete, modify and check logically, and assemble dao layer public class StudentServiceImpl implements IStudentService{ //Create a StudentDao object to assemble //Interface xx = new implementation class (); IStudentDao studentDao = new StudentDaoImpl(); //Method of adding (add: query + add) public boolean addStudent(Student student) { //First judge whether it exists, and then add if it exists if(!studentDao.isExist(student.getSno())) { //If the student does not exist, add the student. /*studentDao.addStudent(student); flag = true; */ //The addStudent method that is merged and called directly returns a Boolean value. Just return return studentDao.addStudent(student); } return false; } //Deletion method public boolean deleteStudentBySno(int sno) { //First judge whether this person exists, and delete it if it exists if(studentDao.isExist(sno)) { return studentDao.deleteStudentBySno(sno); } return false; } //Method of change public boolean updateStudentBySno(int sno,Student student) { if(studentDao.isExist(sno)) { return studentDao.updateStudentBySno(sno, student); } return false; } //Check students according to student number public Student queryStudentBySno(int sno) { return studentDao.queryStudentBysno(sno); } //Query all students public List<Student> queryAllStudents(){ return studentDao.queryAllStudents(); } @Override public int getTotalCount() { return studentDao.getTotalCount(); } //Total number of query data @Override public List<Student> queryStudentsByPage(int currentPage, int pageSize) { return studentDao.queryStudentsByPage(currentPage, pageSize); } }
add
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.Student; import service.IStudentService; import service.impl.StudentServiceImpl; //Add student Servlet public class AddstudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Sets the encoding type of the request request.setCharacterEncoding("utf-8"); //Receive add JSP user input int no = Integer.parseInt(request.getParameter("sno")); String name = request.getParameter("sname"); int age = Integer.parseInt(request.getParameter("sage")); String address = request.getParameter("saddress"); //Encapsulate this data into a Student object Student student = new Student(no,name,age,address); //Create a service object to call the function of adding students //Use polymorphic interface: xx = new implementation class IStudentService studentService = new StudentServiceImpl(); //Add student boolean isAddSuccess = studentService.addStudent(student); /* * jsp Built in objects: out, request, session, application * In the servlet, these built-in objects can be obtained as follows: * out: PrintWriter out = response.getWriter(); * session: request.getSession(); * application: request.getServletContext(); */ //Set the encoding type when responding response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("utf-8"); //Respond after setting the encoding type //Get out object in servlet PrintWriter out = response.getWriter(); //Phase I // if(isAddSuccess) { // //If the addition is successful, re query all students // out.print("increase succeeded"); // }else { // out.println("add failed"); // } //Phase II // if(isAddSuccess) { // //If the addition is successful, re query all students // //out.print("increase succeeded"); // response.sendRedirect("QueryAllStudentServlet"); // }else { // out.println("add failed"); // } //Stage 3: new tips //Pass a value to the request field if(isAddSuccess) { request.setAttribute("isSuccess","Increase success"); }else{ request.setAttribute("isSuccess","Add failed"); } //In any case, go to the all student information interface //Because data needs to be transmitted, the method of request forwarding is used //request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response); //After querying the database in pages, if you add students, go to QueryStudentByPage request.getRequestDispatcher("QueryStudentByPage").forward(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
delete
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import service.IStudentService; import service.impl.StudentServiceImpl; //Delete student's Servlet public class DeleteStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Sets the encoding type of the request request.setCharacterEncoding("utf-8"); //Accept the student number from the front end int no = Integer.parseInt(request.getParameter("sno")); //Create a new Service object //Use polymorphic interface: xx = new implementation class IStudentService service = new StudentServiceImpl(); //Call the method to delete the student boolean isDeleteSuccess = service.deleteStudentBySno(no); //Set the encoding type when responding response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("utf-8"); //Phase I // if(isDeleteSuccess) { // //Get out object in servlet // /*PrintWriter out = response.getWriter(); // out.print("");*/ // //Merge // response.getWriter().print("deletion succeeded"); // }else { // response.getWriter().print("deletion failed"); // } //Phase II // if(isDeleteSuccess) { // //After the deletion is successful, re query all student information, namely: // //Redirect to QueryAllStudentServlet // response.sendRedirect("QueryAllStudentServlet"); // }else { // response.getWriter().print("deletion failed"); // } //Stage 3: add or delete prompt information if(isDeleteSuccess) { request.setAttribute("isSuccess","Deleted successfully"); }else{ request.setAttribute("isSuccess","Delete failed"); } //In any case, go to the all student information interface //Because data needs to be transmitted, the method of request forwarding is used //request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response); //After querying the database in pages, if you delete students, go to QueryStudentByPage request.getRequestDispatcher("QueryStudentByPage").forward(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
queryAll
package servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.Student; import service.IStudentService; import service.impl.StudentServiceImpl; //Query all students public class QueryAllStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); //Call service logic //Use polymorphic interface: xx = new implementation class IStudentService service = new StudentServiceImpl(); //Call the method to query all students List<Student> students = service.queryAllStudents(); //Save data request.setAttribute("students",students); //Because there is data in the request, you need to jump through request forwarding (redirection will lose the request field) //Although using the session object, redirection and forwarding will not lose data, but the session consumes more resources //Ranking of resources: pagecontext (valid for the same page) < request (valid for the same time)< //< session < application //request.getRequestDispatcher("index.jsp").forward(request,response); //After querying the database in pages, the query students use the paging database to query. There is no need to jump. Note out the above line } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
queryStudentByPage paging
package servlet; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.Page; import entity.Student; import service.IStudentService; import service.impl.StudentServiceImpl; public class QueryStudentByPage extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { IStudentService studentService = new StudentServiceImpl(); int count = studentService.getTotalCount();//Total data //Assemble the five fields required for paging (one of them is calculated automatically, but actually only four need to be assembled) into the page object Page page = new Page(); //Gets the number of pages passed in the jsp String cPage = request.getParameter("currentPage"); //Judge whether the number of incoming pages is empty. If it is empty, it is the first time to enter, if(cPage == null) { //The first entry changes the number of pages to 0. Because the number of MySQL pages starts from 0, the first page is 0 cPage = "0"; } //The received cPage is of string type. Here, call the parseInt method to convert it into a string int currentPage = Integer.parseInt(cPage); //Here, the current number of pages is encapsulated into the page object page.setCurrentPage(currentPage); int totalCount = studentService.getTotalCount(); page.setTotalCount(totalCount); int pageSize= 5; page.setPageSize(pageSize); List<Student> students = studentService.queryStudentsByPage(currentPage,pageSize); System.out.println(students); System.out.println(count); page.setStudents(students); //Pass the encapsulated page into jsp request.setAttribute("page",page); request.getRequestDispatcher("index.jsp").forward(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
QueryStudentBySno
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.Student; import service.IStudentService; import service.impl.StudentServiceImpl; //Query students by student number public class QueryStudentBySnoServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); int no = Integer.parseInt(request.getParameter("sno")); //Use polymorphic interface: xx = new implementation class IStudentService service = new StudentServiceImpl(); Student student = service.queryStudentBySno(no); //System.out.println(student); //When querying all the information of the student, display the student through the JSP on the front desk: studentinfo jsp //Save the student's information to the reuqest field first request.setAttribute("student",student); //If there is no data in the request field, use redirect response sendRedirect(); //If there is data in the request field, use the method of request forwarding request.getRequestDispatcher("studentInfo.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
update
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.Student; import service.IStudentService; import service.impl.StudentServiceImpl; //Methods of modifying student information public class UpdateStudentServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Sets the encoding type of the request request.setCharacterEncoding("utf-8"); //Obtain the student number of the student to be modified int no = Integer.parseInt(request.getParameter("sno")); //Get the content that needs to be modified and encapsulate it into an entity class (java bean) String name = request.getParameter("sname"); int age = Integer.parseInt(request.getParameter("sage")); String address = request.getParameter("saddress"); //Encapsulate the modified content into Student Student student = new Student(name,age,address); //Create a new Service object //Use polymorphic interface: xx = new implementation class IStudentService service = new StudentServiceImpl(); //Call student's method boolean isUpdateSuccess = service.updateStudentBySno(no, student); //Set the encoding type when responding response.setContentType("text/html;charset=UTF-8"); response.setCharacterEncoding("utf-8"); //Phase I // if(isUpdateSuccess) { // //response.getWriter().print("modified successfully"); // }else { // response.getWriter().print("modification failed"); // } //Phase II // if(isUpdateSuccess) { // //After the modification is successful, re query all student information, that is, redirect to QueryAllStudentServlet // response.sendRedirect("QueryAllStudentServlet"); // }else { // response.getWriter().print("modification failed"); // } if(isUpdateSuccess) { request.setAttribute("isSuccess","Modified successfully"); }else{ request.setAttribute("isSuccess","Modification failed"); } //In any case, go to the all student information interface //Because data needs to be transmitted, the method of request forwarding is used //request.getRequestDispatcher("QueryAllStudentServlet").forward(request, response); //After querying the database by page and modifying the student information, go to QueryStudentByPage request.getRequestDispatcher("QueryStudentByPage").forward(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
DBUtil tool class
package util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import entity.Student; //General database operation method public class DBUtil { //Defined separately, it can be applied to multiple methods private static final String URL = "jdbc:mysql://localhost:3306/datas"; private static final String USERNAME = "root"; private static final String PASSWORD = "1051976202"; public static Connection conn = null; public static PreparedStatement ps = null; public static ResultSet rs = null; //Get database connection public static Connection getConnection() throws ClassNotFoundException, SQLException { Class.forName("com.mysql.cj.jdbc.Driver"); return DriverManager.getConnection(URL,USERNAME,PASSWORD); } //Pass values to parameters public static PreparedStatement createPreparedStatement(String sql,Object[] params) throws ClassNotFoundException, SQLException { ps =getConnection().prepareStatement(sql); if(params != null) {//If the collection is empty, the value transfer operation will not be performed for(int i=0;i<params.length;i++) { //i+1 indicates to? The first value of is passed to the first value of the array, that is, the element with subscript 0 ps.setObject(i+1,params[i]); } } return ps; } //Method of closing connection public static void closeAll(ResultSet rs ,Statement stmt ,Connection connection) { if(rs != null) { try { rs.close(); }catch(SQLException e) { e.printStackTrace(); } } if(ps != null) { try { ps.close(); }catch(SQLException e) { e.printStackTrace(); } } if(conn != null) { try { conn.close(); }catch(SQLException e) { e.printStackTrace(); } } } //General database addition, deletion and modification public static boolean executeUpdate(String sql,Object[] params) { boolean flag = false; try { //Get database connection using method // Class.forName("com.mysql.cj.jdbc.Driver"); // conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); //Object obs = {name,age,x,...,xx}; For delivery? Value of //String sql = " update student set name=?,age=?,x=? where xx=? "; // ps =getConnection().prepareStatement(sql); //ps.setInt(1, sno); //The number of setXxx() methods is the same as that of? The number of has been,? The number of params is actually the number of params in the array //The number of setXxx() methods is consistent with the number of array params // If (params! = null) {/ / if the collection is empty, no value transfer operation will be performed // for(int i=0;i<params.length;i++) { // //i+1 indicates to? The first value of is passed to the first value of the array, that is, the element with subscript 0 // ps.setObject(i+1,params[i]); // } // } ps = createPreparedStatement(sql,params); int count = ps.executeUpdate(); if(count==1) { flag = true; } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { closeAll(null,ps,conn); // if(ps != null) { // try { // ps.close(); // }catch(SQLException e) { // e.printStackTrace(); // } // } // if(conn != null) { // try { // conn.close(); // }catch(SQLException e) { // e.printStackTrace(); // } // } } return flag; } //General query: the return value is a set (student, list < student >, null > //Because of decoupling, the collection of student objects cannot be returned, but the object of ResultSet type should be returned public static ResultSet executeQuery(String sql,Object[] params) { try { // Class.forName("com.mysql.cj.jdbc.Driver"); // conn = DriverManager.getConnection(URL,USERNAME,PASSWORD); //String sql = "select * from student"; String ename,job from xx where... // ps =getConnection().prepareStatement(sql);// precompile //If so? Then pass value // If (params! = null) {/ / if the collection is empty, no value transfer operation will be performed // for(int i=0;i<params.length;i++) { // ps.setObject(i+1, rs); // } // } ps = createPreparedStatement(sql,params); rs = ps.executeQuery(); //implement //To be common to all queries, you need to remove the coupled code /* * //Use a loop to put the student object into the collection while (rs.next()) {int no = rs.getint ("SnO"); string name= * rs.getString("sname"); int age = rs.getInt("sage"); String address = * rs.getString("saddress"); //Encapsulated data student = new Student(no,name,age,address); * //Put the object into the collection students add(student); } */ } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } //Because rs wants to return, it cannot be closed at last /* * finally { if(rs != null) { try { rs.close(); }catch(SQLException e) { * e.printStackTrace(); } } if(ps != null) { try { ps.close(); * }catch(SQLException e) { e.printStackTrace(); } } if(conn != null) { try { * conn.close(); }catch(SQLException e) { e.printStackTrace(); } } } */ //Because of decoupling, the collection of student objects cannot be returned, but the object of ResultSet type should be returned //return students; return rs; } //Total queries public static int getTotalCount(String sql) {//select count(1) form student; //The default value is - 1. If it is not found, it returns - 1. int count = -1; try { ps = createPreparedStatement(sql,null); rs = ps.executeQuery(); if(rs.next()) { //getInt() gets the data of the database according to the index, starting from 1 count = rs.getInt(1); } }catch(SQLException e) { e.printStackTrace(); }catch(Exception e) { e.printStackTrace(); } return count; } }
index
<%@ page import="entity.Page" %> <%@ page import="java.util.List"%> <%@ page import="entity.Student" %> <%@ page import="java.lang.String" %> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <script type="text/javascript" src="js/jquery-1.8.3.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("tr:odd").css("background-color","lightgray"); }); </script> <meta charset="UTF-8"> <title>Student information</title> </head> <body> <% /* On the basis of pagination display: what data does jsp need Current page: currentPage Page size: pageSize Data collection of the current page: students Total data: totalCount Total pages: totalPage Create a new Page class to encapsulate the above five fields */ %> <!-- When you're here, you have to do it first QueryAllStudentServlet because index This is needed in the servlet Return data, otherwise index Just execute it null So put QueryAllStudentServlet Put on web.xml First in<welcome-file> In the label, server This will be executed after startup servlet,Then jump to by forwarding Should index in --> <!-- Problems needing attention during running: you cannot right-click to run on this page, - Right click in the project list to run - Or in QueryAllStudentServlet Right click Run --> <!-- Phase III: each increase/modify/Prompt whether the deletion is successful or not --> <% //Get the prompt to judge whether it is successful String success =(String)request.getAttribute("isSuccess"); /* "".equals()Can avoid null pointers If you simply show whether the operation is successful, you can use this method to subtract the judgment of null pointer After adding / deleting / modifying successfully, pass in yes and vice versa: no if("yes".equals(success)){ out.print("Operation succeeded "); }else if("no".equals(success)){ out.print("Operation failed ''); } */ //Use the method of intercepting string to judge //(Master) The String substring(int beginIndex) parameter is the starting subscript intercepted string //System.out.println("http://www.baidu.com".substring(7)); //www.baidu.com //(Master) String substring(int beginIndex,int endIndex) intercepts some strings //beginIndex start position (including) endIndex end position (excluding) //System.out.println("http://www.baidu.com".substring(7,10)); //www /* if(success != null){ if("Success ". equals(success.substring(2))){ out.print(success); }else if("Failed ". equals(success.substring(2))){ out.print(success); } } */ //Two other methods: //(Master) boolean contains(CharSequence s) //Judge whether the previous string contains the following string, including: return true, excluding: return false //Here, success. Is called at the bottom of contains ToString () method, so null pointers should also be processed here. If they are not null, they can be executed again /* if(success != null){ if("Added successfully deleted successfully modified successfully ". contains(success)){ out.print(success); }else if("Adding failed deleting failed modifying failed ". contains(success)){ out.print(success); } } */ //(Master) boolean endsWith(String suffix) //Determines whether the current string ends with a string if(success != null){ if(success.endsWith("success")){ out.print(success); }else if(success.endsWith("fail")){ out.print(success); } } %> <table border="1px"> <tr> <th>Student number</th> <th>full name</th> <th>Age</th> <!-- <th>address</th> --> <th>operation</th> </tr> <% //Use getAttribute to get the data in the requset field //Because the return value of this method is of type Object, cast is used //List<Student> students = (List<Student>)request.getAttribute("students"); //Page is directly received. You can't name the variable page here, because one of the built-in objects of jsp is page, and you can't rename it again Page pag = (Page)request.getAttribute("page"); //Traverse the data in the output set for(Student student: pag.getStudents()){ //One person's data is output in each cycle, which is separated by java code blocks %> <!-- Intermediate use java Expression to get --> <tr> <!-- Click the student number to display all the information of the student --> <td><a href="QueryStudentBySnoServlet?sno=<%=student.getSno()%>"><%=student.getSno()%></a></td> <td><%=student.getSname() %></td> <td><%=student.getSage() %></td> <%-- Don't display all of them first. Click the student number and then display all the details <td><%=student.getSaddress() %></td>--%> <!-- You can delete each student's information record here Using hyperlinks, go to the deleted servlet, The parameter transmitted is the student number of this message. This message can be deleted by the student number ?Pass the student number behind sno,Continue calling getSno Methods obtain the student number of the student --> <td> <a href="DeleteStudentServlet?sno=<%=student.getSno()%>">delete</a> </td> <!-- After the deletion is successful, you need to query all students again servlet in If the deletion is successful, redirect to QueryAllStudentServlet this servlet in Then this servlet It will be forwarded here again after execution index Show all student information in --> </tr> <% } %> </table> <a href="add.jsp">newly added</a><br/> <!-- Pagination database displays student information --> <% //If the current page is the first page, only the next page and the last page will be displayed //Since the number of MySQL pages starts from 0, the first page is 0 if(pag.getCurrentPage() == 0){ %> <a href="QueryStudentByPage?currentPage=<%=pag.getCurrentPage()+1%>">next page</a> <a href="QueryStudentByPage?currentPage=<%=pag.getTotalPage()-1%>">Last page</a> <% //If it is the last page, only the first page and the previous page are displayed }else if(pag.getCurrentPage() == pag.getTotalPage()-1){ %> <a href="QueryStudentByPage?currentPage=0">home page</a> <a href="QueryStudentByPage?currentPage=<%=pag.getCurrentPage()-1%>">previous page</a> <% }else{//If it is not the first page or the last page, the first page, previous page, next page and last page will be displayed. %> <a href="QueryStudentByPage?currentPage=0">home page</a> <a href="QueryStudentByPage?currentPage=<%=pag.getCurrentPage()-1%>">previous page</a> <a href="QueryStudentByPage?currentPage=<%=pag.getCurrentPage()+1%>">next page</a> <!-- Last page: total pages. stay mySQL Starting from 0, so the total number of pages-1 That is, the last page data can be obtained --> <a href="QueryStudentByPage?currentPage=<%=pag.getTotalPage()-1%>">Last page</a> <% } %> </body> </html>
add
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <script type="text/javascript" src="js/jquery-1.8.3.js"></script> <script type="text/javascript"> $(document).ready(function(){ }); function check(){ //onsubmit: ruturn true the form is submitted normally, return false the form is not submitted var sno = $("#sno").val(); var sname = $("#sname").val(); var sage = $("#sage").val(); var saddress = $("#saddress").val(); if(sno < 0){ alert("Student number is incorrect, please re-enter") return false; } if(!(sname.length>1 && sanme.length<5)){ alert("Name must be in 2-10 position"); return false; } //if(){return false} return true; } </script> </head> <body> <!-- add to submit Event, verification form --> <form action = "AddstudentServlet" method="post" onsubmit="return check()"> Student number:<input type="text" name="sno" id="sno"><br> full name:<input type="text" name="sname" id="sname"/><br> Age:<input type="text" name="sage" id="sage"/><br> Address:<input type="text" name="saddress" id="saddress"><br> <input type="submit" value="newly added"/><br> </form> <!-- <a href="QueryAllStudentServlet">return</a> --> <!-- After paging the database, return to the first page of the information --> <a href="QueryStudentByPage">return</a> </body> </html>
studentInfo
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ page import="entity.Student" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% //Get the data saved in the requset field first Student student = (Student)request.getAttribute("student"); %> <!-- Use forms to display student information, so that you can directly add the function of modification In addition, the data forms that need to be submitted during modification are all available, so they can be submitted directly to UpdateStudentServlet In the middle, here again servlet Definition in: if the modification is successful Go directly to the one who inquires all student information servlet in --> <form action="UpdateStudentServlet"> <!-- Because it is modified through the student number, the student number is set to read-only: readonly="readonly"--> <!-- When reading, you need to pass name Read, so here name Write it down --> Student number:<input type="text" name="sno" value=<%=student.getSno() %> readonly="readonly"><br> full name:<input type="text" name="sname" value=<%=student.getSname() %>><br> Age:<input type="text" name="sage" value=<%=student.getSage() %>><br> Address:<input type="text" name="saddress" value=<%=student.getSaddress() %>><br> <!-- Add modification function --> <input type="submit" value="modify"> <!-- <a href="QueryAllStudentServlet">return</a> --> <!-- After paging the database, return to the first page of the information --> <a href="QueryStudentByPage">return</a> </form> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>ThreeTierSample</display-name> <welcome-file-list> <welcome-file>QueryStudentByPage</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>AddstudentServlet</display-name> <servlet-name>AddstudentServlet</servlet-name> <servlet-class>servlet.AddstudentServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AddstudentServlet</servlet-name> <url-pattern>/AddstudentServlet</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>DeleteStudentServlet</display-name> <servlet-name>DeleteStudentServlet</servlet-name> <servlet-class>servlet.DeleteStudentServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DeleteStudentServlet</servlet-name> <url-pattern>/DeleteStudentServlet</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>UpdateStudentServlet</display-name> <servlet-name>UpdateStudentServlet</servlet-name> <servlet-class>servlet.UpdateStudentServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UpdateStudentServlet</servlet-name> <url-pattern>/UpdateStudentServlet</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>QueryStudentBySnoServlet</display-name> <servlet-name>QueryStudentBySnoServlet</servlet-name> <servlet-class>servlet.QueryStudentBySnoServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>QueryStudentBySnoServlet</servlet-name> <url-pattern>/QueryStudentBySnoServlet</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>QueryAllStudentServlet</display-name> <servlet-name>QueryAllStudentServlet</servlet-name> <servlet-class>servlet.QueryAllStudentServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>QueryAllStudentServlet</servlet-name> <url-pattern>/QueryAllStudentServlet</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>QueryStudentByPage</display-name> <servlet-name>QueryStudentByPage</servlet-name> <servlet-class>servlet.QueryStudentByPage</servlet-class> </servlet> <servlet-mapping> <servlet-name>QueryStudentByPage</servlet-name> <url-pattern>/QueryStudentByPage</url-pattern> </servlet-mapping> </web-app>
File upload and download
Upload:
use apache of commons-fileupload.jar Component, which depends on commons-io.jar. Both need to be downloaded Browser search: component name mvn . Directly in mvn Download from library introduce: Put these two jar Packages placed in the project WebContent In folder WEB-INF In folder lib Under folder
to write
-
Foreground jsp
Form submission method must be post,because get The submission method data is placed in the address bar, and the maximum capacity of the address bar is 4 kb,Most of the uploaded files exceed this size, so they must be used post Submission method You must add an attribute to the form: entype="multipart/form-data"
-
Problems needing attention when uploading files to the directory
Uploaded directory upload Yes tomcat In the server directory 1,If you modify the code, then tomcat When we restart, we create a new one in the project upload The folder will be deleted. Reason: when modifying the code, tomcat Will recompile a copy class,And redeploy (recreate various directories) 2,If the code is not modified, it will not be deleted upload folder Reason: the code was not modified, class It's still the same as before class. Solutions to prevent folder loss: 1,Use virtual paths. 2,Directly change the upload directory to non tomcat catalogue 3,have access to io Flowing File Class to create a folder where we need to store uploaded files. Before creating, you can also judge whether the folder exists. If it does not exist, create a new one.
-
Problems needing attention in file upload
Limit upload: Type and size Note the restrictions on the file and write it again parseRequest before
-
Problems needing attention in file download
Download does not need to rely on any jar - request(address a,form form ),request servlet - Servlet Through the address of the file, turn the file into an input stream and read it Servlet in - Output the file that has just been converted into the input stream to the user through the output stream Note: to download a file, you need to set two response headers: //Set the download type of the file response.addHeader("content-Type","application/octet-stream"); //The file name of the file to download. fileName file name contains file suffix, such as ABC txt response.addHeader("content-Disposition","attachement;filename="+fileName);
-
Solution of browser garbled code during download
//If the file name of the file contains the Chinese character, it needs to be transcoded Encode (file name, encoding type); //This method is applicable to IE, chrome and Firefox in 2021 response.addHeader("content-Disposition","attachement;filename="+URLEncoder.encode(fileName,"utf-8")); If it is a previous version of Firefox: Prefix file names with:=?UTF-8?B?,String Construction method Base64.encode,suffix?= response.addHeader("content-Disposition","attachement;filename==?UTF-8?B?"+new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))+"?="); //This method is applicable to IE, chrome and Firefox in 2021 //response.addHeader("content-Disposition","attachement;filename="+URLEncoder.encode(fileName,"utf-8")); //If it is the previous Firefox browser, you need to judge which browser to use when executing here //Get the user agent of the client String agent = request.getHeader("User-Agent"); //toLowerCase(): convert to lowercase. indexOf() determines the index (subscript) of the first occurrence of a substring in the current string //If it is not - 1, it means that the string contains firefox, that is, firefox browser if(agent.toLowerCase().indexOf("firefox")!=-1) { response.addHeader("content-Disposition","attachement;filename==?UTF-8?B?"+new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))+"?="); }else { response.addHeader("content-Disposition","attachement;filename="+URLEncoder.encode(fileName,"utf-8")); }
File upload and download examples
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <form action="UploadServlet" method="post" enctype="multipart/form-data"> Student number<input name="sno"/><br/> full name<input name="sname"/><br/> Upload photos<input type="file" name="spicture"/> <br/> <input type="submit" value="register"/> </form> <a href="DownloadServlet?filename=picture.png">picture</a> </body> </html>
UploadServlet: the servlet used for uploading
package servlet; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadBase; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class UploadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Encoding settings at request request.setCharacterEncoding("utf-8"); //Encoding settings in response response.setCharacterEncoding("utf-8"); //Coding settings when displaying response.setContentType("text/html; charset=UTF-8"); //upload //This method returns a Boolean value, which is used to judge whether the submitted form contains the attribute: entype = "multipart / form data" boolean isMultipart = ServletFileUpload.isMultipartContent(request); //If the submitted form has the mutipart attribute if(isMultipart) { //Uploading requires an object of type ServletFileUpload, which needs to pass an object of type FileItemFactory //FileItemFactory is an interface, and the implementation class DiskFileItemFactory of this interface is used when creating a new object //FileItemFactory factory = new DiskFileItemFactory(); DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); //Add restrictions before parsing //Set the size of temporary files used when uploading files. Object of type DiskFileItemFactory factory.setSizeThreshold(1024*10);//Set the temporary buffer file size to 10kb, that is, if it is a 50kb file, it needs to be buffered for 5 times factory.setRepository(new File("D:\\uploadtemp"));//Set the path of temporary file storage //Control the size of a single file: 40kb. Object of type ServletFileUpload upload.setSizeMax(1024*40);//Unit: byte B. try { //Parse all request fields in the form through parseRequest and save them to the items collection //That is, sno, sname and spice passed by the foreground are now saved in the items collection List<FileItem> items = upload.parseRequest(request); //Traverse the data in items (sno, sname, spice) Iterator<FileItem> iter = items.iterator(); while(iter.hasNext()) { FileItem item = iter.next(); //Here, the getFiledName() method is used to obtain the name value of the common form field String itemName = item.getFieldName(); int sno = -1; String sname = null; //Determine whether the foreground field is a normal form field or a file field through the isFormField() method if(item.isFormField()) {//Judge whether the item is sno, sname or spice according to the name attribute //If it is a normal field, judge which one is in the normal field if(itemName.equals("sno")) { //Ordinary form through request Getparameter() passes name to get value //Upload files in the form through ITER The getString () method can get all the values //After judging by the above methods, take it directly and then operate it //Parameter passes an encoding type, usually utf-8 sno = Integer.parseInt(item.getString("UTF-8")); }else if(itemName.equals("sname")) { sname = item.getString("UTF-8"); }else { System.out.println("Other fields"); } }else {//spicture //File upload //The file name getFieldName is the name value that gets the field of the normal form //getName() is the field to get the file name, that is, the field to get the file name String fileName = item.getName();//a.txt ,a.docx ,a.png //boolean endsWith(String suffix) determines whether the current string ends with a string if(!(fileName.endsWith("png")||fileName.endsWith("jpg")||fileName.endsWith("jpeg"))) { System.out.println("Wrong picture type, format must be png or jpg or jpeg"); //If it is not the specified type, the execution of the program is terminated return; } //Get file content and upload //Definition file path: specify the upload location (server path: this project in the directory where tomcat is located) //Get the server path: D:\Program Files (x86)\eclipse\tomcat-9\wtpwebapps\UpAndDown\upload //String path = request.getSession().getServletContext().getRealPath("upload"); String path = "D:\\upload"; File file = new File(path,fileName); //upload item.write(file); System.out.println(fileName+"Upload successful"); return; } } }catch(FileUploadBase.SizeLimitExceededException e) { System.out.println("Upload file size exceeds the limit,The maximum file size is 40 kb"); }catch (FileUploadException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
DownLoadServlet: a servlet for downloading
package servlet; import java.io.IOException; import java.io.InputStream; import java.net.URLEncoder; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.tomcat.util.codec.binary.Base64; public class DownloadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Set encoding type request.setCharacterEncoding("utf-8"); //form,<a href=""> ,... Servlet?a=b, all values are obtained through request Getparameter() method String fileName = request.getParameter("filename"); //To download a file, you need to set the message header: //Set the download type of the file response.addHeader("content-Type","application/octet-stream"); //The file name of the file to download //fileName file name contains file suffix, such as ABC txt //response.addHeader("content-Disposition","attachement;filename="+fileName); //If the file name contains Chinese, the file name needs to be transcoded Encode (file name, encoding type); //This method is applicable to IE, chrome and Firefox in 2021 response.addHeader("content-Disposition","attachement;filename="+URLEncoder.encode(fileName,"utf-8")); //Adapt to previous versions of Firefox: //response.addHeader("content-Disposition","attachement;filename==?UTF-8?B?"+new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))+"?="); // //If it is the previous Firefox browser, you need to judge which browser to use when executing here // //Get the user agent of the client // String agent = request.getHeader("User-Agent"); // //toLowerCase(): convert to lowercase. indexOf() determines the index (subscript) of the first occurrence of a substring in the current string // //If it is not - 1, it means that the string contains firefox, that is, firefox browser // if(agent.toLowerCase().indexOf("firefox")!=-1) { // response.addHeader("content-Disposition","attachement;filename==?UTF-8?B?"+new String(Base64.encodeBase64(fileName.getBytes("UTF-8")))+"?="); // }else { // response.addHeader("content-Disposition","attachement;filename="+URLEncoder.encode(fileName,"utf-8")); // } //Servlet converts the file into an input stream through the address of the file and reads it into the servlet InputStream in = getServletContext().getResourceAsStream("/res/picture.PNG"); //The file that has just been converted into the input stream is responded to the user through the output stream ServletOutputStream out = response.getOutputStream(); byte[] bs = new byte[10]; int len = -1; while((len=in.read(bs))!=-1) { out.write(bs,0,len); } out.close(); in.close(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
EL expression
-
EL: Expression Language can replace java code in JSP pages (eliminate java code in JSP)
servlet(Add data)->jsp(Display data) Traditional in jsp of use java Disadvantages of code display data: type conversion and processing null,Mixed code. use EL These problems can be avoided, and EL No guide package is required.
-
grammar
${EL expression} ${Domain object.Properties in domain objects.attribute.Properties of properties} ${requestScope.student.address.schoolAddress} Operators: operation attributes dot operator(.): Easy to use []Operator: if it is a constant attribute, you need to use""/''Pull it up. More powerful than the point operator: - It can contain special characters(. , -). - You can also get the value of a variable, such as a variable that exists name,Then you can ${requestScope[name]} - []If you do not use quotation marks in, it is a variable. If you use quotation marks, it is an attribute. String x = "a"; ${requestScope.a}Equivalent to ${requestScope["a"]}Equivalent to ${requestScope[x]} - You can also get array elements (that is, access arrays) Application: --------------dot operator----------------<br/> ${requestScope.student}<br/> ${requestScope.student.sno }<br/> ${requestScope.student.sname }<br/> ${requestScope.student.address }<br/> ${requestScope.student.address.homeAddress }<br/> ${requestScope.student.address.schoolAddress }<br/> --------[]Operator,The attribute name should be enclosed in single quotation marks or double quotation marks---------------<br/> ${requestScope["student"]["address"]["schoolAddress"] }<br/> -----Attribute names with special symbols--------<br/> Point operator: ${requestScope.my-name }<br/> [""]Operator: ${requestScope['my-name'] }<br/> ----Get array data hobbies-------<br/> ${requestScope.hobbies[0] }<br/> ${requestScope.hobbies[2] }
-
Get the value in the normal object and map. And the operator of EL
EL relational and logical operators
[the external chain picture transfer fails, and the source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-wjlwqerx-1622360006666) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ picture \ 21, EL relational operator and logical operator. PNG)]
Empty Operator: judge whether a value is null,Return if empty false. Application: -----map ${requestScope.map.cn } ${requestScope.map["us"] } -----operation------ ${3>2 },${3 gt 2 } ${3>2 || 3<2 },${3>2 or 3<2 }; ------empty------ Non empty(false): ${empty requestScope["my-name"] } Non existent value(true): ${empty requestScope["helloworld"] } Null value(true): ${empty requestScope.nullVal } ---session---- ${sessionScope.sessionKey } ${sessionKey }
-
Implicit object of EL expression (object that can be used without new: self-contained object)
- Scope access object( EL Domain object: pageScope requestScope sessionScope applicationScope If you do not specify a domain object, the values will be taken from small to large by default: pageScope<requestScope<sessionScope<applicationScope - Parameter access object: get the value passed in the form data (hyperlink) a.jsp?a=b&c=d,Value in address bar a.jsp?a=b&c=d) (request.getParameter(),request. getParameterValues EL Get by: ${param} ${paramValues} - JSP Implicit object: pageContext,stay jsp Can pass pageContext Get other jsp Implicit object; So if you want to EL Used in JSP Implicit object, you can pageContext Indirect acquisition. ${pageContext.Remove the method name()and get And make the first letter lowercase}. For example: ${pageContext.getSession()} --> ${pageContext.session} ${pageContext.getResponse()} --> ${pageContext.response} ${pageContext.getRequest()} --> ${pageContext.request} You can also use this method to cascade acquisition methods: the same is the method name()and get And make the first letter lowercase: ${pageContext.request.serverPort}
Application:
form.jsp
<form action="el.jsp"> user name:<input name="uname" type="text"/><br/> interest:<br/> <input name="hobbies" value="football" type="checkbox" />Football <input name="hobbies" value="basketball" type="checkbox" />Basketball <input name="hobbies" value="pingpang" type="checkbox" />Table Tennis <input type="submit" value="register" /> </form>
el.jsp
-------------Parameter object--------<br/> ${param.uname }<br/> ${paramValues.hobbies[0] }<br/> ${paramValues.hobbies[1] }<br/> ${paramValues.hobbies[2] }<br/> ${pageContext.request.serverPort}
-
Sevlets used in EL
package servlet; import java.io.IOException; import java.util.HashMap; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.Address; import entity.Student; public class ElInitServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Student student =new Student(); student.setSno(1); student.setSname("zs"); Address address = new Address(); address.setHomeAddress("xa"); address.setSchoolAddress("bj"); student.setAddress(address); //Put the student into the request field request.setAttribute("student",student); request.setAttribute("my-name","daidai"); String[] bobbies = new String[] {"football","pingpang","basketball"}; request.setAttribute("hobbies", bobbies); Map<String,Object> map = new HashMap<>(); map.put("cn","China"); map.put("us","U.S.A"); request.setAttribute("map",map); request.setAttribute("nullVal",null); request.getSession().setAttribute("sessionKey","sessionValue"); request.getRequestDispatcher("el.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
-
Entity classes used in EL
address.java entity
package entity; public class Address { private String homeAddress; private String schoolAddress; public String getHomeAddress() { return homeAddress; } public void setHomeAddress(String homeAddress) { this.homeAddress = homeAddress; } public String getSchoolAddress() { return schoolAddress; } public void setSchoolAddress(String schoolAddress) { this.schoolAddress = schoolAddress; } }
student.java entity
package entity; public class Student { private int sno ; private String sname ; private Address address; public int getSno() { return sno; } public void setSno(int sno) { this.sno = sno; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
JSTL expression
-
Assignment, display and deletion of general tags in JSTL
use JSTL Need to introduce two jar: jstl.jar ,standard.jar Need to use tablib Label introduction: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> among prefix="c"Represents the prefix. jstl You need to use the core tag library. The core tag library includes: General tag library, conditional tag library and iterative tag library - General label Library: <c:set>Assignment: 1,Assign a value to a variable in a scope (four scope objects) <c:set var="Variable name" value="Variable value" scope="Scope of four scope objects"/> <!-- request.setAttribute("name","zhangsan"); -->Equivalent to: <c:set var="name" value="zhangsan" scope="request" /> <c:set var="Variable name" value="Variable value" scope="4 Scope of multiple scope objects" /> 2,Assign values to normal objects In a scope (four scope objects), assign a value to an object (this writing method cannot be specified) scope Properties) <c:set target="${requestScope.student }" property="sname" value="zxs" /> <c:set target="object" property="Object properties" value="New value" /> 3,to map Object Assignment <c:set target="${requestScope.countries }" property="cn" value="China" /> be careful:<c:set>You can assign values to variables that do not exist(However, you cannot assign a value to an object that does not exist) <c:set var="x" value="y" scope="request" /> <c:out> display tradition EL: ${requestScope.student } c:out Method:<c:out value="${requestScope.student}"/> default Attribute: when value When empty, the default value displayed c:out Display data that does not exist:<c:out value="${requestScope.stu }" default="zs-23"/> escapeXml Properties: for true Displays the string in quotation marks, if false That is, it is displayed after code parsing true: <c:out value='<a href="https://www.baidu. Com "> Baidu < / a > 'escape XML =" true "/ > < br / > false: <c:out value='<a href="https://www.baidu. Com "> Baidu < / a > 'escape XML =" false "/ > <c:remove>: Delete attribute <c:remove var="a" scope="request" />
Application: JSTL jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <!-- request.setAttribute("name","zhangsan"); --> <c:set var="name" value="zhangsan" scope="request"/> ${requestScope.name} <br/> ============Assign values to properties of ordinary objects=============<br/> ${requestScope.student.sname }<br/> <c:set target="${requestScope.student }" property="sname" value="zxs" /> ${requestScope.student.sname }<br/> ============to map Attribute assignment of object=============<br/> ${requestScope.countries.cn }<br/> <c:set target="${requestScope.countries }" property="cn" value="China" /> ${requestScope.countries.cn }<br/> ============Assign a value to a variable that does not exist=============<br/> <c:set var="x" value="y" scope="request" /> ${requestScope.x } <br/> <br/> =========c:out=========<br/> tradition EL: ${requestScope.student }<br/> c:out Method:<c:out value="${requestScope.student}"/><br/> c:out Display data that does not exist:<c:out value="${requestScope.stu }" default="zs-23"/> <br/><br/><br/> <a href="https://www.baidu. Com "> Baidu < / a > < br / > true: <c:out value='<a href="https://www.baidu. Com "> Baidu < / a > 'escape XML =" true "/ > < br / > false: <c:out value='<a href="https://www.baidu. Com "> Baidu < / a > 'escape XML =" false "/ > <br/><br/><br/> <c:set var="a" value="b" scope="request"/><br/> Display: ${a } <c:remove var="a" scope="request" /><br/> Display after deletion: ${a } </body> </html>
-
Single selection and multiple selection in conditional tag library in JSTL
<!-- use JSTL Time,General recommendations: ${Range.xx},This will directly look for attributes in this range xx --> <!-- Write only if ${xx}You can also look for attributes in four range objects from small to large xx: pageScope requestScope sessionScope applicationScope However, it is suggested to add scope--> <!-- Note: single weight/In multiple selection test Value in property"${}"Inside}And back quotation marks(")No spaces between If there are spaces, it is equivalent to a boolean variable and an empty string""After the join operation, it is not a Boolean value Therefore, we should pay attention to:}No space after --> choice: if(boolean) Single selection <c:if test="" > <c:if test="${10>5 }" var="result" scope="request"> really ${requestScope.result } </c:if> Multiple selection: if else if... esle if... else /switch <c:choose> <c:when test="..."> </c:when> <c:when test="..."> </c:when> <c:when test="..."> </c:when> <c:otherwise> </c:otherwise> </c:choose> <!-- Multiple choice --> <c:set var="role" value="student" scope="request"></c:set> <c:choose> <c:when test="${requestScope.role == 'teacher' }">The teacher's....</c:when> <c:when test="${requestScope.role == 'student' }">Student's....</c:when> <c:otherwise> Administrators and other personnel</c:otherwise> </c:choose> in use test="" Be sure to pay attention to whether there is a space after it For example: test="${10>2 }" true test="${10>2 } " wrong true
Application:
jstl2.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <%-- use JSTL Time,General recommendations: ${Range.xx},This will directly look for attributes in this range xx --%> <%-- If only write ${xx}You can also look for attributes in four range objects from small to large xx: pageScope requestScope sessionScope applicationScope However, it is suggested to add scope --%> <%-- Note: single weight/In multiple selection test Value in property"${}"Inside}And back quotation marks(")No spaces between If there are spaces, it is equivalent to a boolean variable and an empty string""After the join operation, it is not a Boolean value Therefore, we should pay attention to:}No space after --%> <!-- Single selection --> <c:if test="${10>5 }" var="result" scope="request"> really ${requestScope.result } </c:if> <br/> <br/> <br/> <!-- Multiple choice --> <c:set var="role" value="student" scope="request"></c:set> <c:choose> <c:when test="${requestScope.role == 'teacher' }">The teacher's....</c:when> <c:when test="${requestScope.role == 'student' }">Student's....</c:when> <c:otherwise> Administrators and other personnel</c:otherwise> </c:choose> <br><br> =========================<br> <!-- for(int i=0;i<5;i++) --> <%-- begin Is the starting value equivalent to int i=0,end Is the end value(contain),amount to i<=5 ,step Is 1 or-1,If it is 1: equivalent to i++ ;If it is-1,Is equivalent to i-- --%> <%-- You can also put var as well as varStatus. If you need to know which element is traversed, You can define one first varStatus="object",Then pass ${object.index}Extract attribute subscript --%> <c:forEach begin="0" end="5" step="1" varStatus="status"> ${status.index } test... </c:forEach> <br><br>=====<br> <!-- Traversal set --> <c:forEach var="name" items="${requestScope.names }"> --${name }-- </c:forEach> <br><br>=====<br> <!-- Traverse student set --> <c:forEach var="student" items="${requestScope.students }"> --${student.sno}--${student.sname }------------ </c:forEach> </body> </html>
-
Iterative tag library in JSTL
<!-- for(int i=0;i<5;i++) --> <%-- begin Is the starting value equivalent to int i=0,end Is the end value(contain),amount to i<=5 ,step Is 1 or-1,If it is 1: equivalent to i++ ;If it is-1,Is equivalent to i-- --%> <%-- You can also put var as well as varStatus. If you need to know which element is traversed, You can define one first varStatus="object",Then pass ${object.index}Extract attribute subscript --%> <c:forEach begin="0" end="5" step="1" varStatus="status"> ${status.index } test... </c:forEach> <!-- Traversal set --> <c:forEach var="name" items="${requestScope.names }"> --${name }-- </c:forEach> <!-- for(String str:names) --> <!-- Traverse student set --> <c:forEach var="student" items="${requestScope.students }"> ${student.sno}-${student.sname } </c:forEach>
-
Note: all attribute values are""It's in there ${}For example: test="${}". In this form,}And"There can be no spaces between them. Once there are spaces, it is equivalent to the string splicing operation between the execution result of the original code and the empty string, so an error occurs.
-
Entity classes and servlet s used in jstl
Address entity class
package entity; public class Address { private String homeAddress; private String schoolAddress; public String getHomeAddress() { return homeAddress; } public void setHomeAddress(String homeAddress) { this.homeAddress = homeAddress; } public String getSchoolAddress() { return schoolAddress; } public void setSchoolAddress(String schoolAddress) { this.schoolAddress = schoolAddress; } }
Student entity class
package entity; public class Student { private int sno ; private String sname ; private Address address; public int getSno() { return sno; } public void setSno(int sno) { this.sno = sno; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } }
InitServlet
package servlet; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.Address; import entity.Student; public class InitServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Student student = new Student(); student.setSno(1); student.setSname("zs"); Address add = new Address(); add.setHomeAddress("xa"); add.setSchoolAddress("bj"); student.setAddress(add); request.setAttribute("student", student); request.setAttribute("he-llo", "world"); String[] arr = new String[] {"aa","cc","dd"}; request.setAttribute("he-llo", "world"); request.setAttribute("arr", arr); response.setHeader("Cache-Control","no-cache"); //HTTP 1.1 response.setHeader("Pragma","no-cache"); //HTTP 1.0 response.setDateHeader ("Expires", 0); //prevents caching at the proxy server Map<String,String> map = new HashMap<>(); map.put("cn", "China"); map.put("us", "USA"); request.setAttribute("countries", map); String[] names = new String[] {"aaa","bb","ccc"}; request.setAttribute("names", names); //Create two new student objects Student stu1 = new Student(); Student stu2 = new Student() ; //Put value stu1.setSname("zs"); stu1.setSno(1); stu2.setSname("ls"); stu2.setSno(2); //Put two student objects into the collection List<Student> students = new ArrayList<>(); students.add(stu1); students.add(stu2); //Pass the collection object into the request field request.setAttribute("students", students); //The request is forwarded to jstl2 JSP page request.getRequestDispatcher("jstl2.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
filter
Filter interceptor diagram
[the external chain image transfer fails, and the source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-whuqelqn-1622360006668) (C: \ users \ Qishi \ desktop \ typera markdown learning \ JSP \ image \ 22, filter interceptor. png)]
-
filter
To put an ordinary class Become a class with specific functions (filter, interceptor)...). Either inherit the parent class, implement an interface, or add an annotation realization Filter Interface: - init(),destroy()The principle and execution timing of these two methods are consistent with each other Servlet Same. - Configure filters, similar to Servlet. stay web.xml Medium<web-app>Create a new label in the label; <!-- Configure filter --> <filter> <filter-name>MyServlet</filter-name> <filter-class>filter.MyFilter</filter-class> </filter> <filter-mapping> <filter-name>MyServlet</filter-name> <url-pattern>/MyServlet</url-pattern><!-- Block access only MyServlet Request for --> <!-- <url-pattern>/*</url-pattern> Block all requests --> </filter-mapping> - When executed, through the doFilter()Method to handle interception, And pass chain.doFilter(request,response);Release - Precautions for interception: Block access only MyServlet Request for:<url-pattern>/MyServlet</url-pattern> Block all requests (every visit will be blocked):<url-pattern>/*</url-pattern>
-
wildcard
dispatcher Request method: in<filter-mapping>In label - REQUEST: intercept HTTP request get post - FORWARD: Block only requests that are forwarded by request - INCLUDE:Intercept only request.getRequestDispatcher("").include() ,adopt<jsp:include page="..." />Requests made in this manner - ERROR: Intercept only<error-page>Requests made <!-- Configure filter --> <filter> <filter-name>MyServlet</filter-name> <filter-class>filter.MyFilter</filter-class> </filter> <filter-mapping> <filter-name>MyServlet</filter-name> <url-pattern>/*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping> be careful: Filter doFilter()The parameters in the method are ServletRequest Type Servlet The parameters of the method in are HttpServletRequest Type.
-
Filter chain
Multiple filters can be set, and the order of filters is determined by<filter-mapping>The location of the filter determines which filter<filter-mapping>Before, which is the first filter.
-
The servlet and jsp used in the filter
MyServlet.java
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class MyServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("servlet Server....."); response.sendRedirect("jstl2.jsp"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
MyFilter.java
package filter; 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; //To turn an ordinary class into a class with specific functions (filters, interceptors...) //Either inherit the parent class, implement an interface, or add an annotation public class MyFilter implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("Intercept request...."); //Both the release request and response are released. If you don't want to release, write null. chain.doFilter(request,response); System.out.println("Intercept response..."); } @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("filter...init..."); } @Override public void destroy() { System.out.println("filter...destroy"); } }
MyFilter2.java
package filter; 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; public class MyFilter2 implements Filter { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("Intercept request 2..."); //Release chain.doFilter(request,response); System.out.println("Intercept response 2..."); } @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("filter2...init..."); } @Override public void destroy() { System.out.println("filter2...destroy"); } }
index2.jsp
<a href="MyServlet">MyServlet</a>
-
configuration file
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>UpAndDown</display-name> <listener> <listener-class>listener.AttributeListener</listener-class> </listener> <listener> <listener-class>listener.BeanListener2</listener-class> </listener> <welcome-file-list> <welcome-file>InitServlet</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>UploadServlet</display-name> <servlet-name>UploadServlet</servlet-name> <servlet-class>servlet.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/UploadServlet</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>DownloadServlet</display-name> <servlet-name>DownloadServlet</servlet-name> <servlet-class>servlet.DownloadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DownloadServlet</servlet-name> <url-pattern>/DownloadServlet</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>ElInitServlet</display-name> <servlet-name>ElInitServlet</servlet-name> <servlet-class>servlet.ElInitServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ElInitServlet</servlet-name> <url-pattern>/ElInitServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>servlet.MyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/MyServlet</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>InitServlet</display-name> <servlet-name>InitServlet</servlet-name> <servlet-class>servlet.InitServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>InitServlet</servlet-name> <url-pattern>/InitServlet</url-pattern> </servlet-mapping> </web-app>
monitor
-
Listening range:
Four scope objects: PageContext request session application Listening object: request session application To write a listener: - Write the listener and realize the interface - to configure web.xml Note: individual do not need to be configured, such as listening, binding and unbinding: HttpSessionBindingListener ,monitor session Passivation and activation of objects: HttpSessionActivationListener stay<web-app>Create a new one in the label<listener>Tag in which to configure the class where the listener is located <listener> <listener-class>listener.ContextSessionRequestListener</listener-class> </listener>
-
Creation and destruction of listening objects
request: ServletRequestListener session: HttpSessionListener application: ServletContextListener Each listener provides two methods: How to start listening(..Initialized/..created),Method of monitoring end(..Destroyed).
-
jsp and servlet used to create and destroy listening objects
ContextSessionRequestListener.java
package listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.servlet.ServletRequestEvent; import javax.servlet.ServletRequestListener; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; //Implement listener interface public class ContextSessionRequestListener implements ServletRequestListener,HttpSessionListener,ServletContextListener { //Listen for application (object of type ServletContext) @Override public void contextInitialized(ServletContextEvent sce) { System.out.println("monitor ServletContext: ServletContext Object:"+sce+"Created"); } @Override public void contextDestroyed(ServletContextEvent sce) { System.out.println("monitor ServletContext: ServletContext Object:"+sce+"Destroyed"); } //Listening session @Override public void sessionCreated(HttpSessionEvent se) { System.out.println("monitor HttpSession: HttpSession Object:"+se+"Created"); } @Override public void sessionDestroyed(HttpSessionEvent se) { System.out.println("monitor HttpSession: HttpSession Object:"+se+"Destroyed"); } //Listen for request @Override public void requestDestroyed(ServletRequestEvent sre) { System.out.println("monitor ServletRequest: ServletRequest Object:"+sre+"Destroyed"); } @Override public void requestInitialized(ServletRequestEvent sre) { System.out.println("monitor ServletRequest: ServletRequest Object:"+sre+"Created"); } }
session.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <!-- Invalidate: Invalidate --> <a href="sessionInvalidate.jsp">send session invalid</a> </body> </html>
sessionInvalidate.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% System.out.println("==========session Destroy page sessionInvalidate.jsp================"); session.invalidate(); %> </body> </html>
-
Listening for property changes in objects
request: ServletRequestAttributeListener session: HttpSessionAttributeListener application: ServletContextAttributeListener
-
jsp and serve used to listen for attribute changes
attribute.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% //Add the attribute of application (object of ServletContext type) application.setAttribute("name","zs"); //replace application.setAttribute("name","ls"); //delete application.removeAttribute("name"); session.setAttribute("user","user01"); session.setAttribute("user","user02"); session.removeAttribute("user"); request.setAttribute("school","lq"); request.setAttribute("school","lq2"); request.removeAttribute("school"); %> </body> </html>
AttributeListener.java
package listener; import javax.servlet.ServletContextAttributeEvent; import javax.servlet.ServletContextAttributeListener; import javax.servlet.ServletRequestAttributeEvent; import javax.servlet.ServletRequestAttributeListener; import javax.servlet.http.HttpSessionAttributeListener; import javax.servlet.http.HttpSessionBindingEvent; public class AttributeListener implements ServletRequestAttributeListener, HttpSessionAttributeListener,ServletContextAttributeListener{ //ServletContext @Override public void attributeAdded(ServletContextAttributeEvent scae) { String attrName = scae.getName();//The property name of the current operation Object attrValue = scae.getServletContext().getAttribute(attrName); System.out.println("ServletContext[Add attribute:"+attrName+",Attribute value:"+attrValue); } @Override public void attributeRemoved(ServletContextAttributeEvent scae) { System.out.println("ServletContext[Delete attribute:"+scae.getName()); } @Override public void attributeReplaced(ServletContextAttributeEvent scae) { /** * application.setAttribute("name","zs"); -New name attribute * application.setAttribute("name","ls"); -Replace name attribute value */ String attrName = scae.getName(); Object attrValue = scae.getServletContext().getAttribute(attrName); System.out.println("ServletContext[Replace attribute:"+attrName+",Attribute value:"+attrValue); } //session @Override public void attributeAdded(HttpSessionBindingEvent se) { String attrName = se.getName();//The name of the property currently being operated on Object attrValue = se.getSession().getAttribute(attrName); System.out.println("HttpSession[Add attribute:"+attrName+",Attribute value:"+attrValue); } @Override public void attributeRemoved(HttpSessionBindingEvent se) { System.out.println("HttpSession[Delete attribute:"+se.getName()); } @Override public void attributeReplaced(HttpSessionBindingEvent se) { String attrName = se.getName(); Object attrValue = se.getSession().getAttribute(attrName); System.out.println("HttpSession[Replace attribute:"+attrName+",Attribute value:"+attrValue); } //request @Override public void attributeAdded(ServletRequestAttributeEvent srae) { String attrName = srae.getName();//The name of the property currently being operated on Object attrValue = srae.getServletRequest().getAttribute(attrName); System.out.println("ServletRequest[Add attribute:"+attrName+",Attribute value:"+attrValue); } @Override public void attributeRemoved(ServletRequestAttributeEvent srae) { System.out.println("ServletRequest[Delete attribute:"+srae.getName()); } @Override public void attributeReplaced(ServletRequestAttributeEvent srae) { String attrName = srae.getName(); Object attrValue = srae.getServletRequest().getAttribute(attrName); System.out.println("ServletRequest[Replace attribute:"+attrName+",Attribute value:"+attrValue); } }
-
Passivation and activation of session
Passivation: memory——>Hard disk Activation: hard disk——>Memory
-
There are four states of the session object:
Listening binding and unbinding: HttpSessionBindingListener(No configuration required web.xml) - session.setAttribute("a",xxx)Will object a Bind to session in - session.removeAttribute("a") Will object a from session [unbinding] monitor session Passivation and activation of objects: HttpSessionActivationListener(No configuration required web.xml) - passivation - activation
-
The binding and unbinding of session objects use jsp and servlet
BeanListener.java
package listener; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener; public class BeanListener implements HttpSessionBindingListener{ //binding @Override public void valueBound(HttpSessionBindingEvent event) { //this represents the bound object: a. System.out.println("binding Bean Object (will) Bean Object added to session Domain), bound object:"+this+",sessionId: "+event.getSession().getId()); } //Unbound @Override public void valueUnbound(HttpSessionBindingEvent event) { System.out.println("Unbound Bean Object (will) Bean Object added to session Domain), unbound object:"+this+"sessionId: "+event.getSession().getId()); } }
binding.jsp
<%@page import="listener.BeanListener"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% //Listening session object BeanListener bean = new BeanListener(); session.setAttribute("bean",bean);//binding //session.setAttribute("bean", the first bound object) //session.setAttribute("bean", second bound object) //The second bound object covers the first object, so when the second object is bound, the first object is unbound %> <!-- First entry: bound object listener.BeanListener@73527132 Object sessionId: 30BF7ECA7D98046854814786637B4C66 Refresh: Bind object: listener.BeanListener@45c38cac Object sessionId: 30BF7ECA7D98046854814786637B4C66 Unbind object: listener.BeanListener@73527132 Object sessionId: 30BF7ECA7D98046854814786637B4C66 --> </body> </html>
-
How to passivate and activate
to configure tomcat Under the installation directory conf Folder order context.xml File: Create a new label under the root directory: <Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1"> <!-- FileStore: The passivation operation is realized through this class directory: Relative path Relative to (absolute path)[D:\Program Files (x86)\eclipse\tomcat-9\work\Catalina\localhost\UpAndDown]) directory:"lq" This is equivalent to creating a new directory named lq Folder for --> <Store className="org.apache.catalina.session.FileStore" directory="lq"/> </Manager> Nature of passivation activation: serialization and deserialization: interface needs to be implemented: java.io.Serializable Summary: passivation and activation are passed during actual implementation context.xml For configuration in. Activation: session Get an object directly from a file in memory if it does not exist HttpSessionActivationListener Just responsible for session Monitor during passivation and activation. It also needs to be realized java.io.Serializable Interface.
-
jsp and servlet used for passivation and activation
BeanListener2.java
package listener; import java.io.Serializable; import javax.servlet.http.HttpSessionActivationListener; import javax.servlet.http.HttpSessionEvent; //Listen for passivation and activation of BeanListener2 objects public class BeanListener2 implements HttpSessionActivationListener,Serializable { //Prepare passivated and activated data private int num; private String user; public int getNum() { return num; } public void setNum(int num) { this.num = num; } public String getUser() { return user; } public void setUser(String user) { this.user = user; } //Monitoring time: before passivation @Override public void sessionWillPassivate(HttpSessionEvent se) { System.out.println("Before passivation: BeanListener2 Objects will follow session Passivation and passivation"); } //Monitoring time: just after activation @Override public void sessionDidActivate(HttpSessionEvent se) { System.out.println("After activation: BeanListener2 Objects will follow session Activated by the activation of"); } }
reade.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> Read from hard disk session Objects in domain (active)<br/> num: ${sessionScope.bean.num }<br/> user:${sessionScope.bean.user }<br/> </body> </html>
write.jsp
<%@page import="listener.BeanListener2"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <% BeanListener2 bean = new BeanListener2(); bean.setNum(10); bean.setUser("zs"); session.setAttribute("bean",bean); %> </body> </html>
-
configuration file
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>UpAndDown</display-name> <listener> <listener-class>listener.AttributeListener</listener-class> </listener> <listener> <listener-class>listener.BeanListener2</listener-class> </listener> <welcome-file-list> <welcome-file>InitServlet</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <description></description> <display-name>UploadServlet</display-name> <servlet-name>UploadServlet</servlet-name> <servlet-class>servlet.UploadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadServlet</servlet-name> <url-pattern>/UploadServlet</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>DownloadServlet</display-name> <servlet-name>DownloadServlet</servlet-name> <servlet-class>servlet.DownloadServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DownloadServlet</servlet-name> <url-pattern>/DownloadServlet</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>ElInitServlet</display-name> <servlet-name>ElInitServlet</servlet-name> <servlet-class>servlet.ElInitServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>ElInitServlet</servlet-name> <url-pattern>/ElInitServlet</url-pattern> </servlet-mapping> <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>servlet.MyServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/MyServlet</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>InitServlet</display-name> <servlet-name>InitServlet</servlet-name> <servlet-class>servlet.InitServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>InitServlet</servlet-name> <url-pattern>/InitServlet</url-pattern> </servlet-mapping> </web-app>