JavaWeb笔记:Servlet+JSP基础

Tomcat(9) :

多服务器:
复制服务器文件,修改conf中server.xml:

<Server port="8005" shutdown="SHUTDOWN"> <!-- 修改8005-->

<Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />    <!--修改8080-->

    <Connector protocol="AJP/1.3"
               address="::1"
               port="8009"
               redirectPort="8443" />   <!--修改8009-->   

配置虚拟路径:
1.修改conf中server.xml:(需要手动重启,缺省则path="")

 <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true">
<!--添加-->
<Context path="xxx1" docBase="C:\development\apps\app2"></Context>
        <!-- SingleSignOn valve, share authentication between web applications
             Documentation at: /docs/config/valve.html -->
        <!--
        <Valve className="org.apache.catalina.authenticator.SingleSignOn" />
        -->

        <!-- Access log processes all example.
             Documentation at: /docs/config/valve.html
             Note: The pattern used is equivalent to using pattern="common" -->
        <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
               prefix="localhost_access_log" suffix=".txt"
               pattern="%h %l %u %t &quot;%r&quot; %s %b" />

      </Host>

2.在conf/Catalina/localhost 目录下创建xml文件,文件名即为映射的虚拟路径,文件内容:(不用手动重启,缺省则ROOT.xml且需要重启,多级则文件名为b#c#d.xml映射为/b/c/d)

<Context docBase="C:\development\apps\app2"></Context>

网络资源访问流程:

JavaWeb笔记:Servlet+JSP基础

Servlet:

在WEB-INF中注册映射servlet:

    <servlet>
        <servlet-name>为该servlet类起的的别名</servlet-name>
        <servlet-class>servlet类名</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>刚刚起的别名</servlet-name>
        <url-pattern>/定义的映射url</url-pattern>
    </servlet-mapping>

同样也可以在java的servlet类前面声明:(name为别名,value为映射url)

@WebServlet(name = "ImplementsServlet", value = "/GoImplementsServlet")
public class ImplementsServlet implements Servlet {
……
}

ServletRequest存放的是用户请求的所有信息
ServletResponse存放的是服务器响应给浏览器所有信息

request
接口:
javax.servlet.ServletRequest
传递的实现类:
org.apache.catalina.connector.RequestFacade
关系:
public class RequestFacade implements HttpServletRequest
public interface HttpServletRequest extends ServletRequest .
结果:
RequestFacade–>HttpServletRequest–>ServletRequest.
response
接口:
javax.servlet.ServletResponsel
传递的实现类:
public class ResponseFacade implements HttpServletResponse
public interface HttpServletResponse extends ServletResponsel
结果:
ResponseFacade–>HttpServletResponse–>ServletResponse

1、GenericServlet类是所有Servlet类的祖先类,而且是抽象的。
2、HttpServlet类继承了GenericServlet类。
JavaWeb笔记:Servlet+JSP基础
response发送数据
1.字节流:

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        ServletOutputStream stream= response.getOutputStream();
        String data="字节流";
        //stream.print(data); 英文
        stream.write(data.getBytes(StandardCharsets.UTF_8));//中文
        //另一种中文方法为,getBytes方法无参数,但是要去掉response.setContentType参数中的utf-8
        //getBytes和浏览器都默认gbk编码
        //详见https://blog.csdn.net/wangyanming123/article/details/52266253/
        //总之统一编码
    }

2.字符流:

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");//中文必须设置utf-8或gbk
        PrintWriter out = response.getWriter();
        String dataString="字符流";
        out.print(dataString);
    }

两者不能同时使用,否则报错getOutputStream() has already been called for this response、getWriter() has already been called for this response
print()方法和write()方法区别:
http://www.bubuko.com/infodetail-3020111.html https://blog.csdn.net/pengshuai128/article/details/72676579?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromMachineLearnPai2-1.control
https://blog.csdn.net/paullinjie/article/details/80577155
request接收数据:

    public void doGet(HttpServletRequest request, HttpServletResponse response){
        request.setCharacterEncoding("UTF-8"); //统一编码(post必备)
        String user=request.getParameter("user");
        String pwd=request.getParameter("pwd");
        String[] hobby=request.getParameterValues("hobby");
        //获取数组(复选框)
        System.out.println(user);
        System.out.println(pwd);
        System.out.println(Arrays.toString(hobby));
    }

重定向:

 response.sendRedirect("./index.jsp");

转发:

   public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        RequestDispatcher dispatcher=request.getRequestDispatcher("GetServlet");
        dispatcher.forward(request,response);
        //dispatcher.include(request,response);
        //将转发的servlet结果加在当前servlet结果上,而不是用转发的替代当前的
    }

重定向和转发的区别
1.重定向可以访问当前的web资源,也可以访问其他web资源,转发只能访问当前的web资源
⒉跳转后request设置的值,重定向不能获取第一次的request,因为有两次请求,而转发能直接获取request,只有一次请求。
3.重定向url变了;转发url没有变化。
4.转发是在服务器端完成的,重定向是在客户端完成的。
5.转发的速度快,重定向速度慢
使用时机:
重定向:完成跳转
转发:数据传递

Cookie:
创建cookie:

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        Cookie mycookie=new Cookie("name",request.getParameter("user"));
        response.addCookie(mycookie);
        //response.sendRedirect("ReadCookie");
    }

获取cookie:

 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        Cookie[] getcookie=request.getCookies();
        if(getcookie!=null){
            for(Cookie cookie:getcookie){
                String itemname=cookie.getName();
                String itemvalue=cookie.getValue();
                System.out.println(itemname+":"+itemvalue);
            }
        }
    }

cookie持久化:

        mycookie.setMaxAge(60*60*24);//持久化
    }

cookie设置路径

        mycookie.setPath("/");

在读取cookie时,会读取当前页面路径及以上所有的cookie,但是不能读取下级
中文cookie:key-value中的key中文需要规定编码
创建时:

Cookie mycookie=new Cookie(URLEncoder.encode("姓名","utf-8") ,"张三");

读取时:

System.out.println(URLDecoder.decode(itemname,"utf-8")+":"+ itemvalue);

Session:
创建session:

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        HttpSession session=request.getSession();//调用即创建
        System.out.println(session);
        System.out.println(session.isNew());
        //session的key:JSESSIONID
    }

获取session:

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        HttpSession session=request.getSession();
        System.out.println(session.getId());
    }

可以利用自己创建cookie来使得session延时,session默认30分钟生存
当浏览器禁用cookie时想使用session:

 response.encodeRedirectURL(java.lang.String url) 
 //string类型,用于对sendRedirect方法后的url地址进行重写。
 response.encodeURL(java.lang.String url)
 //string类型,用于对表单action和超链接的url地址进行重写

例子:
验证码:

<form action="Judge" method="post">
    <input type="text" name="num">
    <img src="/servlet_war_exploded/Image">
    <input type="submit">
</form>

Image:

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        int width=80;int height=40;
        BufferedImage image =new BufferedImage (width,height,BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics () ;
        g.setColor (Color.white) ;//填充矩形
        g.fillRect (0, 0, width-2, height-2);
        String dataString="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";//设置字体
        g.setFont (new Font ("宋体",Font.BOLD,30));
        StringBuffer buf=new StringBuffer ();
        Random random=new Random ( ) ;
        for (int i = 0; i < 4; i++){
            g.setColor(new Color(random.nextInt (255), random.nextInt (255) , random.nextInt(255)));
            int index =random.nextInt (62);
            String str = dataString.substring(index, index+1);
            g.drawString(str,20*i,30);
            buf.append (str);
        }
        for (int i =0; i < 10; i++) {
            g.setColor(new Color(random.nextInt (255),random.nextInt (255) , random.nextInt (255)));
            g.drawLine(random.nextInt(width),random.nextInt(height), random.nextInt (width), random.nextInt(height));
        }
        HttpSession session = request.getSession () ;
        session.setAttribute("cap", buf.toString()) ;
        response.setContentType ( "image/ jpeg") ;
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

Judge:

public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer= response.getWriter();
        String num=request.getParameter("num");
        if(!num.equals("")){
            String cap=request.getSession().getAttribute("cap").toString();
            System.out.println(cap);
            System.out.println(num);
            if(num.equals(cap)) {
                writer.println("通过");
            }else {
                writer.println("未通过");
            }
        }else{
            writer.println("请输入");
        }
    }

异步:
https://www.cnblogs.com/davenkin/p/async-servlet.html需要搭配异步ajax使用。
过滤器监听器:
https://blog.csdn.net/duanyuwan/article/details/81391220
https://blog.csdn.net/qq_37084904/article/details/89309579

JSP:

编码区别:https://www.cnblogs.com/lllini/p/4433168.html
常用:

<%@ page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

JSP语法:

<% 代码片段 %>

或者

<jsp:scriptlet>
   代码片段
</jsp:scriptlet>

任何文本、HTML标签、JSP元素必须写在脚本程序的外面。
在这里声明的变量为局部变量,将会在最终servlet类的jspService类中进行try
声明最终类的全局变量方法:

<%! declaration; [ declaration; ]+ ... %>

或者,

<jsp:declaration>
   代码片段
</jsp:declaration>

表达式:

<%= 表达式 %>

或者

<jsp:expression>
   表达式
</jsp:expression>

注释:

语法 描述
<%-- 注释 --%> JSP注释,注释内容不会被发送至浏览器甚至不会被编译
<!-- 注释 --> HTML注释,通过浏览器查看网页源代码时可以看见注释内容
<\% 代表静态 <%常量
%\> 代表静态 %> 常量
\' 在属性中使用的单引号
\" 在属性中使用的双引号

JSP指令:

指令 描述
<%@ page ... %> 定义页面的依赖属性,比如脚本语言、error页面、缓存需求等等
<%@ include ... %> 包含其他文件
<%@ taglib ... %> 引入标签库的定义,可以是自定义标签

JSP隐式对象:
JavaWeb笔记:Servlet+JSP基础

上一篇:HttpServletResponse


下一篇:Spring MVC-拦截器