JavaWeb筆記

来源:http://www.cnblogs.com/Renyi-Fan/archive/2017/10/18/7684900.html
-Advertisement-
Play Games

JavaWeb筆記 一、servlet 真正helloServlet所在的位置 HelloServlet.java package net.zixue.servlet; import jdk.nashorn.internal.runtime.arrays.IteratorAction; import ...


JavaWeb筆記

一、servlet

 

 

真正helloServlet所在的位置

 

 

 

 

 

 

 

 

 

HelloServlet.java

package net.zixue.servlet;

 

import jdk.nashorn.internal.runtime.arrays.IteratorAction;

 

import javax.lang.model.element.NestingKind;

import javax.servlet.ServletConfig;

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.IOException;

import java.io.PrintWriter;

import java.util.Enumeration;

import java.util.Iterator;

import java.util.Map;

 

/**

 * Created by invinjun on 2017/5/25.

 */

public class HelloServlet extends HttpServlet{

 

    @Override

    public void init() throws ServletException {

        super.init();

        ServletConfig servletConfig = this.getServletConfig();

        String encoding = servletConfig.getInitParameter("encoding");

        System.out.println("encoding="+encoding);

    }

 

    @Override

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

        //獲取請求行

//        System.out.println("接收到get請求");

//        System.out.println("請求方式:"+request.getMethod());

//        System.out.println("URI:"+request.getRequestURI());

//        System.out.println("發出請求客戶端IP地址:"+request.getRemoteAddr());

//        System.out.println("服務點接收請求的IP地址:"+request.getLocalAddr());

//        System.out.println("訪問客戶端的埠號:"+request.getRemotePort());

//        System.out.println("web應用路徑:"+request.getContextPath());

//        System.out.println("http協議和版本:"+request.getProtocol());

//        //獲取請求頭

//        Enumeration<String> headerNames = request.getHeaderNames();

//        while (headerNames.hasMoreElements()){

//            String element = headerNames.nextElement();

//            System.out.println(element+":"+request.getHeader(element));

//        }

//

//       //獲取請求參數

//        String name = request.getParameter("name");

//        String passWord = request.getParameter("passWord");

//        System.out.println("用戶名:"+name);

//        System.out.println("密碼:"+passWord);

//

//       String result="恭喜您登錄成功";

////        ServletOutputStream outputStream = response.getOutputStream();

////        outputStream.write(result.getBytes());

//        response.setContentType("text/html;charset=utf-8");

//        PrintWriter writer = response.getWriter();

//        writer.write(result);

        request.setAttribute("name","123");

        request.getRequestDispatcher("/index.jsp").forward(request,response);

 

    }

 

    @Override

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("接收到post請求");

    }

}

 

 

 

web.xml

<?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_3_1.xsd"

         version="3.1">

 

    <session-config>

        <session-timeout>10</session-timeout>

    </session-config>

 

 

    <context-param>

    <param-name>encoding</param-name>

    <param-value>utf-8</param-value>

</context-param>

 

    <context-param>

        <param-name>encoding1</param-name>

        <param-value>utf-8</param-value>

    </context-param>

 

<servlet>

    <servlet-name>helloServlet</servlet-name>

    <servlet-class>net.zixue.servlet.HelloServlet</servlet-class>

 

 

</servlet>

 

    <servlet-mapping>

        <servlet-name>helloServlet</servlet-name>

        <url-pattern>/hi</url-pattern>

    </servlet-mapping>

</web-app>

 

 

二、cookie

 

 

 

 

 

 

 

 

 

TimeServlet.java

package net.zixue.cookie;

 

import javax.servlet.ServletException;

import javax.servlet.annotation.WebServlet;

import javax.servlet.http.Cookie;

import javax.servlet.http.HttpServlet;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

 

/**

 * Created by invinjun on 2017/6/9.

 */

@WebServlet(name = "TimeServlet", urlPatterns = "/time")

public class TimeServlet extends HttpServlet {

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

 

    }

 

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

 

 

        //記錄訪問時間並其通過cookie加入到響應頭

        Date date = new Date();

 

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd-hh:mm:ss");

        String time = simpleDateFormat.format(date);

 

        Cookie cookie = new Cookie("time", time);

        cookie.setMaxAge(60*60*24);

        response.addCookie(cookie);

        response.setContentType("text/html;charset=utf-8");

        //獲取客戶端瀏覽器發送過來的cookie數據

        Cookie[] cookies = request.getCookies();

        String timeValue = null;

        for (Cookie cookie1 : cookies) {

 

            if (cookie1.getName().equals("time")) {

                timeValue = cookie1.getValue();

            }

        }

        if (timeValue == null) {

            response.getWriter().write("歡迎您訪問我們的網站");

        } else {

            response.getWriter().write("您上次訪問網站的時間是:" + timeValue);

        }

 

 

    }

}

 

 

 

三、JSP

JSP做頁面,servlet做處理

JSP的9大內置對象

 

 

四、EL表達式+JSTL標簽

servlet獲取數據,傳給jsp頁面,jsp頁面顯示數據

 

 

 

 

PhoneListServlet.java

package net.zixue.JSP;

 

import net.zixue.bean.Phone;

 

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.io.IOException;

import java.util.ArrayList;

import java.util.List;

 

/**

 * Created by invinjun on 2017/6/16.

 */

@WebServlet(name = "PhoneListServlet",urlPatterns = "/phoneList")

public class PhoneListServlet extends HttpServlet {

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

 

    }

 

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

 

        //通過servlet從資料庫中獲取數據,我們這裡暫時通過手動創建數據

 

        Phone phone=new Phone();

        phone.setName("iphone6");

        phone.setId(001);

        phone.setImage("https://img10.360buyimg.com/n7/jfs/t277/193/1005339798/768456/29136988/542d0798N19d42ce3.jpg");

        phone.setPrice("3900");

 

        Phone phone1=new Phone();

        phone1.setName("堅果pro");

        phone1.setId(002);

        phone1.setPrice("1799");

        phone1.setImage("https://img13.360buyimg.com/n7/jfs/t5377/56/1578379545/209772/32105f74/5911bcbdN7afa707b.jpg");

 

        Phone phone2=new Phone();

        phone2.setName("vivo x9");

        phone2.setPrice("2345");

        phone2.setId(003);

        phone2.setImage("https://img12.360buyimg.com/n7/jfs/t6067/340/2101390376/231820/750cc50e/593aa83fN8b0829fc.jpg");

 

        Phone phone3=new Phone();

        phone3.setName("oppo A57");

        phone3.setId(004);

        phone3.setPrice("1399");

        phone3.setImage("https://img10.360buyimg.com/n7/jfs/t4978/185/135948089/78285/f6a84203/58db6fa4N354322d9.jpg");

 

        Phone phone4=new Phone();

        phone4.setName("諾基亞6");

        phone4.setId(005);

        phone4.setPrice("1699");

        phone4.setImage("https://img11.360buyimg.com/n7/jfs/t4930/86/192598423/86027/36a57ccf/58dcbfa5N5c41cbfd.jpg");

 

        Phone phone5=new Phone();

        phone5.setName("小米MIX");

        phone5.setId(006);

        phone5.setPrice("3999");

        phone5.setImage("https://img13.360buyimg.com/n7/jfs/t4264/215/455518113/309855/38fe41f1/58b4fc81N1d924112.jpg");

 

        List<Phone> list=new ArrayList<>();

        list.add(phone);

        list.add(phone1);

        list.add(phone2);

        list.add(phone3);

        list.add(phone4);

        list.add(phone5);

 

        request.setAttribute("list",list);

 

        request.getRequestDispatcher("/phone_list.jsp").forward(request,response);

 

 

    }

}

 

 

phone_list.jsp

<%--

  Created by IntelliJ IDEA.

  User: invinjun

  Date: 2017/6/16

  Time: 16:57

  To change this template use File | Settings | File Templates.

--%>

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

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

<html>

<head>

    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>商品列表</title>

    <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />

    <script src="js/jquery-1.11.3.min.js" type="text/javascript"></script>

    <script src="js/bootstrap.min.js" type="text/javascript"></script>

    <!-- 引入自定義css文件 style.css -->

 

 

</head>

 

<body>

 

<c:forEach items="${list}" var="phone">

 

    <div class="col-md-2" style="height:250px">

        <img src="${phone.image}" width="170" height="170" style="display: inline-block;">

        </a>

        <p>

            <a href="product_info.html" style='color: green'>${phone.name}</a>

        </p>

        <p>

            <font color="#FF0000">商城價:&yen;${phone.price}</font>

        </p>

    </div>

 

</c:forEach>

 

 

 

</body>

 

</html>

 

 

 

bootstrap.min.css(前30行)

/*!

 * Bootstrap v3.3.5 (http://getbootstrap.com)

 * Copyright 2011-2015 Twitter, Inc.

 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)

 */

/*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */

html {

    font-family: sans-serif;

    -webkit-text-size-adjust: 100%;

    -ms-text-size-adjust: 100%

}

 

body {

    margin: 0

}

 

article, aside, details, figcaption, figure, footer, header, hgroup,

    main, menu, nav, section, summary {

    display: block

}

 

audio, canvas, progress, video {

    display: inline-block;

    vertical-align: baseline

}

 

audio:not ([controls] ){

    display: none;

    height: 0

}

 

 

Phone.java

package net.zixue.bean;

 

/**

 * Created by invinjun on 2017/6/16.

 */

public class Phone {

 

    private int id;

    private String name;

    private String image;

    private String price;

 

    public int getId() {

        return id;

    }

 

    public void setId(int id) {

        this.id = id;

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public String getImage() {

        return image;

    }

 

    public void setImage(String image) {

        this.image = image;

    }

 

    public String getPrice() {

        return price;

    }

 

    public void setPrice(String price) {

        this.price = price;

    }

}

 

 

 

 

五、SQL註入

 

 

 

 

 

Login.java

package net.zixue.crud;

 

import net.zixue.utils.JDBCUtil;

 

import java.math.BigDecimal;

import java.sql.*;

 

/**

 * Created by Administrator on 2017/6/24.

 */

public class Login {

 

    public  void login(String account,String password) throws ClassNotFoundException, SQLException {

 

        Connection connection = JDBCUtil.getConnection();

        // 3.獲取操作資料庫的對象

        Statement statement = connection.createStatement();

 

        String sql="select * from user WHERE account='"+account+"' AND password='"+password+"'";

        ResultSet resultSet = statement.executeQuery(sql);

 

        // 4.  取出數據

        if (resultSet.next()){

            String name=resultSet.getString("nickname");

            System.out.println(name+"登錄成功" );

 

        }else{

            System.out.println("登陸失敗");

        }

 

        release(connection, statement, resultSet);

 

 

    }

 

    private void release(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {

        resultSet.close();

        statement.close();

 

        connection.close();

    }

 

    public  void login1(String account,String password) throws ClassNotFoundException, SQLException {

 

        Class.forName("com.mysql.jdbc.Driver");

 

        // 2.獲取資料庫連接

 

        String url="jdbc:mysql://localhost:3306/mall";

        Connection connection = DriverManager.getConnection(url, "root", "root");

 

        // 3.獲取操作資料庫的對象

//        Statement statement = connection.createStatement();

        String sql="select * from user WHERE account=? AND password=?";

        PreparedStatement preparedStatement = connection.prepareStatement(sql);

 

//        ResultSet resultSet = statement.executeQuery(sql);

        preparedStatement.setString(1,account);

        preparedStatement.setString(2,password);

        ResultSet resultSet = preparedStatement.executeQuery();

 

        // 4.  取出數據

        if (resultSet.next()){

            String name=resultSet.getString("nickname");

            System.out.println(name+"登錄成功" );

 

        }else{

            System.out.println("登錄失敗");

        }

 

        resultSet.close();

        preparedStatement.close();

 

        connection.close();

 

 

    }

 

}

 

LoginTest.java

package net.zixue.crud;

 

import org.junit.Test;

 

import static org.junit.Assert.*;

 

/**

 * Created by Administrator on 2017/6/24.

 */

public class LoginTest {

    @Test

    public void login() throws Exception {

        Login login=new Login();

        login.login1("xiaoming","123");

    }

 

}

 

 

JDBCUtil.java

package net.zixue.utils;

 

 

import java.io.IOException;

import java.io.InputStream;

import java.sql.*;

import java.util.Properties;

 

/**

 * Created by Administrator on 2017/6/24.

 */

public class JDBCUtil {

 

    private static String driver;

    private static String url;

    private static String username;

    private static String password;

//靜態代碼塊 初始化配置文件信息

 

  static {

        try {

        ClassLoader classLoader = JDBCUtil.class.getClassLoader();

        InputStream resourceAsStream = classLoader.getResourceAsStream("db.propertise");

        Properties properties=new Properties();

            properties.load(resourceAsStream);

            driver = properties.getProperty("driver");

            url = properties.getProperty("url");

            username = properties.getProperty("username");

            password = properties.getProperty("password");

 

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

 

    public static Connection getConnection() {

        Connection connection = null;

        //註冊驅動,獲取連接

        try {

            Class.forName(driver);

            connection = DriverManager.getConnection(url, username, password);

        } catch (Exception e) {

            e.printStackTrace();

        }

 

        return connection;

    }

 

 

    public static void release(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet) {

            //釋放資源

 

        if (resultSet != null) {

            try {

                resultSet.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

        }

 

        if (preparedStatement != null) {

            try {

                preparedStatement.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

        }

        if (connection != null) {

            try {

                connection.close();

            } catch (SQLException e) {

                e.printStackTrace();

            }

        }

 

 

    }

 

}

 

修改代碼很複雜,但是修改配置文件很簡單

還有就是註意一下上面為什麼使用靜態代碼塊

db.propertise

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/mall

username=root

password=root

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • int #數值(整數) str #字元串(文字) float #浮點(小數點) list #列表 print() #列印\輸出 len() #長度 max() #最大值 min() #最小值 del() #刪除元素 list.append(obj) #此語法中list代表列表,obj代表需要添加到l ...
  • PS:再次說明一下,原本不想寫的太啰嗦的,可之前那個系列發佈後發現,好多朋友都想馬上拿到代碼立即能上手開發自己的項目,對代碼結構、基礎常識、分類目錄與文件功能結構、常用函數......等等什麼都不懂,然後就想使用,我真的很無語,還有一些朋友有十幾年開發經驗也會問一些很基礎的問題,我都不知道怎麼回答了 ...
  • 一、簡介 阿裡巴巴於10月14日在杭州雲棲大會上,正式發佈了《阿裡巴巴Java開發規約》掃描插件!該插件基於《阿裡巴巴Java開發規約》手冊內容,在掃描代碼後,將不符合規約的代碼按Blocker/Critical/Major三個等級顯示在下方,甚至在IDEA上,還基於Inspection機制提供了實 ...
  • 簡述 寫這個工具主要目的在於減少工作量,bear在寫gitbook的時候,發現對應目錄一個一個寫進去,非常繁瑣,而且最近在學習python,所以,手癢之下寫了一個目錄生成的小工具。 工具使用 本身工具並不複雜,主要實現功能接受一個github中的raw版本的url,然後列印自動生成對應文件的mark ...
  • 本節內容 - 使用nm查看符號 - 使用readelf -s輸出符號信息 - 刪除符號表對反彙編的影響 - 使用strip刪除符號和調試信息 - 使用UPX壓縮並保護可執行文件 ...
  • spring boot / cloud (十九) 併發消費消息,如何保證入庫的數據是最新的? 消息中間件在解決非同步處理,模塊間解耦和,和高流量場景的削峰,等情況下有著很廣泛的應用 . 本文將跟大家一起討論以下其中的異常場景,如題. 場景 在實際工作中,大家可能也都遇到過這樣的需求 : 如 : 系統A ...
  • /p 問題描述 明明想在學校中請一些同學一起做一項問卷調查,為了實驗的客觀性,他先用電腦生成了N個1到1000之間的隨機整數(N≤100),對於其中重覆的數字,只保留一個,把其餘相同的數去掉,不同的數對應著不同的學生的學號。然後再把這些數從小到大排序,按照排好的順序去找同學做調查。請你協助明明完成 ...
  • 一、CURL小結 個人將歸納curl請求總結成三步 1、創建curl 句柄(curl_init),並設置參數(curl_setopt)(打開冰箱) 2、執行請求(curl_exec),處理返回的數據 (把大象塞進去) 3、關閉curl(curl_close),釋放所有資源(關上冰箱) 其實如果代碼看 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...