JavaWEB

HTML

  • html代码示例
<html>
    <title>
            //这里表示网页的标题
            Here We GO !!!
    </title>
    //这里设置的是浏览器解析网页时的编码格式
    <meta charset="utf-8" />
    //设置网页文字的颜色
    <body text="#0000ff" >
        //<i>表示斜体字
        //<a name="top">和代码最后面的<a href="#top"">返回顶部</a>相对应,代表页内跳转,相当于页内定位
        <i><a name="top">这是斜体字</a></i>
        //块的概念,需要先设置style,在其中设置对应块的属性值
        <style type="text/css">
            div#header{background-color:#ff0000;width:300px}
        </style>
        //块,id对应style中的对应块属性显示
        <div id="header">
        <p>这是一个段落</p>
        <p>这是一个段落</p>
        </div>
        //<p>代表文字段落
        <p>这是一个段落</p>
        //<sub>表示下角标
        <p>两个黄鹂<sub><a href="http://www.baidu.com">百度一下,你就知道</a></sub>鸣翠柳</p>
        //<sup>表示上角标
        <p>一行白鹭<sup>3</sup>上青天</p>
        <del>这是删除字段</del>
        //跳转链接
        <a href="http://www.baidu.com">百度一下,你就知道</a>
        //插入图片
        <img src="1.png" width="300" height="300"></img>
        //插入表格,border表示表格边框线的宽度,不设置就是没有边框线
        <table border="1">
        //<tr>表示行
        <tr>
            //<td>表示列
            <td>第一行第1列</td>
            <td>第一行第2列</td>
            <td>第一行第3列</td>
        </tr>
        <tr>
            <td>第1列</td>
            <td>第2列</td>
            <td>第3列</td>
        </tr>
        <tr>
            <td>第1列</td>
            <td>第2列</td>
            <td>第3列</td>
        </tr>
        </table>

        //清单,<ul>表示无序号列表
        <ul>
        <li>这是一个条目</li>
        <li>这是一个条目</li>
        <li>这是一个条目</li>
        </ul>

        //清单,<ol>表示无序号列表
        <ol>
        <li>这是一个条目</li>
        <li>这是一个条目</li>
        <li>这是一个条目</li>
        </ol>

        //页内定位,相当于业内跳转
        <a href="#top"">返回顶部</a>

    </body>
</html>
  • 表单html代码
<html>
    <meta charset="utf-8" />
    <title>
        欢迎来到登录界面
    </title>
    <body>
    <style type="text/css">
        div#test{background-color:#0000ff;margin:auto;width:300px}
    </style>
        //表示表单
        <form>
            <div id="test">
            Username:
            //表示输入框
            <input type="text" name="first">
            <br>
            Password:
            <input type="text" name="second">
            <br>
            //表示按钮,按钮上显示“Log In”
            <input type="button" name="bt1" value="Log In">
            </div>
        </form>
    </body>
</html>

JSP

  • JSP是在html中嵌入了java脚本
  • <% 此处允许写java代码 %>
  • <%@ 指令 %>
  • <% java的语句 %>
  • <%= 表达式,即要输出的内容 %>
  • <%! Java方法 %>
JSP执行过程

这里写图片描述

内置对象
  • 内置对象就类似于ava中的关键字,不必在new,可以直接使用
    这里写图片描述
//指定了文件的编码方式,各种属性
<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    你还好吗

    //在JSP中编写编写java方法,获取当前日期
    <%!public String getDate() {
        Date date = new Date();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String time = format.format(date);
        return time;
    }%>
    <!-- 这是会被发送的注释 -->
    <%-- 这是不会发送的注释 --%>
    当前的时间为:<%=getDate()%>
    <br>
    //编写java代码连接并获取数据库的数据
    //Jdbc放到lib文件夹下
    <%
        try {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("驱动加载成功");
            Connection conn = DriverManager.getConnection(
                    "jdbc:mysql://localhost:3306/school", "root", "123456");
            PreparedStatement statement = conn
                    .prepareStatement("select * from student");
            ResultSet set = statement.executeQuery();
            while (set.next()) {
            //内置关键字out的使用
                out.println("姓名:"+set.getString("sname"));
                out.println("                 密码:"+set.getString("spass"));
                out.println("班级:"+set.getString("class"));
                out.println("<br>");

            }

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    %>
</body>
</html>

Post和Get


  • Request 接收浏览器的form表单提交过来的数据
  • Form 表单提交数据的两种方式
  • get明文提交 ,会将提交的参数明文显示在url的后边 ?xxx=xxx&xxx=xxx&xxx=xxx
  • post 隐式提交,提交的参数不会显示在url中

转发和重定向的区别

转发 服务器内部的跳转,url不改变
重定向 客户端浏览器url的重新访问,url会改变

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    欢迎来带登录界面
    <form action="user.jsp" method="post">
        用户名:<input type="text" name="user_name">
        <br>
        密&nbsp&nbsp码:<input type="text" name="password">
        <br>
        <input type="submit" value="登录">
    </form>
</body>
</html>

<%@page import="java.text.SimpleDateFormat"%>
<%@page import="java.util.Date"%>
<%@page import="java.sql.*"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <%
        request.setCharacterEncoding("UTF-8");
        String name=request.getParameter("user_name");
        String password=request.getParameter("password");
        if(name.equals("zhangsan")){
        //转发
            RequestDispatcher rd=request.getRequestDispatcher("success.html");
            rd.forward(request,response);
            out.clear();
            out=pageContext.pushBody();
        }else{
        //重定向
            response.sendRedirect("fail.html");
        }
    %>
</body>
</html>


<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    登陆成功
</body>
</html>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    登录失败
</body>
</html>

客户端和服务器端的交互

知识点
  • Web项目中,要导入的jar包,除了要build path 导入之外,还要讲需要用的的jar包,拷贝到WEB-INF文件夹中的lib文件夹下。牢记牢记牢记
    Get提交数据的时候,就调用的servlet中的doGet方法
    Post 提交数据的时候,就调用的servlet中的dogPost方法

  • 要将jdbc的jar文件拷贝到apache-tomcat-8.0.27的lib文件夹下D:\apache-tomcat-8.0.27\lib

  • 无论是get提交还是post提交都必须设置这些参数
    HttpURLConnection对象
    设置超时时间
    设置提交方法
    设置提交数据的编码格式
    打开输入输出流

get方式提交数据
  • 客户端代码
logInBtn.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
            //首先获取要提交的数据,如用户名,密码
                String name = nameText.getText();
                String password = passwordText.getText();
                System.out.println("用户名:" + name);
                System.out.println("密码:" + password);
                //拼接url,因为是get显式提交,故将要提交的数据拼接在url后面即可,最好将服务器的地址http://localhost:8080/MyFirWEB/写成Properties配置文件
                String urls = "http://localhost:8080/MyFirWEB/CheckServlet?user=" + name + "&password=" + password;
                URL url;
                try {
                    url = new URL(urls);
                    //获取连接对象
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    //设置连接的属性,包括超时时间,get提交方式,提交数据的编码格式
                    conn.setConnectTimeout(1000);
                    conn.setRequestMethod("GET");
                    conn.setRequestProperty("Accept-Charset", "utf-8");
                    //获取返回码,200表示正确连接成功,其他连接失败
                    int code = conn.getResponseCode();
                    //获取连接的输入流,获取服务器返回信息
                    BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                    String line=br.readLine();
                    if (code == HttpURLConnection.HTTP_OK) {
                        System.out.println("连接网络成功");
                        //根据服务器返回的不同信息,执行不同的操作
                        if ("用户名密码错误".equals(line)) {
                            BackDialog.create(line);
                        }
                    } else {
                        System.out.println("连接网络失败");
                    }
                } catch (MalformedURLException e1) {
                    e1.printStackTrace();
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
  • WEB项目中的服务器端servlet代码
protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("gbk");
        //获取数据库的连接对象
        Connection conn = ConnectionFactory.newInstance().createConnection();
        //根据客户端拼接的url通过request获取数据,用户名密码
        String name = request.getParameter("user");
        String password = request.getParameter("password");
        try {
        //数据库预编译指令,通过数据库的操作,来与数据库中的数据进行对比,在执行其他一系列操作
            PreparedStatement statement = conn
                    .prepareStatement("select count(*) from student where user_name=? and user_password=?");
            statement.setString(1, name);
            statement.setString(2, password);
            //通过对查询结果的resultset对象进行判断,
            ResultSet set = statement.executeQuery();
            set.first();
            // 以 Java 编程语言中 int 的形式获取此 ResultSet 对象的当前行中指定列的值。
            // columnIndex - 第一个列是 1,第二个列是 2,……
            // 列值;如果值为 SQL NULL,则返回值为 0
            int num = set.getInt(1);
            //获取response的输出流对象,将服务器的信息返回到客户端
            PrintWriter out=response.getWriter();
            if (num < 1) {
                System.out.println("用户不存在");
                out.println("用户名密码错误");
            } else {
                System.out.println("登陆成功");
                out.println("登陆成功");
            }
            //最后,记得关闭set和输出流
            set.close();
            out.flush();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

-服务器端的数据库连接对象应用了数据库连接池,数据库连接池的配置,请参见MySQL数据库中的数据库连接池的配置方法

POST方式提交数据
  • 客户端代码
//创建json用来存储数据,再将其转换为字符串返回
private String postJsonData(String name,String pass){
        JSONObject data=new JSONObject();
        data.accumulate("username", name);
        data.accumulate("password", pass);
        JSONObject obj=new JSONObject();
        obj.accumulate("type", "login");
        obj.accumulate("data", data);
        return "json="+obj.toString();
    }


btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String name=nameText.getText();
                String password=passwordText.getText();


                String urls="http://localhost:8080/ZWEB/CheckServlet";
                try {
                    URL url=new URL(urls);
                    HttpURLConnection conn=(HttpURLConnection) url.openConnection();
                    //改为POST提交方式
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                    conn.setDoInput(true);
                    conn.setConnectTimeout(1000);
                    conn.setRequestProperty("Accept-Charset", "utf-8");
        //将创建的json数据转化为的字符串用connection对象的输出流,发送给服务器         
                conn.getOutputStream().write(postJsonData(name, password).getBytes());
                    int code=conn.getResponseCode();
                    String respon="";
                    if (code==HttpURLConnection.HTTP_OK) {
                        System.out.println("网络连接成功");
                        BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
                        String line=br.readLine();
                        while (line!=null) {
                            respon+=line;
                            line=br.readLine();
                        }
                        System.out.println(respon);
                    }else {
                        System.out.println("网络连接失败");
                    }
                    if ("用户名密码错误 !!!".equals(respon)) {
                        ErrorDialog.create();
                    }
                } catch (MalformedURLException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }

            }
        });
  • 服务器代码
protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setCharacterEncoding("GBK");
        PrintWriter out = response.getWriter();
        //通过request获取到客户端发送过来的数据
        String jsonString = request.getParameter("json");
        //造型为json对象,将其中的数据分别取出
        JSONObject obj = JSONObject.fromObject(jsonString);
        //根据其中传递的参数不同,如type,执行不同的sql语句
        String type = obj.getString("type");
        try {
            if ("login".equals(type)) {
                JSONObject data = obj.getJSONObject("data");
                String name = data.getString("username");
                String password = data.getString("password");
                int isSuccess=checkLogin(out, name, password);
                switch (isSuccess) {
                case LOGIN_SUCCESS:
                    System.out.println("登陆成功");
                    break;
                case LOGIN_ERR_USERNAME:
                    System.out.println("用户名错误");
                    break;
                case LOGIN_ERR_PASSWORD:
                    System.out.println("密码错误");
                    break;
                }

            } else if ("newuser".equals(type)) {

            } else if ("forget".equals(type)) {

            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private int checkLogin(PrintWriter out, String name, String password) throws SQLException {
        String sql=null;
        sql="select count(*) from student where sname=?";
        String[] array=new String[1];
        array[0]=name;
        int num=selectNum(sql, array);
        if (num < 1) {
            // 用户名不存在
            return LOGIN_ERR_USERNAME;
        } else {
            sql="select count(*) from student where sname=? and spass=?";
            array=new String[2];
            array[0]=name;
            array[1]=password;
            num=selectNum(sql, array);
            if (num < 1) {
                // 密码错误
                return LOGIN_ERR_PASSWORD;
            } else {
                // 登陆成功
                return LOGIN_SUCCESS;
            }

        }
    }

    public int selectNum(String sql,String array[]) throws SQLException{
        Connection conn=ConnectionFactory.newInstance().creat();
        PreparedStatement statement=conn.prepareStatement(sql);
        for (int i = 0; i < array.length; i++) {
            statement.setString(i+1, array[i]);
        }
        ResultSet set=statement.executeQuery();
        set.first();
        int num=set.getInt(1);
        return num;
    }



    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

特别注意
- post数据中,有些特殊字符需要转义,例如+ & %等等,不这样处理的话,数据传递的时候后出现错误
str=str.replace(“+”, “%2B”);
str=str.replace(“%”, “%25”);
str=str.replace(“&”, “%26”);

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值