day1
|
新建項目javascript
選擇mavencss
組織名與項目名html
位置,完成java
容許自動導入包node
添加框架支持,變換成web項目mysql
選擇web applicationjquery
若是沒有Web-INF程序員
添加Web容器支持,tomcatweb
添加tomcat面試
設置tomcat屬性
設置虛擬目錄
運行
添加一個Servlet
新建個一個用於存放servlet的包com.tax.action
結果
建立一個servlet
添加Servlet依賴的包
選擇要依賴的環境
修改Servlet類,結果以下:
package com.tax.action; import java.io.IOException; import java.io.PrintWriter; //註解,訪問路徑 @javax.servlet.annotation.WebServlet("/HiServlet") public class HiServlet extends javax.servlet.http.HttpServlet { protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { doGet(request,response); } protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException { //設置HTTP內容類型 response.setContentType("text/html;charset=utf-8"); //得到輸出對象 PrintWriter out=response.getWriter(); //向客戶端響應一串字符 out.println("<h2>Hello Servlet!</h2>"); } }
運行結果:
reg.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html> <head> <title>用戶註冊</title> <meta charset="UTF-8" /> </head> <body> <form method="post" action="Reg"> <h2>用戶註冊</h2> <p> 姓名:<input type="text" name="name"/> </p> <p> 愛好: <input type="checkbox" name="hobby" value="運動"/>運動 <input type="checkbox" name="hobby" value="電影"/>電影 <input type="checkbox" name="hobby" value="閱讀"/>閱讀 </p> <p> <input type="submit" value="提交" /> </p> </form> </body> </html>
Reg Servlet
package com.tax.action; 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.io.PrintWriter; @WebServlet("/Reg") public class Reg extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設置編碼 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); //得到輸出對象 PrintWriter out=response.getWriter(); //得到單個參數 String name=request.getParameter("name"); //得到元素name=name的值 out.println("姓名:"+name+"<br/>"); //得到多個參數 String[] hobbies=request.getParameterValues("hobby"); //得到全部name=hobby的值,數組 out.println("愛好:"); for (String hobby:hobbies){ //遍歷輸出全部的愛好 out.println(hobby); } } }
運行結果:
提交後
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8");
字符
String msg = request.getParameter("message"); String str=new String(msg.getBytes("ISO-8859-1"),"UTF-8"); byte []b = ss.getBytes("GBK"); ss = new String(b,"UTF-8");
server.xml文件
<Connector port="80" maxThreads="150" minSpareThreads="25" maxSpareThreads="75" enableLookups="false" redirectPort="8443" acceptCount="100" debug="0" connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8" />
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <% //若是爲空則得到空字符,不然取值 String uid = request.getParameter("uid") == null ? "" : request.getParameter("uid"); String pwd = request.getParameter("pwd") == null ? "" : request.getParameter("pwd"); Object msg=request.getAttribute("message")==null?"":request.getAttribute("message"); %> <html> <head> <title>登陸</title> </head> <body> <form action="Login" method="post"> <p> 賬號:<input name="uid" value="<%=uid%>"/> </p> <p> 密碼:<input name="pwd" type="password" value="<%=pwd%>"/> </p> <p> <input type="submit" value="登陸"/> </p> <p> <%=msg.toString()%> </p> </form> </body> </html>
Login Servlet
package com.tax.action; 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.io.PrintWriter; @WebServlet("/Login") public class Login extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設置編碼 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); //得到輸出對象 PrintWriter out=response.getWriter(); //得到單個參數 String uid=request.getParameter("uid"); String pwd=request.getParameter("pwd"); //若是用戶名與密碼爲admin,123456 if(uid.equals("admin")&&pwd.equals("123456")){ //向Session寫入當前登陸的用戶信息 request.getSession().setAttribute("user",uid); //成功,重定向到後臺首頁,路徑變化了,但request,response對象在index.jsp中沒法使用 response.sendRedirect("backend/index.jsp"); }else{ //在請求中添加屬性 request.setAttribute("message","用戶名或密碼不正確"); //轉發,路徑不變,但request與response能夠再使用 request.getRequestDispatcher("login.jsp").forward(request,response); } } }
後臺backend/index.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2018/3/14 Time: 11:33 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% Object user=request.getSession().getAttribute("user"); if(user==null) { response.sendRedirect("../login.jsp"); } %> <html> <head> <title>Title</title> </head> <body> <h2>歡迎您(<%=user+""%>)登陸後臺!</h2> </body> </html>
運行結果:
create table book ( id int not null primary key, title varchar2(128) not null unique, typename varchar2(128) not null, price numeric(10,2) default(0), state varchar2(10) default('未借出') ) insert into book(id,title,Typename,Price,State) select 1,'零基礎學Java(全綵版)','計算機',50.60,'未借出' from dual union select 2,'輕量級Java EE企業應用實戰','軟件工程',85.30,'未借出' from dual union select 3,'Java併發編程的藝術','軟件工程',45.40,'未借出' from dual union select 4,'實戰Java高併發程序設計','軟件開發',48.70,'未借出' from dual union select 5,'Java程序員面試筆試寶典','神話',38.50,'已借出' from dual union select 6,'Java Web從入門到精通','計算機',71.00,'未借出' from dual union select 7,'Java編程思想(第4版)','計算機',70.10,'已借出' from dual union select 8,'深刻理解JAVA虛擬機','神話',65.00,'未借出' from dual union select 9,'從零開始寫Java Web框架','計算機',63.20,'已借出' from dual select id, title, typename, price, state from book commit;
Book.java
package com.tax.model; /**圖書*/ public class Book { /**編號*/ private int id; /**書名*/ private String title; /**類型*/ private String typename; /**價格*/ private double price; /**狀態*/ private String state; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getTypename() { return typename; } public void setTypename(String typename) { this.typename = typename; } public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } public String getState() { return state; } public void setState(String state) { this.state = state; } }
package com.tax.dao; /** * Created by Administrator on 2017/8/10. */ import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class JDBCUtil { public static String DRIVER="oracle.jdbc.driver.OracleDriver"; public static String URL="jdbc:oracle:thin:@127.0.0.1:1521:orcl"; public static String USER_NAME="tax"; public static String PASSWORD="orcl"; //加載驅動 static { try { Class.forName(DRIVER); } catch (ClassNotFoundException e) { e.printStackTrace(); } } private JDBCUtil() { } /** * 得到鏈接 * * @return */ public static Connection getconnnection() { Connection con = null; try { con = DriverManager.getConnection(URL, USER_NAME, PASSWORD); } catch (SQLException e) { e.printStackTrace(); } return con; } /** * 關閉鏈接 * * @param rs * @param st * @param con */ public static void close(ResultSet rs, Statement st, Connection con) { try { try { if (rs != null) { rs.close(); } } finally { try { if (st != null) { st.close(); } } finally { if (con != null) con.close(); } } } catch (SQLException e) { e.printStackTrace(); } } /** * 關閉鏈接 * * @param rs */ public static void close(ResultSet rs) { Statement st = null; Connection con = null; try { try { if (rs != null) { st = rs.getStatement(); rs.close(); } } finally { try { if (st != null) { con = st.getConnection(); st.close(); } } finally { if (con != null) { con.close(); } } } } catch (SQLException e) { e.printStackTrace(); } } /** * 關閉鏈接 * * @param st * @param con */ public static void close(Statement st, Connection con) { try { try { if (st != null) { st.close(); } } finally { if (con != null) con.close(); } } catch (SQLException e) { e.printStackTrace(); } } /** * insert/update/delete * 增長/更新/刪除 * * @param sql 數據庫語句 * @param args 可變參數(能夠不帶參數,能夠帶0-n個參數) * @return */ public static int update(String sql, Object... args) { int result = 0; Connection con = getconnnection(); PreparedStatement ps = null; try { ps = con.prepareStatement(sql); if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject((i + 1), args[i]); } } result = ps.executeUpdate(); } catch (SQLException e) { e.printStackTrace(); } finally { close(ps, con); } return result; } /** * query, because need to manually close the resource, so not recommended * for use it * * @param sql * @param args * @return ResultSet */ @Deprecated //註解 public static ResultSet query(String sql, Object... args) { ResultSet result = null; Connection con = getconnnection(); PreparedStatement ps = null; try { ps = con.prepareStatement(sql); if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject((i + 1), args[i]); } } result = ps.executeQuery(); } catch (SQLException e) { e.printStackTrace(); } return result; } /** * Query a single record * 查詢單個記錄 * @param sql * @param args * @return Map<String,Object> */ public static Map<String, Object> queryForMap(String sql, Object... args) { Map<String, Object> result = new HashMap<String, Object>(); List<Map<String, Object>> list = queryForList(sql, args); if (list.size() > 0) { result = list.get(0); } return result; } /** * Query a single record * 查詢單個記錄返回強類型對象 * @param sql * @param args * @return <T> //泛型 */ public static <T> T queryForObject(String sql, Class<T> clz, Object... args) { T result = null; List<T> list = queryForList(sql, clz, args); if (list.size() > 0) { result = list.get(0); } return result; } /** * Query a single record * * @param sql * @param args * @return List<Map<String,Object>> */ public static List<Map<String, Object>> queryForList(String sql, Object... args) { List<Map<String, Object>> result = new ArrayList<Map<String, Object>>(); Connection con = null; ResultSet rs = null; PreparedStatement ps = null; try { con = getconnnection(); ps = con.prepareStatement(sql); if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject((i + 1), args[i]); } } rs = ps.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); while (rs.next()) { Map<String, Object> map = new HashMap<String, Object>(); for (int i = 1; i <= columnCount; i++) { map.put(rsmd.getColumnLabel(i), rs.getObject(i)); } result.add(map); } } catch (SQLException e) { e.printStackTrace(); } finally { close(rs, ps, con); } return result; } /** * Query records * 查詢多個對象,返回強類型集合 * @param sql * @param args * @return List<T> */ public static <T> List<T> queryForList(String sql, Class<T> clz, Object... args) { List<T> result = new ArrayList<T>(); Connection con = null; PreparedStatement ps = null; ResultSet rs = null; try { con = getconnnection(); ps = con.prepareStatement(sql); if (args != null) { for (int i = 0; i < args.length; i++) { ps.setObject((i + 1), args[i]); } } rs = ps.executeQuery(); ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); while (rs.next()) { T obj = clz.newInstance(); for (int i = 1; i <= columnCount; i++) { String columnName = rsmd.getColumnName(i); String methodName = "set" + columnName.substring(0, 1).toUpperCase() + columnName.substring(1, columnName.length()).toLowerCase(); Method method[] = clz.getMethods(); for (Method meth : method) { if (methodName.equals(meth.getName())) { meth.invoke(obj, rs.getObject(i)); } } } result.add(obj); } } catch (InstantiationException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } finally { close(rs, ps, con); } return result; } }
package com.tax.dao; import com.tax.model.Book; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; /** * 用於訪問數據庫中的Book表 */ public class BookDao { /*** * 得到全部的圖書 * @return */ public List<Book> getAllBooks() { List<Book> result = null; Connection conn = null; PreparedStatement statement = null; ResultSet set = null; try { //得到鏈接對象 conn = JDBCUtil.getconnnection(); //建立sql命令對象 statement = conn.prepareStatement("select id, title, typename, price, state from book"); //執行查詢返回結果集 set = statement.executeQuery(); result = new ArrayList<Book>(); //遍歷結果集 while (set.next()) { Book book = new Book(); //建立圖書對象 book.setId(set.getInt("id")); //從結果集中得到當前行列名爲id的值轉成int類型 book.setTypename(set.getString("typename")); book.setTitle(set.getString("title")); book.setState(set.getString("state")); book.setPrice(set.getDouble("price")); result.add(book); //將圖書對象添加到集合中 } } catch (Exception e) { e.printStackTrace(); } finally { JDBCUtil.close(set, statement, conn); } //返回結果 return result; } public static void main(String[] args) { BookDao dao=new BookDao(); for (Book book:dao.getAllBooks()) { System.out.println(book.getTitle()); } } }
Book.jsp
<%@ page import="com.tax.dao.BookDao" %> <%@ page import="com.tax.model.Book" %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <% BookDao dao=new BookDao(); %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Book</title> <link rel="stylesheet" type="text/css" href="js/jPicture.min.css" /> <style type="text/css"> * { margin: 0; padding: 0; } #container { width: 1004px; margin: 0 auto; } #header { height: 200px; background: url(images/top.png) no-repeat; } #menu { background: orangered; } #menu a { width: 100px; display: inline-block; background: orangered; height: 30px; text-align: center; line-height: 30px; text-decoration: none; color: white; } #menu a:hover { background: mistyrose; color: orangered; } #banner img { width: 1004px; } #main { clear: both; overflow: hidden; margin-bottom: 10px; } #main #left { width: 30%; float: left; background: lightblue; height: 400px; } #main #right { width: 70%; float: left; } #main .bookitem { width: 30%; float: left; margin-right: 3%; } #footer { clear: both; text-align: center; background: lightsalmon; height: 65px; line-height: 30px; padding-top: 5px; } #left a { width: 100%; display: inline-block; /*行內塊標籤,行內標籤設置寬度無效*/ background: orangered; height: 30px; text-align: center; line-height: 30px; text-decoration: none; /*去下劃線*/ color: white; } #banner{ width: 1004px; height: 300px;} </style> </head> <body> <div id="container"> <div id="header"></div> <div id="menu"> <a href="#">圖書列表</a> <a href="#">用戶登陸</a> <a href="#">後臺管理</a> <a href="#">圖書列表</a> <a href="#">用戶登陸</a> <a href="#">後臺管理</a> </div> <div id="banner"> <div> <div> <a href="#"> <img src="images/adv3.jpg" /> </a> </div> <div> <a href="#"> <img src="images/adv2.jpg" /> </a> </div> <div> <a href="#"> <img src="images/adv1.jpg" /> </a> </div> </div> </div> <div id="main"> <div id="left"> <a href="#">圖書列表</a> <a href="#">用戶登陸</a> <a href="#">後臺管理</a> <a href="#">圖書列表</a> <a href="#">用戶登陸</a> <a href="#">後臺管理</a> </div> <div id="right"> <%for (Book book: dao.getAllBooks()) {%> <div class="bookitem"> <p class="picture"> <img src="images/book(<%=book.getId()%>).jpg" /> </p> <p class="price"> ¥<%=book.getPrice()%> </p> <p class="title"> <%=book.getTitle()%> </p> <p class="state"> <%=book.getState()%> </p> </div> <%}%> </div> </div> <div id="footer"> <p> 關於咱們 | 聯繫咱們 | 聯繫客服 | 合做招商 | 商家幫助 | 營銷中心 | 手機書店 | 友情連接 | 銷售聯盟 </p> <p> Copyright @ 2004 - 2018 國稅JavaEE版權全部 </p> </div> </div> <script src="js/jquery-1.11.3.min.js" type="text/javascript" charset="utf-8"></script> <script src="js/jPicture.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> jPicture("#banner", { type: "slide", autoplay: 2000 }); </script> </body> </html>
結果:
BookController控制器
package com.tax.action; import com.tax.dao.BookDao; 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; @WebServlet("/Book") public class BookController extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { BookDao dao=new BookDao(); request.setAttribute("books",dao.getAllBooks()); request.getRequestDispatcher("booklist.jsp").forward(request,response); } }
booklist.jsp視圖
<%@ page import="com.tax.dao.BookDao" %> <%@ page import="com.tax.model.Book" %> <%@ 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 charset="UTF-8"> <title>Book</title> <link rel="stylesheet" type="text/css" href="js/jPicture.min.css"/> <style type="text/css"> * { margin: 0; padding: 0; } #container { width: 1004px; margin: 0 auto; } #header { height: 200px; background: url(images/top.png) no-repeat; } #menu { background: orangered; } #menu a { width: 100px; display: inline-block; background: orangered; height: 30px; text-align: center; line-height: 30px; text-decoration: none; color: white; } #menu a:hover { background: mistyrose; color: orangered; } #banner img { width: 1004px; } #main { clear: both; overflow: hidden; margin-bottom: 10px; } #main #left { width: 30%; float: left; background: lightblue; height: 400px; } #main #right { width: 70%; float: left; } #main .bookitem { width: 30%; float: left; margin-right: 3%; } #footer { clear: both; text-align: center; background: lightsalmon; height: 65px; line-height: 30px; padding-top: 5px; } #left a { width: 100%; display: inline-block; /*行內塊標籤,行內標籤設置寬度無效*/ background: orangered; height: 30px; text-align: center; line-height: 30px; text-decoration: none; /*去下劃線*/ color: white; } #banner { width: 1004px; height: 300px; } </style> </head> <body> <div id="container"> <div id="header"></div> <div id="menu"> <a href="#">圖書列表</a> <a href="#">用戶登陸</a> <a href="#">後臺管理</a> <a href="#">圖書列表</a> <a href="#">用戶登陸</a> <a href="#">後臺管理</a> </div> <div id="banner"> <div> <div> <a href="#"> <img src="images/adv3.jpg"/> </a> </div> <div> <a href="#"> <img src="images/adv2.jpg"/> </a> </div> <div> <a href="#"> <img src="images/adv1.jpg"/> </a> </div> </div> </div> <div id="main"> <div id="left"> <a href="#">圖書列表</a> <a href="#">用戶登陸</a> <a href="#">後臺管理</a> <a href="#">圖書列表</a> <a href="#">用戶登陸</a> <a href="#">後臺管理</a> </div> <div id="right"> <c:forEach var="book" items="${books}"> <div class="bookitem"> <p class="picture"> <img src="images/book(${book.id}).jpg"/> </p> <p class="price"> ¥${book.price} </p> <p class="title"> ${book.title} </p> <p class="state"> ${book.state} </p> </div> </c:forEach> </div> </div> <div id="footer"> <p> 關於咱們 | 聯繫咱們 | 聯繫客服 | 合做招商 | 商家幫助 | 營銷中心 | 手機書店 | 友情連接 | 銷售聯盟 </p> <p> Copyright @ 2004 - 2018 國稅JavaEE版權全部 </p> </div> </div> <script src="js/jquery-1.11.3.min.js" type="text/javascript" charset="utf-8"></script> <script src="js/jPicture.min.js" type="text/javascript" charset="utf-8"></script> <script type="text/javascript"> jPicture("#banner", { type: "slide", autoplay: 2000 }); </script> </body> </html>
結果:
addBook.jsp
<%-- Created by IntelliJ IDEA. User: Administrator Date: 2018/3/14 Time: 17:07 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>添加圖書</title> </head> <body> <form method="post" action="AddBook"> <h2>添加圖書</h2> <fieldset> <legend>圖書詳細</legend> <p> 書名:<input type="text" name="title"/> </p> <p> 類型:<select name="typename"> <option value="計算機">計算機</option> <option value="神話">神話</option> <option value="軟件工程">軟件工程</option> </select> </p> <p> 價格:<input type="text" name="price"/> </p> <p> 狀態:<input type="checkbox" name="state" value="已借出"/>已借出 <input type="checkbox" name="state" value="未借出"/>未借出 </p> <p> 描述:<textarea name="memo" cols="50" rows="5"></textarea> </p> <p> <input type="submit" value="添加" /> </p> <P> <%=request.getAttribute("msg")==null?"":request.getAttribute("msg")%> </P> </fieldset> </form> </body> </html>
AddBook Servlet
package com.tax.action; import com.tax.dao.BookDao; import com.tax.model.Book; 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; @WebServlet("/AddBook") public class AddBook extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //設置編碼 request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8"); response.setCharacterEncoding("utf-8"); String title=request.getParameter("title"); String state=request.getParameter("state"); String price=request.getParameter("price"); String typename=request.getParameter("typename"); Book book=new Book(); book.setTitle(title); book.setState(state); book.setTypename(typename); book.setPrice(Double.parseDouble(price)); BookDao dao=new BookDao(); if(dao.add(book)>0) { response.sendRedirect("book.jsp"); }else { request.setAttribute("msg","添加失敗"); request.getRequestDispatcher("addBook.jsp").forward(request,response); } } }
運行結果
day1
|