• Java Web 开发的JavaBean + Servlet + Sql Server


    日期:2018.12.9

    博客期:026

    星期日

      我知道对于每个人都需要对开发web进行了解,而我们常用的技术,也应该有所了解

      /*<------------------->*/知识点:

      1、JavaBean

      JavaBean 是一种JAVA语言写成的可重用组件。为写成JavaBean,类必须是具体的和公共的,并且具有无参数的构造器。JavaBean 通过提供符合一致性设计模式的公共方法将内部域暴露成员属性,set和get方法获取。众所周知,属性名称符合这种模式,其他Java 类可以通过自省机制(反射机制)发现和操作这些JavaBean 的属性。

      2、Servlet

      Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务器端程序,主要功能在于交互式地浏览和修改数据,生成动态Web内容。
      狭义的Servlet是指Java语言实现的一个接口,广义的Servlet是指任何实现了这个Servlet接口的类,一般情况下,人们将Servlet理解为后者。Servlet运行于支持Java的应用服务器中。从原理上讲,Servlet可以响应任何类型的请求,但绝大多数情况下Servlet只用来扩展基于HTTP协议的Web服务器。
      最早支持Servlet标准的是JavaSoft的Java Web Server,此后,一些其它的基于Java的Web服务器开始支持标准的Servlet。

      3、Sql Server

      SQL Server 是Microsoft 公司推出的关系型数据库管理系统。具有使用方便可伸缩性好与相关软件集成程度高等优点,可跨越从运行Microsoft Windows 98 的膝上型电脑到运行Microsoft Windows 2012 的大型多处理器的服务器等多种平台使用。
    Microsoft SQL Server 是一个全面的数据库平台,使用集成的商业智能 (BI)工具提供了企业级的数据管理。Microsoft SQL Server 数据库引擎为关系型数据和结构化数据提供了更安全可靠的存储功能,使您可以构建和管理用于业务的高可用和高性能的数据应用程序。

      ——资料来源于《百度百科》

      /*<------------------->*/建立网站系统的操作步骤:

      1、安装集成环境(Eclipse以及其web组件安装完全的可以跳过)

      (1)、登陆官网下载eclipse(版本:Eclipse Java EE IDE for Web Developers.)

      下载地址:  https://www.eclipse.org/downloads/

      (2)、之后找到Tomcat官网去下载tomcat服务器【请根据自己的Eclipse支持的Tomcat版本选择】

      下载地址:  http://tomcat.apache.org/download-70.cgi

      (3)、准备eclipse的环境配置:

      这个参考之前的博客,可以找到基本路径的配置

      (4)、在Eclipse里供应Tomcat服务

      这个需要在 窗口 的栏目 首选项 里找到 Server 一栏,再找到 RunTime Environments 一项,如果没有任何服务,则选择添加服务,对应你安装的位置,依次顺下来就可以啦!

      

      2、项目的基本构建

      (1)、在项目资源管理器里鼠标右击,选择新建项目,勾选 Dynamic Web Project 一项,并单击“下一步”

      

      之后,写入项目名称,单击“完成”

      

      呃~把下图两个包复制粘贴到lib文件下,lib目录也如下:

      

      它会自动导入Jar包:

       classes12.jar
       json-rpc-1.0.jar

      如果没有将My Sql 的 Jar 包导入的朋友可以选择把mysql(省略).jar也导入进去。

      再新建 web.xml 在上图位置,写这个文件的问题留到之后去说。

      新建专门用来写CSS和Java Script的两个文件夹(个人习惯)

      jsp统一建在WEB-INF文件夹下

      

      分别建立JavaBean的基础类和Servlet以及SqlServer的包

      3、建立JavaBean

      就拿Student来说,和Java一样,新建类输入名称Student,写基本属性,鼠标右击选择“源码”,自动生成所有的set、get方法和构造方法,另外再写一个Display()方法,用于相关连接的测试。

      1 package basic;
      2 
      3 public class Student {
      4     //-----------------------------------<数据域>----------------------------------------//
      5     //名字
      6     protected String name;
      7     //性别
      8     protected boolean sex;
      9     //学号
     10     protected String studentNumber;
     11     //年龄
     12     protected int age;
     13     //综合测评分数
     14     protected double score;
     15     //-----------------------------------<方法域>----------------------------------------//
     16     //---[set、get方法]
     17     public String getName() {
     18         return name;
     19     }
     20     public void setName(String name) {
     21         this.name = name;
     22     }
     23     public boolean isSex() {
     24         return sex;
     25     }
     26     public int getSex(){
     27         return sex?1:0;
     28     }
     29     public void setSex(int sex){
     30         this.sex = sex!=0;
     31     }
     32     public void setSex(boolean sex) {
     33         this.sex = sex;
     34     }
     35     public String getStudentNumber() {
     36         return studentNumber;
     37     }
     38     public void setStudentNumber(String studentNumber) {
     39         this.studentNumber = studentNumber;
     40     }
     41     public int getAge() {
     42         return age;
     43     }
     44     public void setAge(int age) {
     45         this.age = age;
     46     }
     47     public double getScore() {
     48         return score;
     49     }
     50     public void setScore(double score) {
     51         this.score = score;
     52     }
     53     //---[构造方法]
     54     public Student(){
     55         name = "";
     56         studentNumber = "";
     57         age = 0;
     58         score = 0.0;
     59         sex = false;
     60     }
     61     public Student(String Name){
     62         name = Name;
     63         studentNumber = "";
     64         age = 0;
     65         score = 0.0;
     66         sex = false;
     67     }
     68     public Student(int Age){
     69         name = "";
     70         studentNumber = "";
     71         age = Age;
     72         score = 0.0;
     73         sex = false;
     74     }
     75     public Student(double Score){
     76         name = "";
     77         studentNumber = "";
     78         age = 0;
     79         score = Score;
     80         sex = false;
     81     }
     82     public Student(boolean Sex){
     83         name = "";
     84         studentNumber = "";
     85         age = 0;
     86         score = 0.0;
     87         sex = Sex;
     88     }
     89     public Student(String Name,String StudentNumber){
     90         name = Name;
     91         studentNumber = StudentNumber;
     92         age = 0;
     93         score = 0.0;
     94         sex = false;
     95     }
     96     public Student(String Name,int Age,double Score,boolean Sex){
     97         name = Name;
     98         studentNumber = "";
     99         age = Age;
    100         score = Score;
    101         sex = Sex;
    102     }
    103     public Student(String Name,String StudentNumber,double Score,boolean Sex){
    104         name = Name;
    105         studentNumber = StudentNumber;
    106         age = 0;
    107         score = Score;
    108         sex = Sex;
    109     }
    110     public Student(String Name,String StudentNumber,int Age,boolean Sex){
    111         name = Name;
    112         studentNumber = StudentNumber;
    113         age = Age;
    114         score = 0.0;
    115         sex = Sex;
    116     }
    117     public Student(String Name,String StudentNumber,int Age,double Score){
    118         name = Name;
    119         studentNumber = StudentNumber;
    120         age = Age;
    121         score = Score;
    122         sex = false;
    123     }
    124     public Student(String Name,String StudentNumber,int Age,double Score,boolean Sex){
    125         name = Name;
    126         studentNumber = StudentNumber;
    127         age = Age;
    128         score = Score;
    129         sex = Sex;
    130     }
    131     public Student(String Name,String StudentNumber,double Score,boolean Sex,int Age){
    132         name = Name;
    133         studentNumber = StudentNumber;
    134         age = Age;
    135         score = Score;
    136         sex = Sex;
    137     }
    138     public Student(String Name,String StudentNumber,double Score,int Age,boolean Sex){
    139         name = Name;
    140         studentNumber = StudentNumber;
    141         age = Age;
    142         score = Score;
    143         sex = Sex;
    144     }
    145     public Student(String Name,String StudentNumber,int Age,boolean Sex,double Score){
    146         name = Name;
    147         studentNumber = StudentNumber;
    148         age = Age;
    149         score = Score;
    150         sex = Sex;
    151     }
    152     public Student(String Name,String StudentNumber,boolean Sex,int Age,double Score){
    153         name = Name;
    154         studentNumber = StudentNumber;
    155         age = Age;
    156         score = Score;
    157         sex = Sex;
    158     }
    159     public Student(String Name,int Age,String StudentNumber,boolean Sex,double Score){
    160         name = Name;
    161         studentNumber = StudentNumber;
    162         age = Age;
    163         score = Score;
    164         sex = Sex;
    165     }
    166     public Student(String Name,int Age,boolean Sex,String StudentNumber,double Score){
    167         name = Name;
    168         studentNumber = StudentNumber;
    169         age = Age;
    170         score = Score;
    171         sex = Sex;
    172     }
    173     public Student(String Name,int Age,boolean Sex,double Score,String StudentNumber){
    174         name = Name;
    175         studentNumber = StudentNumber;
    176         age = Age;
    177         score = Score;
    178         sex = Sex;
    179     }
    180     public Student(int Age,String Name,String StudentNumber,boolean Sex,double Score){
    181         name = Name;
    182         studentNumber = StudentNumber;
    183         age = Age;
    184         score = Score;
    185         sex = Sex;
    186     }
    187     public Student(int Age,String Name,boolean Sex,String StudentNumber,double Score){
    188         name = Name;
    189         studentNumber = StudentNumber;
    190         age = Age;
    191         score = Score;
    192         sex = Sex;
    193     }
    194     public Student(int Age,String Name,boolean Sex,double Score,String StudentNumber){
    195         name = Name;
    196         studentNumber = StudentNumber;
    197         age = Age;
    198         score = Score;
    199         sex = Sex;
    200     }
    201     //---[显示方法]---[阶段性测试]
    202     public void Display(){
    203         System.out.printf("%-20s	",name);
    204         System.out.println(studentNumber+"	"+age+"	"+score+"	"+sex);
    205     }
    206 }
    Student

      当然可以不写这么多的没用的构造方法。

      4、建立Sql Server

      嗯,写一个增删改查的大类,LinkToMySQL ,叫什么名字无所谓,关键是使用的方式:

      1 package basic;
      2 
      3 import java.sql.Connection;
      4 import java.sql.DriverManager;
      5 import java.sql.PreparedStatement;
      6 import java.sql.ResultSet;
      7 import java.sql.SQLException;
      8 import java.sql.Statement;
      9 
     10 public class LinkToMySQL {
     11     //=======================================================================================【数据区】
     12     //JDBC 驱动名
     13     private final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
     14     //数据库 URL
     15     private final String DB_URL = "jdbc:mysql://localhost:3306/2048?useSSL=false";
     16     //用户名
     17     private final String USER = "root";
     18     //密码
     19     private final String PASS = "123456";
     20     //构造器
     21     private Connection conn = null;
     22     private Statement stmt = null;
     23     private ResultSet rs = null;
     24     //=======================================================================================【方法区】
     25     //-------《返回是否存在学号为StuNum的数据》
     26     public boolean exsit(String stunum){
     27         ReSetResult("SELECT StuNum from StudentInformation");
     28         try {
     29             while(rs.next())
     30             {
     31                 String s = rs.getString("StuNum");
     32                 if(s.compareTo(stunum)==0)
     33                     return true;
     34             }
     35         } catch (SQLException e) {
     36             // TODO 自动生成的 catch 块
     37             e.printStackTrace();
     38         }
     39         return false;
     40     }
     41     //-------《重设rs》
     42     public void ReSetResult(String sql){
     43         try {
     44             stmt = conn.createStatement();
     45             rs = stmt.executeQuery(sql);
     46         } catch (SQLException e) {
     47             e.printStackTrace();
     48         }
     49     }
     50     //-------《增删改查》
     51     //添加一个学生数据
     52     public void Add(Student x){
     53         PreparedStatement stmts = null;
     54         try {
     55             stmts = (PreparedStatement) conn.prepareStatement("insert into StudentInformation values (?,?,?,?,?)");
     56             stmts.setString(1, x.getName());
     57             stmts.setString(2, x.getStudentNumber());
     58             stmts.setInt(3, x.isSex()?1:0);
     59             stmts.setInt(4, x.getAge());
     60             stmts.setDouble(5, x.getScore());
     61             stmts.executeUpdate();
     62             stmts.close();
     63             } catch (SQLException e) {
     64                 // TODO 自动生成的 catch 块    
     65                 e.printStackTrace();    
     66         }
     67     }
     68     //删除一个学生数据
     69     public void Delete_StuNum(String stunumber){
     70         PreparedStatement stmts = null;
     71         try {
     72             stmts = (PreparedStatement) conn.prepareStatement("delete from StudentInformation where StuNum=?");
     73             stmts.setString(1,stunumber);
     74             stmts.executeUpdate();
     75         } catch (SQLException e) {
     76             // TODO 自动生成的 catch 块
     77             e.printStackTrace();
     78         }
     79     }
     80     public void Delete_Name(String name){
     81         PreparedStatement stmts = null;
     82         try {
     83             stmts = (PreparedStatement) conn.prepareStatement("delete from StudentInformation where Name=?");
     84             stmts.setString(1,name);
     85             stmts.executeUpdate();
     86         } catch (SQLException e) {
     87             e.printStackTrace();
     88         }
     89     }
     90     //更新一个学生数据
     91     public void Renew(String stunumber,Student x){
     92         PreparedStatement stmts;
     93         try {
     94             Class.forName(JDBC_DRIVER);
     95             conn = DriverManager.getConnection(DB_URL,USER,PASS);
     96             stmt = conn.createStatement();
     97             stmts = (PreparedStatement) conn.prepareStatement("update StudentInformation set Name=?, StuNum=?, Sex=?, Age=?, Score=? where StuNum=?");
     98             stmts.setString(1,x.getName());
     99             stmts.setString(2,x.getStudentNumber());
    100             stmts.setInt(3,x.isSex()?1:0);
    101             stmts.setInt(4,x.getAge());
    102             stmts.setDouble(5,x.getScore());
    103             stmts.setString(6,stunumber);
    104             stmts.executeUpdate();
    105             stmts.close();
    106         } catch (SQLException e) {
    107             // TODO 自动生成的 catch 块
    108             e.printStackTrace();
    109         } catch (ClassNotFoundException e) {
    110             // TODO 自动生成的 catch 块
    111             e.printStackTrace();
    112         }
    113     }
    114     //查询第几个学生数据
    115     public Student GetFromSQL(int number){
    116         if(number <=0||number>Length())
    117             return null;
    118         ReSetResult("SELECT Name, StuNum, Sex, Age, Score FROM StudentInformation");
    119         try {
    120             int i = 1;
    121             while(rs.next()&&number>=i)
    122             {
    123                 String Name = rs.getString("Name");
    124                 String StuNum = rs.getString("StuNum");
    125                 int Sex = rs.getInt("Sex");
    126                 int Age = rs.getInt("Age");
    127                 double Score = rs.getDouble("Score");
    128                 if(number==i)
    129                     return new Student(Name,StuNum,Sex!=0,Age,Score);
    130                 ++i;
    131             }
    132         } catch (SQLException e) {
    133             // TODO 自动生成的 catch 块
    134             e.printStackTrace();
    135         }
    136         return null;
    137     }
    138     //查询一个学生数据
    139     public Student Refer(String stunumber){
    140         ReSetResult("SELECT Name, StuNum, Sex, Age, Score FROM StudentInformation");
    141         Student s = null;
    142         try {
    143             while(rs.next())
    144             {
    145                 String Name = rs.getString("Name");
    146                 String StuNum = rs.getString("StuNum");
    147                 int Sex = rs.getInt("Sex");
    148                 int Age = rs.getInt("Age");
    149                 double Score = rs.getDouble("Score");
    150                 if(StuNum.compareTo(stunumber)==0)
    151                     s = new Student(Name,StuNum,Age,Sex==1?true:false,Score);
    152             }
    153         } catch (SQLException e) {
    154             // TODO 自动生成的 catch 块
    155             e.printStackTrace();
    156         }
    157         return s;
    158     }
    159     //-------《数据数》
    160     public int Length(){
    161         ReSetResult("SELECT Name, StuNum, Sex, Age, Score FROM StudentInformation");
    162         int l = 0;
    163         try {
    164             while(rs.next())
    165             {
    166                 ++l;
    167             }
    168         } catch (SQLException e) {
    169             // TODO 自动生成的 catch 块
    170             e.printStackTrace();
    171         }
    172         return l;
    173     }
    174     //-------《释放》
    175     public void free(){
    176         try {
    177             stmt.close();
    178             conn.close();
    179         } catch (SQLException e) {
    180             // TODO 自动生成的 catch 块
    181             e.printStackTrace();
    182         }
    183     }
    184     //-------《构造方法》
    185     public LinkToMySQL(){
    186         try {
    187             Class.forName(JDBC_DRIVER);
    188             conn = DriverManager.getConnection(DB_URL,USER,PASS);
    189         } catch (ClassNotFoundException e1) {
    190             // TODO 自动生成的 catch 块
    191             e1.printStackTrace();
    192         } catch (SQLException e) {
    193             // TODO 自动生成的 catch 块
    194             e.printStackTrace();
    195         }
    196     }
    197     //-------《主方法》
    198     public static void main(String[] args) {
    199         LinkToMySQL l = new LinkToMySQL();
    200         //Student stu = new Student("YaLiShanDa","20170014",true,19,80.5);
    201         //l.Add(stu);
    202         l.Refer("20170001").Display();
    203         /*
    204         for(int i = 1;i<=l.Length();++i)
    205             l.GetFromSQL(i).Display();
    206             */
    207     }
    208 }
    Sql Server

      基本就是这个样子,根据JavaBean来修改SqlServer语句,或者MySQL里的表位置不同,root的密码不同,甚至用户都不是root等等情况都需要做出更改。

      还有每一个servlet调用完后,就需要使用一下free()方法,来关闭构造器。

      5、搭建jsp框架

      使用<b>、<html>、<a>、<div>、<p>、<table>、<script>、<input>等标签搭建基本的HTML框架,这个我不能再教了,参考百度搜索“菜鸟教程”,选择HTML教程。

      6、构建Sevlet,实现连接

      每一个servlet都需要继承

      5、写Servlet进行

     1 package model;
     2 
     3 import java.io.IOException;
     4 
     5 import javax.servlet.ServletException;
     6 import javax.servlet.ServletOutputStream;
     7 import javax.servlet.http.HttpServlet;
     8 import javax.servlet.http.HttpServletRequest;
     9 import javax.servlet.http.HttpServletResponse;
    10 
    11 import org.json.JSONArray;
    12 import org.json.JSONObject;
    13 
    14 import basic.LinkToMySQL;
    15 import basic.Student;
    16 
    17 @SuppressWarnings("serial")
    18 public class ReferStudentServlet extends HttpServlet
    19 {
    20     public LinkToMySQL ltmsql = new LinkToMySQL();
    21     //查询信息
    22     public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException 
    23     {        
    24         doPost(request, response);    
    25     }
    26     public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException
    27     {
    28          request.setCharacterEncoding("utf-8");
    29          response.setCharacterEncoding("utf-8");
    30          response.setContentType("application/json");
    31          response.setHeader("Cache-Control", "no-cache");
    32          response.setHeader("Pragma", "no-cache");
    33          //获得数据的方法
    34          String stunumber = request.getParameter("PrintInStuNumber");
    35          //使用JSON 传递数据
    36          JSONArray json = new JSONArray();
    37          JSONObject jo = new JSONObject();
    38          JSONObject jos = new JSONObject();
    39          jos.put("Length",1);
    40          json.put(jos);
    41          Student question = ltmsql.Refer(stunumber);
    42          if(ltmsql.exsit(stunumber))
    43          {
    44             jo.put("Name",question.getName());
    45              jo.put("StudentNumber",question.getStudentNumber());
    46              jo.put("Sex",question.getSex());
    47              jo.put("Age",question.getAge());
    48              jo.put("Score",question.getScore());
    49          }
    50          else
    51          {
    52             jo.put("Name",null);
    53               jo.put("StudentNumber",null);
    54               jo.put("Sex",null);
    55               jo.put("Age",null);
    56               jo.put("Score",null);
    57          }
    58          json.put(jo);
    59          ServletOutputStream os = response.getOutputStream();
    60          os.write(json.toString().getBytes());
    61          os.flush();
    62          os.close();
    63     }
    64 }
    servlet

      (1)、使用 JSON 的套用格式传数据给jsp,而通过request.getParameter的方法,来实现对jsp的数据调用

      (2)、每新建一个servlet就要在web.xml里写入这个servlet的配置(下方代码以model.BaseServlet为例)

     1 <servlet>
     2     <description>This is the description of my J2EE component</description>
     3     <display-name>This is the display name of my J2EE component</display-name>
     4     <servlet-name>BaseServlet</servlet-name>
     5     <servlet-class>model.BaseServlet</servlet-class>
     6   </servlet>
     7   <servlet-mapping>
     8     <servlet-name>BaseServlet</servlet-name>
     9     <url-pattern>/model/BaseServlet</url-pattern>
    10   </servlet-mapping>
    11   <servlet>
    12     <description>This is the description of my J2EE component</description>
    13     <display-name>This is the display name of my J2EE component</display-name>
    14     <servlet-name>AllStudentServlet</servlet-name>
    15     <servlet-class>model.AllStudentServlet</servlet-class>
    16   </servlet>
    AddArea

      (3)、还有啊!在jsp或js文件里写入调用servlet的代码:

     1 <script type="text/javascript">
     2 window.onload=function()
     3 {
     4     
     5 };
     6 function Back(){
     7     window.location.href = "FirstWin.jsp";
     8 }
     9 function Refer()
    10 {
    11     if(document.getElementById("StuNum").value=="")
    12     {
    13         alert("错误:学号不能为空!");
    14         return;
    15     }
    16     else
    17         MakeTable();
    18 }
    19 function MakeTable()
    20 { 
    21     var xmlHttp = null;
    22     try{
    23         xmlHttp = new XMLHttpRequest();
    24     } catch (e1) {
    25          try {
    26              xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    27         } catch (e2) {
    28             alert("Your browser does not support XMLHTTP!");
    29             return;
    30         }
    31     }
    32     xmlHttp.onreadystatechange = function() {
    33         if (xmlHttp.readyState == 4) {
    34             if (xmlHttp.status == 200) 
    35             {
    36                 alert("修改成功!");
    37             }
    38             else 
    39                 alert(xmlHttp.status);
    40         }
    41     };
    42     var server = "PrintInStuNumber="+document.getElementById("StuNum").value;
    43     server += "&name="+document.getElementById("NAME").value;
    44     server += "&stunumber="+document.getElementById("STUNUMS").value;
    45     server += "&sex="+document.getElementById("SEX").value;
    46     server += "&age="+document.getElementById("AGE").value;
    47     server += "&score="+document.getElementById("SCORE").value;
    48     var url ="model/ChangeStudentServlet";
    49     xmlHttp.open("POST", url, true);
    50     xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
    51     xmlHttp.send(server);
    52 }
    53 </script>
    servletRun

      注意对于jsp里的元素调用,使用document.getElementById("SCORE")方法得到元素,之后再*.value或*.innerHTML来实现取值。

  • 相关阅读:
    Java数据结构与算法之---求两个数的最大公约数(欧几里得算法)
    Linux下面配置文件~/.bash_profile
    Java数据结构之回溯算法的递归应用迷宫的路径问题
    Java数据结构之对称矩阵的压缩算法---
    Java数据结构之字符串模式匹配算法---KMP算法2
    Java数据结构之字符串模式匹配算法---KMP算法
    Java数据结构之字符串模式匹配算法---Brute-Force算法
    Java数据结构之表的增删对比---ArrayList与LinkedList之一
    Java数据结构之队列的实现以及队列的应用之----简单生产者消费者应用
    Java堆栈的应用1----------堆栈的自定义实现以及括号匹配算法的Java实现
  • 原文地址:https://www.cnblogs.com/onepersonwholive/p/10092976.html
Copyright © 2020-2023  润新知