Javaweb

}package test;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * 数据库连接工具
 * @author 
 *
 */
public class DBUtil {
    //联结字符串                                              //数据库名test
    public static String db_url = "jdbc:mysql://localhost:3306/test?&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC&characterEncoding=GB2312";
    //数据库用户名
    public static String db_user = "root";
    //数据库密码名
    public static String db_pass = "123";
    
    public static Connection getConn () {
        
        //声明与数据库的连接并实例化为null
        Connection conn = null;
        
        try {
            //驱动程序名
            Class.forName("com.mysql.jdbc.Driver");//连接数据库
            //具体地连接到数据库——联接字符串(数据库名),联接用户名,联接密码名
            conn = DriverManager.getConnection(db_url, db_user, db_pass);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return conn;
    }
    
    /**
     * 关闭连接
     * @param state
     * @param conn
     */
    public static void close (Statement state, Connection conn) {
        if (state != null) {
            try {
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static void close (ResultSet rs, Statement state, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        
        if (state != null) {
            try {
                state.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }}

  User.java

package test;
 
public class User
{
    private String zhanghao;
    private String code;
    private String sex;
    private String name;
    private String xuehao;
    private String email;
    private String school;
    private String xi;
    private String banji;
    private String year;
    private String address;
    private String beizhu;
   
    public User(String zhanghao, String code, String sex,String name,String xuehao,String email,String school,
            String xi,String banji,String year,String address,String beizhu) {
        this.zhanghao = zhanghao;
        this.code= code;
        this.sex = sex;
        this.name = name;
        this.xuehao=xuehao;
        this.email=email;
        this.school=school;
        this.xi=xi;
        this.banji=banji;
        this.year=year;
        this.address = address;
        this.beizhu=beizhu;
    }
    public String getZhanghao() {
        return zhanghao;
    }
    public void setZhanghao(String zhanghao) {
        this.zhanghao = zhanghao;
    }
    public String getCode() {
        return code;
    }
    public void setCode(String code) {
        this.code =code;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getXuehao() {
        return xuehao;
    }
    public void setXuehao(String xuehao) {
        this.xuehao = xuehao;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getSchool() {
        return school;
    }
    public void setSchool(String school) {
        this.school = school;
    }
    public String getXi() {
        return xi;
    }
    public void setXi(String xi) {
        this.xi= xi;
    }
    public String getBanji() {
        return banji;
    }
    public void setbBanji(String banji) {
        this.banji = banji;
    }
    public String getYear() {
        return year;
    }
    public void setYear(String year) {
        this.year = year;
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getBeizhu() {
        return beizhu;
    }
    public void setBeizhu(String beizhu) {
        this.beizhu = beizhu;
    }
     
}

添加到Grade

package test;
 
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
 
import test.User;
import test.DBUtil;;
 
public class dao
{
 
    //添加
    //添加入Grade表里
     
    public boolean insert(User user)
    {
        String sql="insert into resgist(zhanghao,code,sex,name,xuehao,email,school,xi,banji,year,address,beizhu) values('"+user.getZhanghao()+"','"+user.getCode()+"','"+
    user.getSex()+"','"+user.getName()+"','"+user.getXuehao()+"','"+user.getEmail()+"','"+user.getSchool()+"','"+user.getXi()+"','"+user.getBanji()+
    "','"+user.getYear()+"','"+user.getAddress()+"','"+user.getBeizhu()+"')";
        //insert语句:
        //insert INTO table_name (column1,column2,column3,...) VALUES (value1,value2,value3,...);
        //注意:insert这里 values(100,'吴林祥','"+bianliang+"'),数字可以直接上,字符串的话用 '',变量的话要用 '"++"'
         
        Connection conn=DBUtil.getConn();//数据库连接,加载驱动
        Statement state=null;//数据库操作
        try
        {
            state=conn.createStatement();//实例化Statement对象,方便对sql语句进行操作
            state.executeUpdate(sql);
            //执行数据库更新操作用于执行INSERT、UPDATE或DELETE语句以及SQLDDL(数据定义语言)语句,
            //例如CREATETABLE和DROPTABLE,(创建表和删除表)
        }catch(Exception e)//当try语句中出现异常时,会执行catch中的语句
          {
            e.printStackTrace();//捕获异常的语句
          }
         finally //finally作为异常处理的一部分,它只能用在try/catch语句中,并且附带一个语句块,表示这段语句最终一定会被执行(不管有没有抛出异常),经常被用在需要释放资源的情况下。
         {
             DBUtil.close(state, conn); //close释放资源
         }
        return false;
    }
     
//      //删除
//      //根据ID删除
//     
//      public boolean delete(int id)
//      {
//          String sql="delete from grade_student where ID='"+id+"'";
//          //删除语句:
//          //delete from table_name where some_colume=some_value
//         
//          Connection conn=DBUtil.getConn();
//          Statement state=null;
//         
//          try
//          {
//              state=conn.createStatement();
//              state.executeUpdate(sql);
//          }catch (Exception e)
//          {
//              e.printStackTrace();
//          }
//          finally
//          {
//              DBUtil.close(state, conn);
//          }
//          return false;
//      }
//     
//      //修改
//      //根据学号修改
//     
//      public boolean update(Grade grade)
//      {
//          String sql="update grade_student set Chinese='"+grade.getChinese()+"',Math='"+grade.getMath()+"',English='"+grade.getEnglish()+"',SUM='"+grade.getSUM()+"'   where ID='"+grade.getID()+"' ";
//          //update语句:
//          //update table_name set column1=value1,column2=value2  where some_column=some_value;
//         
//          Connection conn=DBUtil.getConn();
//          Statement state=null;
//         
//          try
//          {
//              state=conn.createStatement();
//              state.executeUpdate(sql);
//          }catch (SQLException e)
//          {
//              e.printStackTrace();
//          }
//          finally
//          {
//              DBUtil.close(state, conn);
//          }
//          return false;
//      }
//     
//      //查询
//      //查询全部并存入list
//      //List指的是集合.<>是泛型,里面指定了这个集合中存放的是什么数据
//      //泛型是程序设计语言的一种特性。
//      //允许程序员在强类型程序设计语言中编写代码时定义一些可变部分,
//      //但是,那些部分在使用前必须作出指明。
//     
//      public  List<User>list()
//      {
//          String sql="select * from grade_student order by ID ASC";
//          //select语句
//          //select * from tabel_name   这是查询所有,若要查询某一列
//          //select column1_name,column2_name,column3_name from table_name
//         
//          List<User>list=new ArrayList<>();
//          //给集合list创造(new)一个存储空间用于存放数据
//         
//          Connection conn=DBUtil.getConn();
//          Statement state=null;
//          ResultSet rs=null;
//         
//          try
//          {
//              state=conn.createStatement();
//              rs=state.executeQuery(sql);
//              User user=null;
//              while(rs.next()) //这里表示,当rs.next()有值得时候,即收到查询结果
//              {
//                  String id=rs.getString("ID"); //注意:这里用双引号,ID是表grade_student里的ID列
//                  String name=rs.getString("NAME");
//                  int Chinese=rs.getInt("Chinese");
//                  int Math=rs.getInt("Math");
//                  int English=rs.getInt("English");
//                  int SUM=rs.getInt("SUM");
//                  user=new User(username,password,name,,English,SUM);
//                  list.add(user); //表示,把bean里的数据存入到list当中
//              }
//          }
//          catch (SQLException e)
//          {
//              e.printStackTrace();
//          }
//          finally
//          {
//              DBUtil.close(state, conn);
//          }
//          return list;
//      }
//     
        //验证注册是否唯一
        public boolean username(String username) {
             
            boolean flag = false;
             
            String sql = "select username from resgist where username = '" + username + "'";
            Connection conn = DBUtil.getConn();
            Statement state = null;
            ResultSet rs = null;
             
        try {
                state = conn.createStatement();
                rs = state.executeQuery(sql);
                //要用statement类的executeQuery()方法来下达select指令以查询数据库,
                //executeQuery()方法会把数据库响应的查询结果存放在ResultSet类对象中供我们使用。
                while (rs.next()) {
                    flag = true;
                }
            }
            catch (SQLException e) {
                e.printStackTrace();
            } finally {
                DBUtil.close(rs, state, conn);
        }
            return flag;
        }
         
         
         
}
package test;
 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
/**
 * Servlet implementation class servelt01
 */
@WebServlet("/servelt01")
public class servelt01 extends HttpServlet {
    private static final long serialVersionUID = 1L;
        
    /**
     * @see HttpServlet#HttpServlet()
     */
    
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.getWriter().append("Served at: ").append(request.getContextPath());
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }
 
}

  service

package test;
 
import java.util.List;
import test.dao;
import test.User;
 
/**
 * CourseService
 * 服务层
 * @author Hu
 *
 */
 
//service层相当于一个封装层,封装那些与业务相关的通用数据接口
 
public class service
{
    dao cdao=new dao();
    /**
     * 添加
     * @param course
     * @return
     */
    public boolean insert(User user)
    {
        boolean f=false;
        if(!cdao.username(user.getName()))
        {
            cdao.insert(user);
            f=true;
        }
        return f;
    }
     
    //删除
     
//  public void delete(int id)
//  {
//      cdao.delete(id);
//  }
// 
//  //修改
// 
//  public void update (Grade grade)
//  {
//      cdao.update(grade);
//  }
// 
//  //通过ID得到一个Course   
// 
//  //通过name得到一个Course 
//
//  //查找
// 
// 
//  //全部数据遍历
// 
//  public List<Grade>list()
//  {
//      return cdao.list();
//  }
}
package test;
 
import java.io.IOException;
import java.util.List;
 
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 test.User;
import test.service;
 
@WebServlet("/servlet")
public class servlet extends HttpServlet //继承的是 HttpServlet方法,和网页交互的方法
{
    private static final long serialVersionUID = 1L;
     
    service service=new service();
     
    //方法选择
     
    protected void service(HttpServletRequest req,HttpServletResponse resp)throws ServletException, IOException
    {
        //req是Request(请求)的简写,指的是从jsp/html界面请求回数据,即 jsp/html → 底层
        //resp是Response(回答)的简写,指的是发送给jsp/html的数据,,即 底层 → jsp/html
         
        req.setCharacterEncoding("utf-8");//设置从jsp或HTML中请求数据的值,也就是设置为中文,防止乱码
        String method=req.getParameter("method");//getParameter()获取的是客户端设置的数据。
        if ("insert".equals(method)) {
            insert(req, resp);
        }
//      //增
//      else if ("delete".equals(method)) {
//          delete(req, resp);
//      }
//      //删
//      else if ("update".equals(method)) {
//          update(req, resp);
//      } 
//      //改
//      else if ("list".equals(method)) {
//          list(req, resp);
//      }
//      //查
    }
     
     
     
    //添加
     
    private void insert(HttpServletRequest req,HttpServletResponse resp)throws IOException, ServletException
    {
        //首先读取前端网页数据并将数据存入我创建的grade存储空间里,即 jsp/html → servlet
         
        req.setCharacterEncoding("utf-8"); //从网页获得数据
        String zhanghao=req.getParameter("zhanghao");
        String code=req.getParameter("code");
        //因为req.getParameter只能获得String类型的数据
        //所以下面需要用Integer.parseInt(req.getParameter())来把String类型的数据转换成我们所需的int数据
        String sex=req.getParameter("sex");
        String name=req.getParameter("name");
        String xuehao=req.getParameter("xuehao");
        String email=req.getParameter("email");
        String school=req.getParameter("school");
        String xi=req.getParameter("xi");
        String banji=req.getParameter("banji");
        String year=req.getParameter("year");
        String address=req.getParameter("ddress");
        String beizhu=req.getParameter("beizhu");
        User user=new User(zhanghao,code,sex,name,xuehao,email,school,xi,banji,year,address,beizhu);
         
         
        //其次进行把grade里的数据与添加到数据库里,即 servlet → mysql数据库
        //并跳转,req.getRequestDispatcher("add.jsp").forward(req, resp);这一步是跳转到前端jsp/html界面
         
        if(service.insert(user)) //如果添加成功
        {
            req.setAttribute("message", "添加成功");
            //这里表示,在req的作用域中设置一个massage变量,变量内容是:添加成功
            //然后,当跳转到它下一个界面时,这个作用域里的值可以通过Object message =request.getAttribute("message")拿出来使用
            req.getRequestDispatcher("index.jsp").forward(req, resp);
            //处理完了,分发到下一个JSP页面或者下一个Action继续处理。
        }
        else
        {
            req.setAttribute("message", "添加重复,请重新输入");
            req.getRequestDispatcher("fail.jsp").forward(req, resp);
        }
    }
     
     
//  //删除delete
// 
//  private void delete(HttpServletRequest req,HttpServletResponse resp)throws IOException,ServletException
//  {
//      req.setCharacterEncoding("UTF-8");
//      int id=Integer.parseInt(req.getParameter("id"));
//      service.delete(id); //进行数据库的删除操作
//      req.setAttribute("message", "删除成功");
//      req.getRequestDispatcher("servlet?method=list").forward(req, resp);
//  }
// 
//  //修改update
// 
//  private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
//      req.setCharacterEncoding("utf-8");
//      String id=req.getParameter("id");
//      int Chinese=Integer.parseInt(req.getParameter("Chinese"));
//      int Math=Integer.parseInt(req.getParameter("Math"));
//      int English=Integer.parseInt(req.getParameter("English"));
//      int SUM=Integer.parseInt(req.getParameter("SUM"));
//      Grade grade=new Grade(id,Chinese,Math,English,SUM);
//      service.update(grade);//进行数据库的修改操作
//      req.setAttribute("message", "修改成功");
//      req.getRequestDispatcher("servlet?method=list").forward(req,resp);
//      //?method=list表示传一个叫做method的参数,他的值是list,你可以在Servlet中用request.getParam...获取到。
//  }
// 
//
//  //全部
// 
//  private void list(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException{
//      req.setCharacterEncoding("utf-8");
//      List<Grade> grade_list = service.list();
//      req.setAttribute("grade_list", grade_list);
//      req.getRequestDispatcher("list.jsp").forward(req,resp);
//  }
//
}

  登录界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>用户注册</title>
<style>
    .a{
        margin-top: 20px;
    }
    .b{
        font-size: 20px;
        width: 140px;
        color: white;
        background-color: black;
    }
</style>
</head>
<body>
 
    <%
         Object message = request.getAttribute("message");
         if(message!=null && !"".equals(message)){
      
    %>
         <script type="text/javascript">
              alert("<%=request.getAttribute("message")%>"); //弹出对话框
         </script>
    <%} %>
    <div align="center">
        <h1 style="color: blue;">用户注册</h1>
        <a href="index.jsp">返回主页</a>
        <form action="servlet?method=insert" method="post" onsubmit="return check()">
            <div class="a">
                登录账号<input type="text" id="zhanghao" name="zhanghao"/>
            </div>
            <div class="a">
                登录密码<input type="password" id="code" name="code" />
                </div>
            <div class="a">
                性别<input id="man" type="radio" checked="checked" name="sex" value="男" />男
                <input id="woman" type="radio"  name="sex" value="女"/>女
            </div>
            <div class="a">
                姓名<input type="text" id="name" name="name" />
                </div>
            <div class="a">
                学号<input type="text" id="xuehao" name="xuehao" /d>
                </div>
            <div class="a">
                电子邮件<input type="text" id="email" name="email" />
                </div>
            <div class="a">
                所在学校<input type="text" id="school" name="school" />
                </div>
            <div class="a">
                所在系<input type="text" id="xi" name="xi" />
                </div>
            <div class="a">
                所在班级<input type="text" id="banji" name="banji" />
            </div>
            <div class="a">
                入学年份(届)
                <select name="year">
  <option value ="1998">1998</option>
  <option value ="1999">1999</option>
  <option value="2000">2000</option>
  <option value="2001">2001</option>
<select>
            </div>
            <div class="a">
                生源地<input type="text" id="address" name="address" />
            </div>
            <div class="a">
                备注<input type="text" id="beizhu" name="beizhu" />
            </div>
            <div class="a">
                <button type="submit" class="b">添 加</button>
            </div>
        </form>
    </div>
</body>
</html>

  

posted @ 2019-10-21 21:28  嘻嘻哒丸子  阅读(120)  评论(0编辑  收藏  举报