JavaWeb入门

JavaWeb

介绍

Web:网页

静态Web (HTML):从网页中获取的数据始终不变

动态Web(JSP、Servlet):可以从服务器端动态的获取数据;

在Java中 , 动态Web资源开发的技术统称为 JavaWeb;

Web应用程序

Web应用程序就是提供浏览器服务支持的一些程序

我们需要把自己开发出来的Web程序放在我们服务器的webapps目录下

发展

  • 静态Web

html,htm , 服务器会直接读取HTML的数据
JavaWeb入门_第1张图片
缺点:

  • 网页内容无法更新
  • 一些简单手段可以让他动起来
    • JavaScript
    • VBScript
  • 动态Web
    主要特征:可以从服务端获取数据,Web界面因人而变
    JavaWeb入门_第2张图片
    优点 :
  • 可以实现真正用户交互
  • 可以从服务端保证每个用户有自己的空间
  • 增强了用户体验性

常用Web服务器

1.IIS (微软)
2.Tomcat (性能优良,非常的小,他是符合Web服务器最小的服务器,Apache)3.WebLogic
4.WebShare

使用IDEA搭建Web开发环境

这里我们用Tomcat来演示
1.创建一个Web项目
JavaWeb入门_第3张图片
JavaWeb入门_第4张图片
JavaWeb入门_第5张图片
配置Tomcat
JavaWeb入门_第6张图片
JavaWeb入门_第7张图片
JavaWeb入门_第8张图片
JavaWeb入门_第9张图片
JavaWeb入门_第10张图片

Servlet

Sun公司在其API中提供了一个Servlet接口,用户若想要发一个动态Web资源,需要完成以下步骤:
1.编写一个Java类,实现Servlet接口
2.将开发好的Java类部署到Web服务器中

request

package com.kuang.servlet;

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 RequestDemo01 extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //查看request对象的方式
        System.out.println(request.getContextPath()); //获得web项目路径
        System.out.println(request.getRequestURI()); //请求的URL路径
        //Remote 远程
        System.out.println(request.getRemoteUser()); //获得远程的用户名
        System.out.println(request.getRequestedSessionId()); //获得SessionId;
        System.out.println(request.getServletPath()); //请求servlet的url
        System.out.println(request.getLocalAddr()); //获得本地地址  防火墙
        System.out.println(request.getLocalName()); //获得本地名字
        System.out.println(request.getLocalPort()); //获得访问的端口号

    }

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

Request对象接收前端用户提交的参数

写前端注册页面

  • 表单的提交方式 get/post
  • 表单提交的位置 action:服务项目的路径/servlet对应的请求url
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    注册




<%--
JSP的注释
--%>


<%--
Form表单
    action:代表要提交的路径,表单要提交到哪里 ,可以提交到一个Servlet
        //提交到Servlet需要,获取到Web项目的路径下的Servlet
    method: 提交表单的方式
--%>

注册

用户名:

密码:

写处理前端提交信息的Servlet

  • 接收前端传递的控件信息, request.getParameter(“控件的name‘)
package com.kuang.servlet;


import javax.print.attribute.HashPrintRequestAttributeSet;
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 RequestDemo02 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 {

        //通过HttpServletRequest获取前端用户提交的信息
        //req.getParameterValues(); 获得前端传递的控件信息,通过控件的name;但是可以接受多个参数的控件,比如(多选框....)
        //req.getParameter(); 获得前端传递的控件信息,通过控件的name;

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

        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //连接数据库,比较数据库中的信息是否匹配

        if (username.equals("admin")&&password.equals("1234567")){
            System.out.println("登录成功!"); //跳转到成功页面
        }else {
            System.out.println("登录失败!"); //提示重新注册
        }

        System.out.println(username);
        System.out.println(password);


    }
}

配置web.xml

  • 配置对应的XML文件

        RequsetDemo02
        com.kuang.servlet.RequestDemo02
    

    


    
        RequsetDemo02
        /r2
    

Request实现请求转发

package com.kuang.servlet;

import javax.servlet.RequestDispatcher;
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 FormServlet1 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");
        //处理前端的请求
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        System.out.println("接收到的用户名:"+username+"\n密码:"+password+"\n爱好:");

        String[] hobbies = req.getParameterValues("hobby");

        for (String hobby : hobbies) {
            System.out.println(hobby);
        }


        //重定向:服务器告诉客户端你应该请求另外一个地址;  (地址栏会变)
        //resp.sendRedirect("url");

        //转发:服务器把这个请求转向另外一个Servlet去处理; (地址栏不会变)
        //RequestDispatcher ,需要使用RequestDispatcher来进行处理,我们需要获得这个类
        //参数就是他要转发到的页面

        /*
        RequestDispatcher requestDispatcher = req.getRequestDispatcher("/success.jsp");
        requestDispatcher.forward(req,resp);
        */

        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        req.getRequestDispatcher("/success.jsp").forward(req,resp);


    }
}

Reponse

通过servletContext对象读取网站配置文件

新建一个properties文件

driver=com.mysql.jdbc.Driver
username=root
password=123456
url=jdbc:mysql://localhost:3306/smbms

编写servlet类

package com.kuang.servlet;

import javax.servlet.ServletException;
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.util.Properties;

//读取properties配置文件
public class ServletDemo03 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 {
        //读取配置文件

        //1.获得配置文件的路径
        String realPath = this.getServletContext().getRealPath("/WEB-INF/classes/resources/database.properties");
        System.out.println("取得的路径为:"+realPath);

        Properties properties = new Properties();
        FileInputStream is = new FileInputStream(realPath);

        properties.load(is);//把文件流加载到配置文件的对象中;

        String driver = properties.getProperty("driver");
        String username = properties.getProperty("username");
        String password = properties.getProperty("password");
        String url = properties.getProperty("url");


        //响应到网页
        resp.getWriter().println(driver);
        resp.getWriter().println(username);
        resp.getWriter().println(password);
        resp.getWriter().println(url);

        //=======================================
        System.out.println(driver);
        System.out.println(username);
        System.out.println(password);
        System.out.println(url);



    }
}

配置web.xml


    Demo03
    com.kuang.servlet.ServletDemo03



    Demo03
    /q3

Cookie

构造器 :
Cookie cookie = new Cookie(String name,String value);
Cookie cookie = new Cookie(String name,String value);
Cookie cookie = new Cookie(String name,String value);
服务器响应cookie给客户端
Response.addCookie(Cookie);
Response.addCookie(Cookie);
Response.addCookie(Cookie);
服务查看用户带来的请求是否有cookie
Cookie[] cookies = Request.getCookie();
//可以使用cookie来验证用户是否来过
//判断cookies是否为空,然后遍历即可
Cookie.getName();
Cookie.getValue();

cookie测试用户是否来过

package com.westos.serlvet;

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

public class CookieTest extends HttpServlet {

    boolean flag = false;

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

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //解决乱码问题:
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        //检查请求的人是否带了Cookie
        //通过用户的请求,检查它是否有cookie
        Cookie[] cookies = request.getCookies();
        System.out.println("cookie:"+cookies);


        if (flag){//如果flag是真,来过
            if (cookies!=null){//你有cookie
                for (int i = 0; i < cookies.length ; i++) {
                    Cookie cookie = cookies[i];
                    if (cookie.getName().equals("lastLoginTime")){
                        response.getWriter().println("你上一次来的时间为:"+cookie.getValue());
                        System.out.println("刷新了cookie");
                    }
                }
            }
        }else { //如果flag是真,没来过
            response.getWriter().println("你是第一次来,还想要会员套餐");
            System.out.println("给该用户一个cookie");
        }

        //建立一个cookie
        Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");

        //设置cookie保存的时间 //cookie.setMaxAge();
        //把这个cookie发给客户端
        response.addCookie(cookie);

        //response.addCookie(new Cookie("lastLoginTime",System.currentTimeMillis()+""));
        flag = true;


    }
}

Session

只要客户端一旦连接上服务器,服务器就会自动产生Session;

一个连接对应一个session,session可以在一个会话中传递信息;

通过setAttribute设置值。

通过getAttribute获得值。

由服务器端控制,服务器如果重启了,信息就会丢失!

package com.westos.serlvet;

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

public class SessionTest 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");
        //Session由服务器自动创建,如何获得session

        //HttpSession 得到的sessioin对象
        HttpSession session = req.getSession();

        //得到sessionID,一次会话,一个seesionID;
        String id = session.getId();
        resp.getWriter().println("获得的sessionId:\n"+id);


        String name = "qinjiang";
        //向session中存入一个值;
        session.setAttribute("name",name);
        resp.getWriter().println("存入信息成功:"+name);

    }




}
package com.westos.serlvet;

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

//获得session存入的值
public class SessionTest2 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");

        //获得
        HttpSession session = req.getSession();
        System.out.println("得到的SessionID:"+session.getId());


        String name = (String) session.getAttribute("name");
        resp.getWriter().println("得到的session存入的信息"+name);

        //Servlet  <  Seesion  <  WebContext

    }
}

会话注销

session.invalidate();//通过代码注销会话



    1

你可能感兴趣的:(JavaWeb入门)