先上結果圖:html
而後先來講說怎樣建立一個Servlet並部署並能被訪問。java
1.在src下創建一個普通的java類,但繼承父類httpServlet.路徑是:javax.servlet.http.HttpServlet,而後重寫你的doPost()和doGet()方法,並註釋掉父類的super.doGet(req,resp)mysql
2.在web-inf下創建classes文件夾,寫完之後運行後,在build下找到class文件,把整個包結構都拷貝過去,不是隻把class文件拷過去,要包結構和java那邊同樣的web
3.在web.xml下配置servlet的網絡訪問路徑,不配置無法在瀏覽器訪問的。sql
<servlet>
<servlet-name>servlet.Servlet</servlet-name>//servlet-name能夠隨便起,只要兩個如出一轍就可
<servlet-class>servlet.Servlet</servlet-class>//真實的包名.文件名全名
</servlet>
<servlet-mapping>
<servlet-name>servlet.Servlet</servlet-name>//servlet-name能夠隨便起,只要兩個如出一轍就可數據庫
//以這個路徑做爲訪問路徑,IP地址:端口號/項目名/servlet.Servlet就能夠訪問到,名字隨便起瀏覽器
<url-pattern>/servlet.Servlet</url-pattern>
</servlet-mapping>tomcat
4.如今就能夠訪問了,調試也是和java同樣設置斷點調試。網絡
下面給出這個微型網站的第一個功能查詢全部學生信息的所有代碼:app
index_left.jsp
<%@ 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> <br><br> <center> <a href="servlet.Servlet?methor=query_all" target="right">查詢全部學生信息</a> <br><br> <a href="insert_student.jsp" target="right">插入學生體質信息</a> </center> </body> </html>
Servlet.java
package servlet; import java.io.IOException; import java.util.List; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import configUtil.QuerySql; import configUtil.StudentHealthJavaBean; public class Servlet extends HttpServlet { public Servlet() { } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO 第三步執行 //super.doGet(req, resp);若是執行了父類方法可能會對本身的覆蓋 req.setCharacterEncoding("UTF-8"); String methor=req.getParameter("methor"); System.out.println(methor); if(methor!=null) { QuerySql query=new QuerySql(); switch(methor) { case "query_all": List<StudentHealthJavaBean> list=query.getAllStudent(); req.setAttribute("list", list); RequestDispatcher rd=req.getRequestDispatcher("/query_all_student.jsp"); rd.forward(req, resp); break; } }else { System.out.println("參數傳輸失敗。"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO 第三部執行若是執行了父類方法可能會對本身的覆蓋 //super.doPost(req, resp); req.setCharacterEncoding("UTF-8"); String str=req.getParameter("methor"); QuerySql q=new QuerySql(); StudentHealthJavaBean student=new StudentHealthJavaBean(); student.setId(req.getParameter("id")); student.setName(req.getParameter("name")); student.setSex(req.getParameter("sex")); student.setAge(Integer.parseInt(req.getParameter("age"))); student.setHight(Float.parseFloat(req.getParameter("hight"))); student.setWeight(Float.parseFloat(req.getParameter("weight"))); if(str!=null&&student!=null) { switch(str) { case "insert": int n=q.insertStudent(student); if(n==0) { System.out.println("沒有成功插入數據!"); req.setAttribute("success", "沒能成功添加此學生信息!"); } else { System.out.println("成功插入數據!"); req.setAttribute("success","成功添加此學生信息!"); } RequestDispatcher dispatcher=req.getRequestDispatcher("/success.jsp"); dispatcher.forward(req,resp); break; } } } @Override protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException { //第二部執行,完了根據post仍是get自動調用doGet()或者doPost()方法 super.service(arg0, arg1); } @Override public void init() throws ServletException { //第一步執行,自動生成request\response對象調用service方法 super.init(); } }
QuerySql.java
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class QuerySql { private String insertSQL="insert into stu_info(id,name,sex,age,hight,weight) values(?,?,?,?,?,?)"; private String selectSQL="select * from stu_info"; private Connection con=null; public QuerySql(){ } @SuppressWarnings("finally") public List<StudentHealthJavaBean> getAllStudent(){ List<StudentHealthJavaBean> list=new ArrayList<StudentHealthJavaBean>(); ResultSet rs=null; PreparedStatement ps=null; StudentHealthJavaBean student=null; con=DataBaseConfig.getConnection(); try { ps=con.prepareStatement(selectSQL); rs=ps.executeQuery(); while(rs.next()) { student=new StudentHealthJavaBean(); student.setId(rs.getString("id")); student.setName(rs.getString("name")); student.setSex(rs.getString("sex")); student.setAge(rs.getInt("age")); student.setHight(rs.getFloat("hight")); student.setWeight(rs.getFloat("weight")); list.add(student); } } catch (SQLException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); }finally { DataBaseConfig.closeDatabaseConnection(con, ps, rs); if(list!=null) System.out.println("成功查詢!"); else { System.out.println("list是空值!"); } return list; } } public int insertStudent(StudentHealthJavaBean student) { int num=0; Connection con=null; ResultSet rs=null; PreparedStatement ps=null; con=DataBaseConfig.getConnection(); try { ps=con.prepareStatement("select * from stu_info where id=?"); ps.setString(1, student.getId()); rs=ps.executeQuery(); if(rs.first()) { System.out.println("已經存在此學號的學生信息,不能插入了!"); DataBaseConfig.closeDatabaseConnection(con, ps, rs); return 0; } ps=con.prepareStatement(insertSQL); ps.setString(1, student.getId()); ps.setString(2, student.getName()); ps.setString(3, student.getSex()); ps.setInt(4, student.getAge()); ps.setFloat(5, student.getHight()); ps.setFloat(6, student.getWeight()); num=ps.executeUpdate(); } catch (SQLException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); }finally { return num; } } }
DataBaseConfig.java
public class DataBaseConfig { public static String url1="jdbc:mysql://localhost:3306/";//數據庫的網址 public static String databaseName="students";//數據庫名 public static String userName="&user=root";//登陸數據庫的登陸名 public static String password="&password=root";//數據庫的密碼 public static String driverName="com.mysql.jdbc.Driver"; //mysql的驅動包名,下載到的解壓包已放在tomcat的lib下 public static String encoding="&useUnicode=true&characterEncoding=UTF-8";//編碼方式 public static String url=url1+databaseName+"?"+"useSSL=false"+encoding+userName+password; @SuppressWarnings("finally")//SSL是一種加密技術,這裏不要他 public static Connection getConnection() { Connection con=null; try { Class.forName(driverName); con=DriverManager.getConnection(url); } catch (ClassNotFoundException | SQLException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); }finally { return con; } } public static void closeDatabaseConnection(Connection con,PreparedStatement ps,ResultSet rs) { try {//須要手動釋放數據庫的一些資源 if(rs!=null)rs.close(); if(ps!=null) ps.close(); if(con!=null) con.close(); } catch (SQLException e) { // TODO 自動生成的 catch 塊 e.printStackTrace(); } } }
StudentHealthJavaBean.java
public class StudentHealthJavaBean { private String id; private String name; private String sex; private int age; private float hight; private float weight; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public float getHight() { return hight; } public void setHight(float hight) { this.hight = hight; } public float getWeight() { return weight; } public void setWeight(float weight) { this.weight = weight; } public StudentHealthJavaBean() { // TODO 自動生成的構造函數存根 } }
query_all_student.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@page import="java.util.*" %> <%@page import="configUtil.*" %> <!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>全部學生信息</title> </head> <body style="padding-left:100px;padding-top:20px"> <%! List<StudentHealthJavaBean> list=null; StudentHealthJavaBean student=null; %> <table border="2"> <% list=(List<StudentHealthJavaBean>)request.getAttribute("list"); for(int i=0;i<list.size();i++){ student=new StudentHealthJavaBean(); student=list.get(i); %> <tr> <td><%=student.getId()%></td> <td><%=student.getName()%></td> <td><%=student.getSex()%></td> <td><%=student.getAge()%></td> <td><%=student.getHight()%></td> <td><%=student.getWeight()%></td> </tr> <% } %> </table> </body> </html>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>StudentHealthSys</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>servlet.Servlet</servlet-name> <servlet-class>servlet.Servlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>servlet.Servlet</servlet-name> <url-pattern>/servlet.Servlet</url-pattern> </servlet-mapping> </web-app>
在作這個微型網站的過程當中的bug記錄和修正:
在web.xml裏servlet-mapping書寫文件名時注意到原來的文件結構有沒有在某個包下面,加上包名就正確了
去掉dopost()doget()調用父類的方法那句,被父類方法覆蓋了,訪問名沒有.java後綴。
webInf下創建classes包,buid下複製java文件的包結構和java文件的class文件過來
寫的連接<a>必需要點擊才能跳轉,不會自動跳轉
用setAttribute()的方式存儲卻用getParameter()的方式取,必須一致用getAttribute能取到了。
getParameter()好像只對Input標籤的值有效。
強制類型轉換是能夠的。
form發送的只是input標籤內的數據,不發送request數據,能夠把不用用戶填入的數據設爲input的type=hidden類型填入。
兩種方法,一種是form表單的action跳過去,另外一種是<a>超連接標籤點擊跳轉
目前只知道一種方法:Request類方法獲得RequestDispatcher對象,其對象的forward帶着request和response跳回去。
RequestDispatcher dispatcher=req.getRequestDispatcher("/success.jsp");
dispatcher.forward(req,resp);
jsp的form表單和<a>的鏈接後能夠加上?屬性=屬性值一塊兒過去,都經過getParameter取出。
經過request的setAttribute()方法存入,在jsp經過getAttribute取出。
用HttpServletResponse的getWriter()方法返回一個PrintWriter對象,調用PrintWriter的println()方法+flush()方法能向本身本窗口和客戶端輸出文字。
首先引入javaBean的路徑,而後創建javabean的對象
<jsp:useBean id=你建的javaBean的對象 class=包名文件名 scope=有效範圍seesion/request等/>
而後存儲<jsp:setProperty name=必須和上面的id對象同名
property=屬性名(若是是*就是全部input自動找到和name同名的賦值) value=值/>
調用<jsp:getProperty name="對象名" property="屬性名"/>
直接建立對象存入數據使用,像通常的類同樣。