JavaWeb

PrintWriter

这个类可以创建一个在网页中写东西的对象

PrintWriter writer = resp.getWriter();
writer.print("你好!");

servlet:

继承HttpServlet类,重写doGet和doPost方法。使用resp来响应内容或则HTML等。

web.xml

对所写的Java文件与网页进行映射

  <servlet>
    <servlet-name>hello</servlet-name>		//和下面的hello要一样。
    <servlet-class>com.kuang.servlet.HelloServlet</servlet-class> //Java文件存放的位置
  </servlet>
  
  <servlet-mapping>
    <servlet-name>hello</servlet-name>		//和上面的hello一致
    <url-pattern>/hello2</url-pattern>		//在浏览器中输入的路径
  </servlet-mapping>

ServletContext

相当于可以对所有的servlet进行一个管理(前提是servlet中的数据被写入了ServletContext中),通过get放入,通过se取出。
set:

 String username = "cling";
        ServletContext context = this.getServletContext();
        context.setAttribute("username",username);

get

     ServletContext context = this.getServletContext();
        String username = (String) context.getAttribute("username");

通过ServletContext在Java文件中获取web.xml中的参数信息。

ServletContext context = this.getServletContext();
        String url2 =  context.getInitParameter("url"); 		//url是web.xml中的参数。不是servlet中的。
        PrintWriter writer = resp.getWriter();
        writer.print(url2);

请求转发

当A想去请求C 的时候,只有通过B这个中介去完成,B就把A的请求转发给 C,C在通过B转发给A。
在这里插入图片描述

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        context.getRequestDispatcher("/demo03").forward(req,resp); 	//想通过的demo04(此类)去访问demo03。
    }

读取resources资源文件

首先需要确定资源文件在加载后的位置(也就是要写服务器上的相对路径),
在这里插入图片描述

 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = this.getServletContext();
        InputStream inputStream = context.getResourceAsStream("./WEB-INF/classes/db.properties");    //获取资源的流
        Properties prop = new Properties();
        prop.load(inputStream);         //加载流文件
        String userName =  prop.getProperty("username");    //获取资源中的信息
        String pwd = prop.getProperty("pwd");
        resp.getWriter().print(userName+""+pwd);
    }

浏览器中下载服务器的文件

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

public class FileServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       String realPath = "F:\\IDEA_project\\javaweb-02-servlet\\servlet-02\\target\\classes\\援军.png";
       int index = realPath.lastIndexOf("\\");
       String fileName = realPath.substring(index+1);
        resp.setHeader("Content-disposition","attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));


        FileInputStream in = new FileInputStream(realPath);

        ServletOutputStream out = resp.getOutputStream();
        int temp = 0;
        byte[] buffer = new byte[1024];
        while ((temp=in.read(buffer))!=-1){
            out.write(buffer,0,temp);
        }
        out.close();
        in.close();
        System.out.println("over!");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

输出验证码


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;


import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.OutputStream;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;

import sun.java2d.loops.DrawLine;

/**
 * 输出随机的验证码
 */
@WebServlet({ "/CheckCode", "/checkCode.jpg" })
public class ImageServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /* 宽度 */
    private final int WIDTH = 200;
    /* 高度 */
    private final int HEIGHT = 40;
    /* 生成验证码的个数 */
    private final int COUNT = 4;
    /* 干扰线条数 */
    private final int LINE_ROW = 6;

    /* 输出的基本码表,如果使用中文,则使用utf-8的码表,类似 \ue234 ,而且应该使用常用字,避免出现偏僻字 */
    private final char[] BASECODE = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
            'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
            'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
            'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9' };

    // 写出数据
    private void write(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        HttpSession session = request.getSession();

        BufferedImage image = new BufferedImage(WIDTH, HEIGHT,
                BufferedImage.TYPE_INT_RGB);
        Graphics graphics = image.getGraphics();

        setBackground(graphics);
        drawBorder(graphics);
        drawDot(graphics);
        drawLine(graphics);
        drawString(graphics, session);

        // 写出数据流
        ImageIO.write(image, "jpg", response.getOutputStream());

    }

    // 写字
    private void drawString(Graphics graphics, HttpSession session) {
        StringBuffer sb = new StringBuffer();
        Random random = new Random();

        graphics.setFont(new Font("宋体", Font.BOLD, 18));
        graphics.setColor(Color.BLACK);

        for (int i = 0; i < COUNT; i++) {
            String ch = String
                    .valueOf(BASECODE[random.nextInt(BASECODE.length)]);
            sb.append(ch);

            // 设置位置
            int x = i * 20 + random.nextInt(12) + 10;
            int y = random.nextInt(HEIGHT / 3) + 12;

            // 旋转字体
            double theta = Math.PI / 180 * random.nextInt(20);
            // rotate(graphics, theta);

            graphics.drawString(ch, x, y);

            // 恢复。。
            // rotate(graphics, -theta);
        }
        session.setAttribute("checkCode", sb.toString());

        System.out.println("   验证码:" + sb.toString());
    }

    // 旋转
    private void rotate(Graphics graphics, double theta) {
        ((Graphics2D) graphics).rotate(theta);
    }

    // 画随机线条
    private void drawLine(Graphics graphics) {
        Random random = new Random();
        for (int i = 0; i < LINE_ROW; i++) {
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);
            setRandomColor(graphics);
            graphics.drawLine(x1, y1, x2, y2);
        }
    }

    // 画斑点
    private void drawDot(Graphics graphics) {
        Random random = new Random();
        graphics.setColor(Color.red);
        for (int i = 0; i < WIDTH; i++) {
            int x = i;
            int y = random.nextInt(HEIGHT);
            int r = random.nextInt(2);
            // graphics.fillOval(x, y, r, r);
            graphics.drawOval(x, y, r, r);
        }
    }

    // 画边框
    private void drawBorder(Graphics graphics) {
        graphics.setColor(Color.BLACK);
        graphics.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);
    }

    // 设置背景
    private void setBackground(Graphics graphics) {
        graphics.setColor(Color.WHITE);
        graphics.fillRect(0, 0, WIDTH, HEIGHT);// 填充背景色
    }

    // 设置随机的画笔颜色
    private void setRandomColor(Graphics g) {
        Random random = new Random();
        g.setColor(new Color(random.nextInt(255), random.nextInt(255), random
                .nextInt(255)));
    }

    protected void doGet(HttpServletRequest request,
                         HttpServletResponse response) throws ServletException, IOException {

        // 输出图片流的头信息
        response.setContentType("image/jpeg");
        response.setHeader("Expires", "-1");
        response.setHeader("Cache-Control", "no-cache");

        // 写出数据
        write(request, response);

    }

    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

重定向(Redirect)

URL地址会改变。
在这里插入图片描述

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RedirectServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.sendRedirect("/servlet_02_war/image");         //项目的报名加上要跳转的路径
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

获取浏览器的参数

index.jsp

<%--一定要加上下面这句话,否则在控制台中输出的中文是乱码--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>

<%--注意美元符号--%>
<form action=${pageContext.request.contextPath}/login method="get" >
    username: <input type="text" name="username"><br/>
    password: <input type="password" name="password"><br/>
    <input type="submit">
</form>
</body>
</html>

LoginServlet

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");         //注意是req
        System.out.println(username+":"+password);
        resp.sendRedirect("/servlet_02_war/success.jsp");       //注意是写xml中的路径
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}

Session

    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");

        HttpSession session = req.getSession();
        session.setAttribute("person",new person(3,"cling"));

        String sessionId = session.getId();

        if (session.isNew()){
            resp.getWriter().print("新创建的sessionID是:"+sessionId);
        }else{
            resp.getWriter().print("已经存在的sessionID是:"+sessionId);
        }
        session.invalidate();       //手动注销session,也可以在web.xml中设置自动注销
    }

session和cookie的区别

Cookie是把用户的数据写给用户的浏览器,浏览器保存(可以保存多个)
Session把用户的数据写到用户独占 Session中,服务器端保存(保存重要的信息,減少服务器资源的浪费)
Session对象由服务创建;

jsp中的错误类型页面的跳转

第一种方法,在可能出错的页面中的头部放入以下要跳转的页面

<%@ page errorPage="505.jsp" %>

第二种方法

错误的jsp页面的代码

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>404</title>
</head>
<body>
<img src="./img/404.png" alt="404">         //这里记得必须使用一个点
</body>
</html>

在web.xml中的配置

    <error-page>
        <error-code>404</error-code>
        <location>/error/404.jsp</location>
    </error-page>

建议使用第二种

添加公用的头部和尾部

但是第一个会和公用的jsp公用变量。
第二个就没有公用变量。所以说建议使用第二个
在这里插入图片描述# JSP内置对象的作用域

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

#JSP标签
jsp转发:

<jsp:forward page="/jsptag2.jsp">
    <jsp:param name="name" value="cling"/>
    <jsp:param name="age" value="3"/>
</jsp:forward>

jsptag2

姓名:<%=request.getParameter("name")%>
年龄:<%=request.getParameter("age")%>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值