JavaWeb筆記
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">商城價:¥${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筆記