码迷,mamicode.com
首页 > 编程语言 > 详细

JavaWeb笔记

时间:2017-10-18 10:10:04      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:jpg   cut   contex   sch   ebs   jquer   ppi   简单   webkit   

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

 

JavaWeb笔记

标签:jpg   cut   contex   sch   ebs   jquer   ppi   简单   webkit   

原文地址:http://www.cnblogs.com/Renyi-Fan/p/7684900.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!