JavaWeb
Static Web resources (such as HTML pages) : The data in a Web page for people to browse is always the same.
Dynamic Web resources: The data in a Web page for people to browse is generated by the program, and the content of the Web page is different at different points in time.
Static Web resource development techniques: HTML, CSS, JavaScript.
Dynamic Web resource development technology: JSP/Servlet, ASP, PHP, etc. In Java, dynamic Web resource development techniques are collectively known as the Java Web.
The Web server
Technical advice
ASP: Microsoft, the earliest domestic popular is ASP, embedded in THE HTML VB script, ASP+COM, high maintenance costs.
PHP: fast development, powerful, cross-platform, simple code, but can’t handle heavy traffic (limitations).
JSP/Servlet: SUN’s B/S architecture, based on the Java language, can carry three high problems (high concurrency, high availability, high performance).
B/S: browser and server; C/S: client and server.
The Web server
The server is used to process some requests from the user, and gives the user some data in response.
IIS: Microsoft, mainly used in ASP, Windows built-in server.
* * Tomcat: **Tomcat is a core project of the Apache Software Foundation’s Jakarta project. The latest Servlet and JSP specifications are always present in Tomcat. Tomcat 5 supports the latest Servlet 2.4 and JSP 2.0 specifications. Because of its advanced technology, stable performance, and free, Tomcat is deeply loved by Java enthusiasts and recognized by some software developers, and has become a popular Web application server.
Tomcat server is a free open source Web application server, belongs to lightweight application server, in small and medium-sized systems and concurrent access users are not many occasions is widely used, is the first choice for developing and debugging JSP programs. For a JavWeb beginner, is the best choice.
Tomcat actually runs JSP pages and servlets.
Tomcat
To install Tomcat, download the package from the official website and decompress it to a specified directory (optional: Configure environment variables).
Bat in the bin directory to start the startup, and enter localhost:8080 in the web address box.
How the site is accessed:
- Enter the user name and press Enter
- Check the local C:\Windows\System32\drivers\etc\hosts configuration file for this domain name mapping
- If yes, return the corresponding IP address directly
- If you don’t find one, look for it on the DNS server. If you find one, return
Http
Http (Hypertext Transfer Protocol) : Http is a simple request-response protocol that typically runs on top of TCP. (Default port: 80)
Https: 443
- Http1.0: A client can connect to a Web server and only get one Web resource, disconnecting.
- Http1.1: A client can connect to a Web server and obtain multiple Web resources.
The Http request
- Client —- Sends requests to —- server
Take Baidu as an example:
Request URL: https://www.baidu.com/ Request Address Request Method: GET Request Method Status Code: 200 OK Status Code Remote Address: 180.101.49.11:443 Remote address Referrer Policy: no-referreer-when - remustCopy the code
The Http response
- Server —- Sends requests to —- client
Baidu’s response:
Cache-control: private Cache Control Connection: keep-alive Content-Encoding: gzip Encoding Content-Type: text/ HTML; Charset = utf-8 typeCopy the code
Request method:
Get: A request can carry a small number of parameters with a limited size. The parameters are displayed in the browser address bar, which is insecure but efficient.
Post: There is no limit on the size of the parameters that can be carried by the request. The content of the parameters will not be displayed in the browser address bar, which is secure but inefficient.
Response status code:
200: The request response succeeded
3** : Requests redirection
404: Resource not found
500: server code error, 502: gateway error
Maven
Maven: Project architecture management tool that automatically imports JAR packages (convention > configuration).
After downloading Maven, decompress it, configure environment variables, set the path of the bin directory to path, enter MVN -version in CMD, and check whether the configuration is successful
Conf directory < setting >
D: \ Environments \ apache maven – 3.6.3 \ maven repo
In conf directory under the setting to configure ali cloud mirror
<! Maven </id> <mirrorOf> Central </mirrorOf> <name> Aliyun </name> <url>https://maven.aliyun.com/repository/public/</url> </mirror>Copy the code
pom.xml
Pom.xml: The core configuration file for Maven
Since the maven convention is larger than the configuration, the configuration file we write later may not be exported or not take effect, so we need to configure resouce under maven configuration.
Servlet
Servlet is a technology for sun Company to develop dynamic Web. Sun company provides an interface called servlet in THE API. If you need to develop a servlet program, you need to write a class to realize the servlet interface, and then deploy the developed Java class to the Web server.
HelloServlet
Sun has two default implementation classes for the Servlet interface: HttpServlet and GenericServlet
-
Create a Maven project, delete the SRC project, and then create a new Model. The empty project is maven’s main project.
-
Maven parent-child Project:
There will be in the parent project
<modules>
<module>servlet-01</module>
</modules>
Copy the code
Subprojects have
<parent>
<artifactId>javaweb-02-servlet</artifactId>
<groupId>com.zr</groupId>
<version>1.0-SNAPSHOT</version>
</parent>
Copy the code
-
Maven environment optimization: Update web.xml to the latest to complete Maven’s architecture.
-
Write a common class to implement the Servlet interface, inherit HttpServlet.
public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //ServletOutputStream outputStream = resp.getOutputStream(); PrintWriter writer = resp.getWriter(); // Response flow writer.println("Hello Servlet"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); }}Copy the code
- Write a Servlet mapping: We are writing a Java program, but we need to access it through a browser, and the browser connects to the Web server, so we need to register our Servlet with the Web server and give it a path that the browser can access.
<! - the registration Servlet - > < Servlet > < Servlet - name > hello < / Servlet - name > < the Servlet class - > com. Zr.. Servlet HelloServlet < / Servlet class - > </servlet> <! Servlet request path --> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern> </servlet-mapping>Copy the code
- Configure Tomcat
- Start the test
The Servlet principle
A Servlet is invoked by a Web server. Upon receiving the request, the Web server:
Mapping
-
A Servlet can specify a mapping path
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> Copy the code
-
A Servlet can specify multiple mapping paths
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello2</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello3</url-pattern> </servlet-mapping> Copy the code
-
A Servlet can specify a generic mapping path
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello/*</url-pattern> </servlet-mapping> Copy the code
-
The default request
<servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping> Copy the code
-
A Servlet can specify suffix or prefix mapping paths
<! ZZR </url-pattern> </url-pattern> ZZR </url-pattern> </servlet-mapping>Copy the code
Priority issues:
The default mapping path is specified, which has the highest priority. If it cannot be found, the request will be processed by default.
Handling 404 pages
<! --404--> <servlet> <servlet-name>error</servlet-name> <servlet-class>com.zr.servlet.ErrorServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>error</servlet-name> <url-pattern>/*</url-pattern> </servlet-mapping>Copy the code
ServletContext
When the Web container is started, it creates a ServletContext object for each Web application, which represents the current Web application.
-
Shared data
The data I save in one Servle is available in the other
public class HelloServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("hello"); //this.getInitParameter(); //this.getServletConfig(); //this.getServletContext(); ServletContext context = this.getServletContext(); String username = "week "; context.setAttribute("username",username); // Save a data in ServletContext}}Copy the code
public class GetServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); String username = (String) context.getAttribute("username"); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html"); Resp.getwriter ().println(" name: "+username); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }Copy the code
<servlet> <servlet-name>hello</servlet-name> <servlet-class>com.zr.servlet.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> <servlet> <servlet-name>get</servlet-name> <servlet-class>com.zr.servlet.GetServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>get</servlet-name> <url-pattern>/get</url-pattern> </servlet-mapping> Copy the code
Test access results
-
Gets initialization parameters
<! <context-param> <param-name>url</param-name> <param-value>jdbc:mysql://localhost:3306/mybaits</param-value> </context-param> <servlet> <servlet-name>gp</servlet-name> <servlet-class>com.zr.servlet.ServletDemo03</servlet-class> </servlet> <servlet-mapping> <servlet-name>gp</servlet-name> <url-pattern>/gp</url-pattern> </servlet-mapping>Copy the code
public class ServletDemo03 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); String url = context.getInitParameter("url"); resp.getWriter().println(url); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); }}Copy the code
-
Forward requests
public class ServletDemo04 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { ServletContext context = this.getServletContext(); RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp"); / / forwarding request path requestDispatcher. Forward (the req, resp); Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doPost(req, resp); }}Copy the code
<servlet> <servlet-name>sd4</servlet-name> <servlet-class>com.zr.servlet.ServletDemo04</servlet-class> </servlet> <servlet-mapping> <servlet-name>sd4</servlet-name> <url-pattern>/sd4</url-pattern> </servlet-mapping> Copy the code
-
Reading resource files
properties
- Create propreties in the Java directory (resources need to be configured under POM.xml)
- Create new Properties under the Resources directory
The discovery is packaged into the target class directory, which we call the classpath.
public class ServletDemo05 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties"); Properties properties = new Properties(); properties.load(is); String username = properties.getProperty("username"); String password = properties.getProperty("password"); resp.getWriter().println("username:"+username); resp.getWriter().println("password:"+password); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
<servlet> <servlet-name>sd5</servlet-name> <servlet-class>com.zr.servlet.ServletDemo05</servlet-class> </servlet> <servlet-mapping> <servlet-name>sd5</servlet-name> <url-pattern>/sd5</url-pattern> </servlet-mapping> Copy the code
<build> <resources> <resource> <directory>src/main/resources</directory> <excludes> <exclude>**/*.properties</exclude> <exclude>**/*.xml</exclude> </excludes> <filtering>true</filtering> </resource> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>true</filtering> </resource> </resources> </build> Copy the code
Db. Properties username=root password=123456Copy the code
HttpServletResponse
The Web server receives an HTTP request from the client, and for this request creates an HttpServletRequest object representing the request, representing an HttpServletResponse.
- If you want to get the argument from the client: HttpServletRequest
- If you want to give the client response some information: HttpServletResponse
Simple classification
The method responsible for sending data to the browser
ServletOutputStream getOutputStream() throws IOException;
PrintWriter getWriter() throws IOException;
Copy the code
The method responsible for sending the response header to the browser
void setCharacterEncoding(String var1);
void setContentLength(int var1);
void setContentLengthLong(long var1);
void setContentType(String var1);
void setDateHeader(String var1, long var2);
void addDateHeader(String var1, long var2);
void setHeader(String var1, String var2);
void addHeader(String var1, String var2);
void setIntHeader(String var1, int var2);
void addIntHeader(String var1, int var2);
Copy the code
The status code of the response
int SC_OK = 200; . int SC_MULTIPLE_CHOICES = 300; int SC_BAD_REQUEST = 400; int SC_UNAUTHORIZED = 401; int SC_PAYMENT_REQUIRED = 402; int SC_FORBIDDEN = 403; int SC_NOT_FOUND = 404; . int SC_INTERNAL_SERVER_ERROR = 500; int SC_BAD_GATEWAY = 502;Copy the code
The download file
-
Output a message to the browser
-
The download file
- Gets the path to the downloaded file
- Download file name
- Let the browser support downloading what we need
- Gets the input stream for the downloaded file
- Creating a buffer
- Get the OutputStream object
- Writes the FileOutputStream to the buffer buffer
- Outputs objects in the OutputStream buffer to the client
public class FileServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1\. String realPath = "D:\ IDEACode\\javaweb-02-servlet\\ Response \\ SRC \main\ resources\ 1.png "; System.out.println(" realPath: "+realPath); String fileName = realPath.subString (realPath.lastIndexof ("\\") + 1); //2\. // 2 \. Let browser support download what we need resp.setheader (" content-disposition ","attachment; filename="+fileName); FileInputStream in = new FileInputStream(realPath); //4\. Int len = 0; byte[] buffer = new byte[1024]; ServletOutputStream out = resp.getOutputStream(); While (len=in.read(buffer))>0){if (len=in.read(buffer)) { out.write(buffer,0,len); } in.close(); out.close(); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
Verification code function
How to generate captcha:
- The front end
- Back end: Need to use Java image class, generate a picture
public class ImageServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// Let the browser refresh resp.setheader ("refresh","5"); / / create pictures BufferedImage image = new BufferedImage (300, 60, BufferedImage. TYPE_INT_RGB); G = image.getgraphics (); // pen // set the background Color of the picture g.setcolor (color.green); G.f illRect,0,300,60 (0); G.setcolor (color.magenta); g.setFont(new Font(null,Font.BOLD,70)); G.d rawString (makeNum (), 0 '); // The browser opens resp.setContentType("image/ PNG ") as an image; // There is a cache on the site. Disallow the browser to cache resp.setDateHeader(" Expires ",-1); resp.setHeader("Cache-Control","no-cache"); resp.setHeader("Pragma","no-cache"); Boolean write = imageio. write(image," JPG ",resp.getOutputStream()); } // Generate Random number private String makeNum(){Random Random = new Random(); String num = random.nextInt(9999999) + ""; StringBuffer sb = new StringBuffer(); for (int i = 0; i < 7-num.length(); i++) { sb.append("0"); } num = sb.toString()+num; return num; } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
<! - the registration Servlet - > < Servlet > < Servlet - name > image < / Servlet - name > < the Servlet class - > com. Zr. Servlet. ImageServlet < / Servlet class - > </servlet> <! Servlet request path --> <servlet-mapping> <servlet-name>image</servlet-name> <url-pattern> </servlet-mapping>Copy the code
Implement redirection
void sendRedirect(String var1) throws IOException; / / redirectionCopy the code
public class RedirectServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /* resp.setHeader("Location","/r/image"); resp.setStatus(302); */ resp.sendRedirect("/r/image"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
Configure the web.xml test
The difference between redirection and forwarding:
Similarities: All pages will jump
Difference:
- When requesting a forward, the URL does not change 307
- The URL address bar will change when redirected
index.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <body> <h2>Hello World! < / h2 > < % - submit the path of the need to find the path to the current project - % > < form action = "${pageContext. Request. ContextPath} / login" method = "post" > username: <input type="text" name="username"> <input type="password" name="password"><br> <input type="submit"> </form> </body> </html>Copy the code
success.jsp
<%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>success</h1> </body> </html>Copy the code
public class RequestTest extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {system.out.println (" Enter the request "); String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println("username:"+username); System.out.println("password:"+password); resp.sendRedirect("/r/success.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
<! - the registration Servlet - > < Servlet > < the Servlet name - > test < / Servlet - name > < the Servlet class - > com. Zr. Servlet. RequestTest < / Servlet class - > </servlet> <! --Servlet request path --> <servlet-mapping> <servlet-name>test</servlet-name> <url-pattern> </servlet-mapping>Copy the code
HttpServletRequest
HttpServletRequest represents the request from the client. The user accesses the server through HTTP protocol. All information in the HTTP request is encapsulated in HttpServletRequest.
public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doPost(req, resp); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { req.setCharacterEncoding("utf-8"); resp.setCharacterEncoding("utf-8"); String username = req.getParameter("username"); String password = req.getParameter("password"); String[] hobbys = req.getParameterValues("hobbys"); System.out.println("=================================="); System.out.println(username); System.out.println(password); System.out.println(Arrays.toString(hobbys)); // Request forward // the/here represents the current Web application req.getrequestDispatcher ("/success.jsp").forward(req,resp); }}Copy the code
index.jsp
<%@ page contentType="text/html; Charset =UTF-8" language=" Java "%> < HTML > <head> <title> Center "> < form action =" ${pageContext. Request. ContextPath} / login "method =" post "> username: <input type="text" name="username"><br> <input type="checkbox" name="hobbys" value=" sing "> Sing <input type="checkbox" name="hobbys" value=" girl "> Girl <input Type ="checkbox" name="hobbys" value=" write "> Write <input type="checkbox" name="hobbys" value=" code "> code <br> <input type="submit"> </form> </div> </body> </html>Copy the code
success.jsp
<%@ page contentType="text/html; Charset =UTF-8" language=" Java "%> < HTML > <head> <title> title </title> </head> <body> <h1> Login successful </h1> </body> </ HTML >Copy the code
web.xml
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.zr.servlet.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
Copy the code
Cookie, Session
cookie
- Client technology (response, request)
session
- Server technology, we can store the user’s session information, we can put information or data in the session
Common application: After logging in to a website once, you can directly access it next time.
Cookie
Retrieve cookie information from the request
The server responds to the client with a cookie
Public class CookieDemo01 extends HttpServlet {@override protected void doGet(HttpServletRequest, HttpServletResponse resp) throws ServletException, IOException {// Req. setCharacterEncoding(" UTF-8 "); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html; charset=utf-8"); PrintWriter out= resp.getWriter(); [] cookies = req.getcookies (); // Check whether cookies exist if (cookies! =null){// If out.write(" The last time you accessed it was: "); for (int i = 0; i < cookies.length; i++) { Cookie cookie = cookies[i]; If (cookie.getName().equals(" lastLoginTime ")){// Get the cookie value long lastLoginTime = Long.parseLong(cookie.getValue()); Date date = new Date(lastlogintime); out.write(date.toLocaleString()); }}}else{out.write(" This is your first time to visit this site!" ); Cookie = new cookie (" lastLoginTime ", system.currentTimemillis ()+""); Cookie. setMaxAge(24*60*60); resp.addCookie(cookie); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
web.xml
<servlet>
<servlet-name>CookieDemo01</servlet-name>
<servlet-class>com.zr.servlet.CookieDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieDemo01</servlet-name>
<url-pattern>/c1</url-pattern>
</servlet-mapping>
Copy the code
Cookie: generally, it is saved in the local user directory AppData.
- A cookie can only hold one piece of information
- A Web site can send multiple cookies to the browser, up to 20
- Cookie size is limited to 4KB
- The maximum number of cookie browsers is 300
Delete the cookie
- If you do not set the validity period, close the browser
- Set the validity period to 0
Session
The session:
-
The server creates a Session object for each user (browser)
-
A session monopolizes a browser and exists as long as the browser is not closed
-
After the user logs in, the whole website can be accessed, –> save the user’s information
The difference between session and cookie:
- Cookie is to write the user’s data to the user’s browser, the browser saves (can save more than one)
- Session is to write data to the user’s exclusive session, and the server saves (saves important information and reduces the waste of resources).
- The Session object is created by the server
Session saves data
package com.zr.pojo; public class Person { private String name; private int age; public Person() { } public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; }}Copy the code
public class SessionDemo01 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// Req. setCharacterEncoding(" UTF-8 "); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html; charset=utf-8"); Session = req.getSession(); Session. setAttribute("name",new Person(" week ",1)); String id = session.getid (); // Obtain the session ID. If (session.isnew ()){resp.getwriter ().write(" Session created successfully, ID: "+ ID); }else {resp.getwriter ().write(" Session already exists, ID: "+ ID); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
public class SessionDemo02 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {// Req. setCharacterEncoding(" UTF-8 "); resp.setCharacterEncoding("utf-8"); resp.setContentType("text/html; charset=utf-8"); Session = req.getSession(); Person person = (Person) session.getAttribute("name"); System.out.println(person); } @Overridejava protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
<servlet>
<servlet-name>SessionDemo01</servlet-name>
<servlet-class>com.zr.servlet.SessionDemo01</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionDemo01</servlet-name>
<url-pattern>/s1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>SessionDemo02</servlet-name>
<servlet-class>com.zr.servlet.SessionDemo02</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SessionDemo02</servlet-name>
<url-pattern>/s2</url-pattern>
</servlet-mapping>
Copy the code
Session manual logout
public class SessionDemo03 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { HttpSession session = req.getSession(); session.removeAttribute("name"); Session.invalidate (); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
Session logout Automatically
<! <session-config> <! </session-timeout> </session-config>Copy the code
JSP
What is a JSP
JSP: Java Server Pages, Java server-side interface, like servlets, for the development of dynamic Web technology.
The characteristics of
- Writing JSP is like writing HTML
- The difference between
- HTML only provides static data to the user
- JSP pages can embed Java code to provide dynamic data to the user
JSP principle
Inside the server, tomcat has a work directory where JSPS are eventually converted into Java classes, which are essentially servlets.
Index_jsp. Java source code
Public void _jspDestroy() {} public void _jspDestroy() {} public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)Copy the code
Determine the request
Some built-in objects
final javax.servlet.jsp.PageContext pageContext; / / page context javax.mail. Servlet. HTTP. HttpSession session = null; //session final javax.servlet.ServletContext application; //applicationContext final javax.servlet.ServletConfig config; //config javax.servlet.jsp.JspWriter out = null; //out final java.lang.Object page = this; //page Current page HttpServletRequest Request // Request HttpServletResponse respons // responseCopy the code
The added code in front of the output page
response.setContentType("text/html"); / / set the response type of page pageContext. = _jspxFactory getPageContext (this, request, response, null, true, 8192, true); _jspx_page_context = pageContext; application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); _jspx_out = out;Copy the code
The above objects can be used directly in a JSP
In a JSP page, Java code is printed as it is, and HTML code is converted to out.write(“…..”). );
JSP Basic Syntax
Any language has its own syntax. JSP, as an application of Java technology, has some of its own expanded syntax (understand). It supports all Java syntax.
JSP expressions
< % - JSP expressions output to the client time - % > < % = new Java. Util. The Date () % >Copy the code
JSP script snippet
<%-- JSP script fragment --%> <% int sum=0; for (int i = 0; i < 100; i++) { sum+=i; } out.println("<h1>sum="+sum+"</h1>"); % >Copy the code
Re-implementation of script fragments
<% int x=10; out.print(x); </p> <% int y=20; out.print(y); %> <% for (int I = 0; i < 5; i++) { %> <h1>helloworld<%=i%></h1> <% } %>Copy the code
JSP declaration
The < %! static { System.out.println("loding..." ); } private int globalvar=0; Public void jspInit(){system.out.println (" enter method "); } % >Copy the code
JSP declarations: are compiled into Java classes generated by JSPS. Others will be generated into jspServer methods.
JSP comments are not displayed in the client source code, HTML comments are displayed in the source code.
Customizing error pages
<error-page>
<error-code>404</error-code>
<location>/error/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/500.jsp</location>
</error-page>
Copy the code
<%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <img src="img/500.jpg" alt="500"> </body> </html>Copy the code
JSP directive
<%@page% args... % > < % @ the include file = "" > < % - page 2 for one, will be % > < % @ the include file =" common/header. The JSP "% > < h1 > subject < / h1 > < % @ include File ="common/footer.jsp"%> <hr> <%-- JSP tag Mosaic page --%> < JSP :include page="common/header. JSP "/> <h1> body </h1> < JSP :include page="common/footer.jsp"/>Copy the code
Nine built-in objects
- The PageContext save things
- The Request to save things
- Response
- The Session to save things
- Application [ServletContext] saves things
- The config [ServletConfig]
- out
- page
- exception
Four scopes
< % - the built-in objects - % > < % pageContext. The setAttribute (" name1 ", "week 1"); Request. setAttribute("name2"," week 2"); // The saved data is valid for only one request, and the request forwarding will carry session.setAttribute("name3"," week 3"); // The saved data is valid for only one session, from opening the browser to closing the browser application.setAttribute("name4"," week 4"); // The saved data is valid on the server, Open the server to shut down the server % > < % - through the pageContext values - % > < % / / by looking for String name1 = (String) pageContext. FindAttribute (" name1 "); String name2 = (String) pageContext.findAttribute("name2"); String name3 = (String) pageContext.findAttribute("name3"); String name4 = (String) pageContext.findAttribute("name4"); String name5 = (String) pageContext.findAttribute("name5"); ${}--%> <h1> </h1> <h3>${name1}</h3> <h3>${name2}</h3> <h3>${name3}</h3> <h3>${name4}</h3> <h3>${name5}</h3> <hr> <%=name5%>Copy the code
Request: The client sends data to the server. The generated data, such as news, is useless after the user finishes reading it
Session: The client sends data to the server, generating data that the user will use later, such as a shopping cart
Application: The client sends data to the server. The generated data is used by one user, but may be used by other users, such as chat records
JSP tags, JSTL tags, EL expressions
<! JSTL </groupId> <artifactId> JSTL - API </artifactId> The < version > 1.2 < / version > < / dependency > <! GroupId <artifactId> Standard </artifactId> <version>1.1.2</version> </dependency>Copy the code
${}
- To get the data
- Perform operation
- Get common objects for Web development
JSP tags:
< % - the JSP: include -- % > < % - carry forward time parameters - % > < JSP: forward page = ". / jsptag2 JSP "> < JSP: param name =" name "value =" out "/ > < JSP: param name="age" value="22"/> </jsp:forward>Copy the code
JSTL expression
The JSTL tag library is used to make up for the deficiency of HTML tags. It has many custom tags that can be used by us, and the function of the tag is the same as Java code.
Core tag (master), format tag, SQL tag, XML tag
< % - the introduction of the JSTL core library - % > < % @ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" > %Copy the code
JSTL label usage procedure
- Import the corresponding taglib
- Use one of the methods
- The JSTL package must be imported into Tomcat; otherwise, a JSTL parsing error will be reported
c:if
<body> <h1>if test </h1> <hr> <form action="coreif.jsp" method="get"> <%-- the EL expression gets the data in the form ${param. Parameter name} - % > < input type = "text" name = "username" value = "${param. Username}" / > < input type = "submit" name = "login" > < / form > < % - --%> <c:if test="${param.username=='admin'}" var="isadmin"> <c:out value=" admin welcome you!" /> </c:if> <c:out value="${isadmin}"/> </body>Copy the code
c:choose
The < body > < % - define a variable score value of 88 - % > < c: set var = "score" value = "88" / > < c: choose > < c: when test = "${score > = 90}" > your excellent achievement! </c:when <c:when test="${score>=80}"> </c:when <c:when test="${score>=60}"> </c:when test="${score<=60}"> </c:when> </c:choose> </body>Copy the code
c:forEach
<body> <% ArrayList<String> people = new ArrayList<String>(); People. The add (0, "zhang"); People. The add (1, "bill"); People. The add (2, "detective"); People. The add (3, "Daisy"); People. The add (4, "panax notoginseng"); request.setAttribute("list",people); % > < % - var variables each traversal items each traversal of a % > < c: forEach var = "people" the items = "${list}" > < c: out value = "${people}" / > < br > < c: forEach > < hr > < % - start end step - % > < c: forEach var = "people" the items = "${list}" begin = "2" end = "4" step = "2" > < c: out value="${people}"/><br> </c:forEach> </body>Copy the code
JavaBean
Entity class
Javabeans are written in a specific way:
- There must be a no-parameter construct
- Attributes must be privatized
- There must be a corresponding get/set method
General used and database field mapping ORM;
ORM object relational mapping
- Table – > class
- Field > Properties
- Line record –> object
People watch
id | name | age | address |
---|---|---|---|
1 | Week 1 | 18 | wuhan |
2 | Week 2 | 22 | Guangzhou |
3 | Week 3 | 100 | foshan |
Create the Java entity class after the database fields are created
package com.zr.pojo; Public class People {private int id; public class People {private int id; private String name; private int age; private String address; public People() { } public People(int id, String name, int age, String address) { this.id = id; this.name = name; this.age = age; this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } @Override public String toString() { return "People{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", address='" + address + '\'' + '}'; }}Copy the code
<%@ page import="com.zr.pojo.People" %><%-- Created by IntelliJ IDEA. User: zr Date: 2020/10/11 Time: 22:08 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html; charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <% // People people = new People(); // people.setAddress(); // people.setId(); // people.setAge(); // people.setName(); < JSP :useBean id="people" class="com.zr.pojo. people" scope="page"/> < JSP :setProperty name="people" /> < JSP :setProperty name="people" property="id" value="1"/> Property ="age" value="18"/> < JSP :setProperty name="people" property="name" value="小周"/> < JSP :getProperty name="people" property="name"/> ID: < JSP :getProperty name="people" property="id"/> Age: < JSP :getProperty name="people" property="age"/> address: < JSP :getProperty name="people" property="address"Copy the code
MVC three-tier architecture
MVC: Model, View, Controller
Model
- Business processing, Business logic (Service)
- Data Persistence Layer, CRUD (Dao)
View
- Display data
- Provide operations to initiate Servlet requests (a, form, img….)
The Controller (Servlet)
- Receive the request, (REq: request parameters, session information…)
- Hand over the corresponding code to the business layer
- Controls the jump of the view
Login --> receive user login request --> process user request (get user login parameter username password) --> hand over business layer to process login business (judge whether username password is correct) -->Dao layer query user password is correct --> databaseCopy the code
The filter
9. A Filter used to Filter data from a website:
- Handle Chinese garbled characters
- Login verification…
Filter preparation: the first configuration Servlet, JSP dependency
Implement the Filter(Servlet) interface and override the corresponding method
Public class CharacterEncodingFilter implements Filter {CharacterEncodingFilter implements Filter { Public void init(FilterConfig FilterConfig) throws ServletException { System.out.println("CharacterEncodingFilter initialization "); system.out. println("CharacterEncodingFilter initialization "); } //Chain: Chain /* 1, all code in the filter will execute 2 when filtering a specific request. */ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8"); response.setContentType("text/html; character=UTF-8"); System.out.println("CharacterEncodingFilter executed before...." ); chain.doFilter(request,response); Println ("CharacterEncodingFilter executed after....") // Let our request continue if not written and the program is intercepted stop system.out. println("CharacterEncodingFilter executed after...." ); Public void destroy() {system.out.println ("CharacterEncodingFilter Destroy "); }}Copy the code
The servlet displays garbled characters
public class ShowServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //resp.setCharacterEncoding("utf-8"); //resp.setContentType("text/html"); Resp.getwriter ().write(" Hello world "); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
Configure web. XML
<servlet> <servlet-name>showServlet</servlet-name> <servlet-class>com.zr.servlet.ShowServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>showServlet</servlet-name> <url-pattern>/servlet/show</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>showServlet</servlet-name> <url-pattern>/show</url-pattern> </servlet-mapping> <filter> <filter-name>CharacterEncoding</filter-name> <filter-class>com.zr.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncoding</filter-name> <! -- Any request from /servlet will pass through this filter --> <url-pattern>/servlet/*</url-pattern> </filter-mapping>Copy the code
The listener
Statistics website online number:
Implements a listener interface
// Count the number of people online. Session Public class OnlineCountListener implements HttpSessionListener {// Create Session listener // This event is triggered once a Session is created public void sessionCreated(HttpSessionEvent se) { ServletContext ctx = se.getSession().getServletContext(); System.out.println(se.getSession().getId()); Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount"); if (onlineCount==null){ onlineCount = new Integer(1); }else { int count = onlineCount.intValue(); onlineCount = new Integer(count+1); } ctx.setAttribute("OnlineCount",onlineCount); Public void sessionDestroyed(HttpSessionEvent se) {ServletContext CTX = se.getSession().getServletContext(); Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount"); if (onlineCount==null){ onlineCount = new Integer(0); }else { int count = onlineCount.intValue(); onlineCount = new Integer(count-1); } ctx.setAttribute("OnlineCount",onlineCount); Se.getsession ().invalidate(); 2. The <session-config> */ configuration in the XML is automatically destroyedCopy the code
Display number of online users
<%@ page contentType="text/html; Charset =UTF-8" language=" Java "%> < HTML > <head> <title>$title $</title> </head> <body> <h1> Hotpink "><%=this.getServletConfig().getServletContext().getAttribute("OnlineCount")%></span> people online </h1> </body> </ HTML >Copy the code
Configure web. XML
<! - registered listeners - > < listener > < listener - class > com. Zr. Listener. OnlineCountListener < / listener - class > < / listener >Copy the code
Filters and listeners are common applications
Listeners are often used in GUI programming
GUI application
Public class TestPanel {public static void main(String[] args) {Frame Frame = new Frame(" happy Mid-Autumn Festival!" ); // Create a new window Panel Panel = new Panel(null); / / panel frame. SetLayout (null); // set the window's layout frame.setBounds(300,300,500,500); // frame. SetBackground (new Color(0,0,255)); // background color panel.setbounds (50,50,300,300); Panel. SetBackground (new Color (0255255)); frame.add(panel); frame.setVisible(true); // Listen event, Frame.addwindowlistener (new WindowAdapter() {@override public void windowClosing(WindowEvent e) { System.exit(0); }}); }}Copy the code
Users can access the home page only after login, but cannot access the home page after logout
1. After the user logs in, the user data is added to the session
2. When entering the home page, determine whether the user is logged in, requiring login.jsp to be implemented in the filter
Login.jsp (under web package)
<body> <h1> Login </h1> <form action=" /servlet/login" method=" POST "> <input type="text" name="username"> <input type="submit"> </form> </body>Copy the code
Success.jsp (web/sys package)
The < body > < h1 > home page < / h1 > < a href = "/ servlet/loginout" > logout < / a > < / body >Copy the code
Error.jsp (under web package)
Error of the < body > < h1 > < / h1 > < h3 > user name error < / h3 > < a href = "/ login JSP" > return to the login page < / a > < / body >Copy the code
Login
public class login extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String username = req.getParameter("username"); if (username.equals("admin")){ req.getSession().setAttribute("USER_SESSION",req.getSession().getId()); resp.sendRedirect("/sys/success.jsp"); }else { resp.sendRedirect("/error.jsp"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); }}Copy the code
LoginOut
public class LoginOut extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object user_session = req.getSession().getAttribute("USER_SESSION");
if (user_session!=null){
req.getSession().removeAttribute("USER_SESSION");
resp.sendRedirect("/login.jsp");
}else {
resp.sendRedirect("/login.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Copy the code
SysFilter: filter
public class SysFilter implements Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
filterChain.doFilter(request, response);
if (req.getSession().getAttribute("USER_SESSION")==null){
resp.sendRedirect("/error.jsp");
}
}
public void destroy() {
}
}
Copy the code
web.xml
<servlet> <servlet-name>login</servlet-name> <servlet-class>com.zr.servlet.login</servlet-class> </servlet> <servlet-mapping> <servlet-name>login</servlet-name> <url-pattern>/servlet/login</url-pattern> </servlet-mapping> <servlet> <servlet-name>loginOut</servlet-name> <servlet-class>com.zr.servlet.LoginOut</servlet-class> </servlet> <servlet-mapping> <servlet-name>loginOut</servlet-name> <url-pattern>/servlet/loginout</url-pattern> </servlet-mapping> <filter> <filter-name>CharacterEncoding</filter-name> <filter-class>com.zr.filter.CharacterEncodingFilter</filter-class> </filter> <filter-mapping> <filter-name>CharacterEncoding</filter-name> <! -- Any request for /servlet, All pass through this filter --> <url-pattern>/servlet/*</url-pattern> </filter-mapping> <filter> <filter-name>SysFilter</filter-name> <filter-class>com.zr.filter.SysFilter</filter-class> </filter> <filter-mapping> <filter-name>SysFilter</filter-name> <! <url-pattern>/sys/*</url-pattern> </filter-mapping>Copy the code
JDBC
Connect to database using mysql-connector-java
public class TestJdbc { public static void main(String[] args) throws ClassNotFoundException, SQLException {/ / configuration information String url = "JDBC: mysql: / / localhost: 3306 / JDBC? useUnicode=true&characterEncoding=utf8"; String username = "root"; String password = "123456"; // Load the Driver class.forname (" com.mysql.jdbc.driver "); / / connect to the database Connection Connection = DriverManager. GetConnection (url, username, password); / / send the database objects of SQL Statement Statement = connection. The createStatement (); SQL = "select * from users"; ResultSet rs = Statement.executeQuery (SQL); while (rs.next()){ System.out.println("id="+rs.getObject("id")); System.out.println("name="+rs.getObject("name")); System.out.println("password="+rs.getObject("password")); System.out.println("email="+rs.getObject("email")); System.out.println("birthday="+rs.getObject("birthday")); } // Close the connection rs.close(); statement.close(); connection.commit(); }}Copy the code
Precompiled SQL
public class TestJdbc2 { public static void main(String[] args) throws ClassNotFoundException, SQLException {/ / configuration information String url = "JDBC: mysql: / / localhost: 3306 / JDBC? useUnicode=true&characterEncoding=utf8"; String username = "root"; String password = "123456"; // Load the Driver class.forname (" com.mysql.jdbc.driver "); / / connect to the database Connection Connection = DriverManager. GetConnection (url, username, password); / / send the database objects of SQL Statement Statement = connection. The createStatement (); String sql = "insert into users(id,name,password,email,birthday) values(? ,? ,? ,? ,?) "; PreparedStatement preparedStatement = connection.prepareStatement(sql); PreparedStatement. SetInt (1, 4); PreparedStatement. SetString (2, "seven weeks"); preparedStatement.setString(3,"888888"); preparedStatement.setString(4,"[email protected]"); preparedStatement.setString(5, String.valueOf(new Date(new java.util.Date().getTime()))); int i = preparedStatement.executeUpdate(); If (I >0){system.out.println (" insert successfully "); } // Close the connection statement.close(); connection.commit(); }}Copy the code
The transaction
It’s all or nothing!
ACID principle to ensure data security.
Open the transaction
Transaction commit commi ()
Rollback ()
Close the transaction
Junit unit tests
Rely on
<! <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>Copy the code
Simple to use
The @test annotation is valid only for methods, and can be run as long as the method is annotated.
public class TestJdbc3 { @Test public void test(){ System.out.println("Hello"); }}Copy the code
Transfer transactions (create account table, field ID, name, money), using unit tests
Public class TestJdbc3 {@ Test public void Test () {/ / configuration information String url = "JDBC: mysql: / / localhost: 3306 / JDBC? useUnicode=true&characterEncoding=utf8"; String username = "root"; String password = "123456"; Connection connection=null; // Load Driver try {class.forname (" com.mysql.jdbc.driver "); / / connect to the database connection = DriverManager. GetConnection (url, username, password); // Tell the database to open the transaction connection.setautoCommit (false); String sql1 = "update account set money=money-100 where name='A'"; connection.prepareStatement(sql1).executeUpdate(); Int I =1/0; String sql2 = "update account set money=money+100 where name='B'"; connection.prepareStatement(sql2).executeUpdate(); connection.commit(); System.out.println(" Commit successfully! "); ); } catch (Exception e) {try {// If an Exception occurs, rollback transaction connection.rollback(); System.out.println(" Transfer failed!" ); } catch (SQLException throwables) { throwables.printStackTrace(); } e.printStackTrace(); }finally { try { connection.close(); } catch (SQLException throwables) { throwables.printStackTrace(); }}}}Copy the code
Original address: www.cnblogs.com/zhou-zr/p/1…