• JavaWeb总结


    环境配置

    Tomcat配置

    tomcat官网:http://tomcat.apache.org/

    配置环境变量

    • CATALINA_BASE tomcat的目录
    • CATALINA_HOME tomcat的目录
    • 在系统的path中配置 %CATALINA_HOME%in

    配置文件:conf文件夹下的server.xml

    可以配置启动的端口号

    • tomcat的默认端口号为:8080
    <Connector port="8081" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    

    可以配置主机的名称

    • 默认的主机名为:localhost->127.0.0.1
    • 默认网站应用存放的位置为:webapps
      <Host name="www.qinjiang.com"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
    

    Maven配置

    官网:https://maven.apache.org/

    配置环境变量

    • M2_HOME maven目录下的bin目录
    • MAVEN_HOME maven的目录
    • 在系统的path中配置 %MAVEN_HOME%in

    阿里云镜像

    conf文件夹下的settings.xml

    • 镜像:mirrors
      • 作用:加速我们的下载
    • 国内建议使用阿里云的镜像
    <mirror>
        <id>nexus-aliyun</id>  
        <mirrorOf>*,!jeecg,!jeecg-snapshots</mirrorOf>  
        <name>Nexus aliyun</name>  
        <url>http://maven.aliyun.com/nexus/content/groups/public</url> 
    </mirror>
    

    本地仓库

    建立一个本地仓库:localRepository

    <localRepository>D:Environmentapache-maven-3.6.2maven-repo</localRepository>
    

    web.xml版本问题

    修改web.xml版本问题(替换为4.0版本与tomcat一致)

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                          http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
             version="4.0"
             metadata-complete="true">
    </web-app>
    

    JavaWeb 常用依赖

    <!-- servlet依赖 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
        <scope>provided</scope>
    </dependency>
    <!-- jsp依赖-->
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>javax.servlet.jsp-api</artifactId>
        <version>2.3.3</version>
        <scope>provided</scope>
    </dependency>
    <!-- mysql依赖 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.47</version>
    </dependency>
    <!-- jstl表达式依赖 -->
    <dependency>
        <groupId>javax.servlet.jsp.jstl</groupId>
        <artifactId>jstl</artifactId>
        <version>1.2</version>
    </dependency>
    <!-- standard标签库 -->
    <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
    </dependency>
    

    Servlet

    ServletContext

    1、共享数据

    web容器在启动时,它会为每一个web应用程序都创建一个ServletContext对象,它代表当前web应用

    我在这个Servlet中保存的数据,可以在另外一个servlet中拿到;

    // 设置servlet的值
    ServletContext context = this.getServletContext();	//得到Servlet上下文
    String username = "小红"; //数据
    context.setAttribute("username",username); //将一个数据保存在了ServletContext中
    
    // 得到servlet中的值
    ServletContext context = this.getServletContext();
    String username = (String) context.getAttribute("username");
    resp.setContentType("text/html");
    resp.setCharacterEncoding("utf-8");
    resp.getWriter().print("名字"+username);
    

    2、获取初始化参数

    <!--配置一些web应用初始化参数-->
    <context-param>
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
    </context-param>
    
    ServletContext context = this.getServletContext();
    String url = context.getInitParameter("url");
    resp.getWriter().print(url);
    //jdbc:mysql://localhost:3306/mybatis
    

    3、请求转发

    ServletContext context = this.getServletContext();
    context.getRequestDispatcher("/gp").forward(req,resp);
    
    //RequestDispatcher requestDispatcher = context.getRequestDispatcher("/gp"); //转发的请求路径
    //requestDispatcher.forward(req,resp); //调用forward实现请求转发;
    

    4、读取资源文件

    Properties

    • 在java目录下新建properties
    • 在resources目录下新建properties

    发现:都被打包到了同一个路径下:classes,我们俗称这个路径为classpath:

    思路:需要一个文件流;

    username=root12312
    password=zxczxczxc
    
    public class ServletDemo05 extends HttpServlet {
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/kuang/servlet/aa.properties");
            Properties prop = new Properties();
            prop.load(is);
    		String user = prop.getProperty("username");
            String pwd = prop.getProperty("password");
            resp.getWriter().print(user+":"+pwd);
        }
    }
    

    HttpServletRequest

    1、设置字符编码

    req.setCharacterEncoding("utf-8");
    resp.setCharacterEncoding("utf-8");
    

    2、获取参数

    String username = req.getParameter("username");	//得到单个参数,返回字符串
    String password = req.getParameter("password");
    String[] hobbys = req.getParameterValues("hobbys");//得到多个参数,返回字符串数组
    

    3、请求转发

    req.getRequestDispatcher("/success.jsp").forward(req,resp);
    //与servletcontext请求转发相同,对象不同!
    

    HttpServletResponse

    1、实现重定向

    //重定向时候一定要注意,路径问题,否则404;
    resp.sendRedirect("/r/img");//重定向
    

    面试题:请你聊聊重定向和转发的区别?

    相同点

    • 页面都会实现跳转

    不同点

    • 请求转发的时候,url不会产生变化(307)
    • 重定向时候,url地址栏会发生变化(302)

    Cookie、Session

    保存会话的两种技术

    cookie

    • 客户端技术 (响应,请求)

    session

    • 服务器技术,利用这个技术,可以保存用户的会话信息? 我们可以把信息或者数据放在Session中!
    Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+""); //新建一个cookie
    cookie.setMaxAge(24*60*60); //设置cookie的有效期
    resp.addCookie(cookie); //响应给客户端一个cookie
    
    Cookie[] cookies = req.getCookies();	//得到cookie对象
    cookie.getName();	 //获得cookie中的key
    cookie.getValue(); 	//获得cookie中的vlaue
    

    注意点:

    • Cookie大小有限制4kb;

    • 一个Cookie只能保存一个信息;

    • Cookie一般会保存在本地的 用户目录下 appdata;

    删除Cookie:

    • 不设置有效期,关闭浏览器,自动失效;
    • 设置有效期时间为 0 ;

    编码解码:

    URLEncoder.encode("小红","utf-8")
    URLDecoder.decode(cookie.getValue(),"UTF-8")
    

    Session

    • 服务器会给每一个用户(浏览器)创建一个Seesion对象;
    • 一个Seesion独占一个浏览器,只要浏览器没有关闭,这个Session就存在;

    Session和cookie的区别:

    • Cookie是把用户的数据写给用户的浏览器,浏览器保存 (可以保存多个)
    • Session把用户的数据写到用户独占Session中,服务器端保存 (保存重要的信息,减少服务器资源的浪费)
    • Session对象由服务创建;
    //得到Session
    HttpSession session = req.getSession();
    //给Session中存东西
    session.setAttribute("name",new Person("小红",1));	//setAttribute
    //获取Session的ID
    String sessionId = session.getId();
    
    //判断Session是不是新创建
    if (session.isNew()){
        resp.getWriter().write("session创建成功,ID:"+sessionId);
    }else {
        resp.getWriter().write("session以及在服务器中存在了,ID:"+sessionId);
    }
    
    //    Session创建的时候做了什么事情;
    //    Cookie cookie = new Cookie("JSESSIONID",sessionId);
    //    resp.addCookie(cookie);
    
    //得到Session
    HttpSession session = req.getSession();
    Person person = (Person) session.getAttribute("name");	//getAttribute
    System.out.println(person.toString());
    //移除Session的值
    HttpSession session = req.getSession();
    session.removeAttribute("name");
    //手动注销Session
    session.invalidate();
    

    会话自动过期:web.xml配置

    <!--设置Session默认的失效时间-->
    <session-config>
        <!--15分钟后Session自动失效,以分钟为单位-->
        <session-timeout>15</session-timeout>
    </session-config>
    

    JSP

    JSP基础语法

    <%--jsp注释--%>		注释语句
    <%= 变量或者表达式%>		输出语句
    <%  jsp语句块 %>		代码编写
    <%!  jsp声明  %>		jsp声明部分
    

    JSP声明:会被编译到JSP生成Java的类中!其他的,就会被生成到 jspService 方法中!

    JSP指令

    <%@page args.... %>
    <%@include file=""%>
    <jsp:include page=""/>
    
    <%@include file="common/header.jsp"%>	会将多个个页面合二为一
    <jsp:include page="/common/header.jsp"/>	拼接页面,本质还是三个
    

    九大内置对象

    NO 内置对象 类型 功能
    1 pageContext javax.servlet.jsp.PageContext 页面上下文
    2 request javax.servlet.http.HttpServletrequest 请求
    3 response javax.servlet.http.HttpServletResponse 响应
    4 session javax.servlet.http.HttpSession 会话
    5 application javax.servlet.ServletContext 应用程序
    6 config javax.servlet.ServletConfig Servlet的配置信息
    7 out javax.servlet.jsp.jspWriter 数据流
    8 page java.lang.object 当前JSP的实例
    9 exception java.lang.Throwable 运行时的异常

    转自博客园:https://www.cnblogs.com/bekeyuan123/p/7071886.html

    pageContext.setAttribute("name1","小红1号"); //保存的数据只在一个页面中有效
    request.setAttribute("name2","小红2号"); //保存的数据只在一次请求中有效,请求转发会携带这个数据
    session.setAttribute("name3","小红3号"); //保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
    application.setAttribute("name4","小红4号"); //保存的数据只在服务器中有效,从打开服务器到关闭服器
    

    四大域

    四个域的作用域范围大小:PageContext (page域) < request < session < servletContext(application域)

    一、ServletContext

    1、生命周期:当Web应用被加载进容器时创建代表整个web应用的ServletContext对象,当服务器关闭或Web应用被移除时,ServletContext对象跟着销毁。

    2、作用范围:整个Web应用。

    3、常用功能:

      (a)在不同Servlet 之间转发

      (b)读取资源文件。

    二、Request 域

    1、生命周期:在service 方法调用前由服务器创建,传入service方法。整个请求结束,request生命结束。

    2、作用范围:整个请求链(请求转发也存在)。

    3、常用功能: 在整个请求链中共享数据。例如在Servlet 中处理好的数据交给Jsp显示,此时参数就可以放置在Request域中带过去。

    三、Session 域

    1、生命周期:在第一次调用 request.getSession() 方法时,服务器会检查是否已经有对应的session,如果没有就在内存 中创建一个session并返回。当一段时间内session没有被使用(默认为30分钟),则服务器会销毁该session。如果服务器非正常关闭(强行关闭),没有到期的session也会跟着销毁。如果调用session提供的invalidate(),可以立即销毁session。

    注意:服务器正常关闭,再启动,Session对象会进行钝化和活化操作。同时如果服务器钝化的时间在session 默认销毁时间之内,则活化后session还是存在的。否则Session不存在。如果JavaBean 数据在session钝化时,没有实现Serializable 则当Session活化时,会消失。

    2、作用范围:一次会话。

    3、常用功能:为浏览器创建独一无二的内存空间,在其中保存会话相关的信息。

    四、PageContext 域

    1、生命周期:当对JSP的请求时开始,当响应结束时销毁。

    2、作用范围:整个JSP页面,是四大作用域中最小的一个,即超过这个页面就不能够使用了。(所以使用pageContext对象向其它页面传递参数是不可能的.)

    3、常用功能:

      (1)获取其它八大隐式对象,可以认为是一个入口对象。

      (2)获取其所有域中的数据

      (3)跳转到其他资源,其身上提供了forward和include方法,简化重定向和转发的操作。

    转自博客园:https://www.cnblogs.com/leirocks/p/9132349.html

    Filter(重点)

    Filter 使用

    Filter:过滤器 ,用来过滤网站的数据;

    • 处理中文乱码
    • 登录验证….
    //1.实现 Filter(javax.servlet) 接口
    public class TestFilter implements Filter{
        //实现重写方法
    }
    
    //2.重写 init()、doFilter()、destroy()方法
    //3.doFilter方法中要加入,否则程序会被拦截停止
    	chain.doFilter(request,response); 
    

    在web.xml中配置 Filter

    <filter>
        <filter-name>TestFilter</filter-name>
        <filter-class>com.kuang.filter.TestFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>TestFilter</filter-name>
        <!--只要是 /servlet的任何请求,会经过这个过滤器-->
        <url-pattern>/servlet/*</url-pattern>
        <!--<url-pattern>/*</url-pattern>-->
    </filter-mapping>
    

    过滤器常见应用

    用户登录之后才能进入主页!用户注销后就不能进入主页了!

    1. 用户登录之后,向Sesison中放入用户的数据

    2. 进入主页的时候要判断用户是否已经登录;要求:在过滤器中实现!

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) resp;
    //Constant.USER_SESSION 为字符串常量,自行替换
    if (request.getSession().getAttribute(Constant.USER_SESSION)==null){
        response.sendRedirect("/error.jsp");	//重定向到错误页面
    }
    
    chain.doFilter(request,response);
    

    Junit单元测试

    依赖

    <!--单元测试-->
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
    </dependency>
    

    使用

    @Test注解只有在方法上有效,只要加了这个注解的方法,就可以直接运行!

    @Test
    public void test(){
        System.out.println("Hello");
    }
    

    本篇总结转载于B站狂神说Javahttps://space.bilibili.com/95256449

  • 相关阅读:
    poj 2352 Stars(线段树)
    poj 2029 Get Many Persimmon Trees
    .Net remoting 的解答,以及跟WebService的区别
    关于Xcode4.2中的release“不能”使用的理解
    委托的学习日志
    钩子是啥?以及用来说啥,是不是可以用来做即时通讯?
    C#后台程序与HTML页面中JS方法互调(功能类似于Ajax中的DWR)
    接触了一下项目管理系统软件:禅道项目管理软件、Bugfree
    将string变为int 的几种方法方法比较
    Hashtable、Dictionary、SortedDictionary、SortedList的比较应用
  • 原文地址:https://www.cnblogs.com/qiu-m/p/13178049.html
Copyright © 2020-2023  润新知