读取配置文件的例子

时间:2022-08-18 21:01:33

package info;

import java.io.*;
import java.util.Properties;

public class Init {
  private String superName=null;
  private String superPassword=null;
  private String driverName=null;
  private String DBURL=null;
  private String DBUser=null;
  private String DBPassword=null;
  private int pageView;

  public Init(String webPath) {
    Properties prop=new Properties();
    if(!webPath.endsWith(System.getProperty("file.separator"))){
      webPath+=System.getProperty("file.separator");
    }
    try{
      File file=new File(webPath+"WEB-INF"+System.getProperty("file.separator")+"guestbook.properties");
      if(file.exists()){
        FileInputStream fileIn=new FileInputStream(file);
        prop.load(fileIn);
        superName=prop.getProperty("superName");
        superPassword=prop.getProperty("superPassword");
        driverName=prop.getProperty("driverName");
        DBURL=prop.getProperty("DBURL");
        DBUser=prop.getProperty("DBUser");
        DBPassword=prop.getProperty("DBPassword");
        pageView=Integer.parseInt(prop.getProperty("pageView"));
      }
      else{
        throw new FileNotFoundException("属性文件未找到");
      }
    }
    catch(IOException e){
        throw new RuntimeException(e);
    }
    catch(NumberFormatException e){
      throw new RuntimeException(e);
    }
  }
  public String getSuperName(){
    return superName;
  }
  public String getSuperPassword(){
    return superPassword;
  }
  public String getDriverName(){
    return driverName;
  }
  public String getDBURL(){
    return DBURL;
  }
  public String getDBUser(){
    return DBUser;
  }
  public String getDBPassword(){
    return DBPassword;
  }
  public int getPageView(){
    return pageView;
  }
}



配置文件大概格式如下:

#管理员帐号
superName=langzi
#管理员密码
superPassword=wubin
#数据库驱动程序
driverName=com.microsoft.jdbc.sqlserver.SQLServerDriver
#URL("wb"为数据库名)
DBURL=jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=wb
#连接数据库用户名DBUser=sa
#连接数据库密码
DBPassword=wb5520105
#每页记录数
pageView=20




tips:

package info;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import sun.misc.BASE64Decoder;
import javax.sql.DataSource;
import java.sql.*;

public class admin extends HttpServlet {
  private static final String CONTENT_TYPE = "text/html; charset=GB2312";
  private DataSource dataSource=null;
  //Initialize global variables
  public void init() throws ServletException {
    Init init=new Init(getServletContext().getRealPath("/"));
    dataSource=LinkDB.getDB();
    if (dataSource==null) {
      LinkDB.setDB(init.getDriverName(),init.getDBURL(),init.getDBUser(),init.getDBPassword());
      dataSource=LinkDB.getDB();
    }
  }
  //Process the HTTP Get request
  public void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException,
    IOException
  {
    Init init=new Init(getServletContext().getRealPath("/"));
    response.setContentType(CONTENT_TYPE);

    //get authorization header
    String authorization = request.getHeader("Authorization");

    if (authorization == null)
    {
      challenge(response); //no authorization so challenge
    }
    else
    {
      //determine if client is using basic authentication
      if (!authorization.toLowerCase().startsWith("basic"))
      {
        challenge(response); //not basic so challenge
      }

      //取经过base64编码后的帐号和密码,从字符串第六位开始取
      String namePass = authorization.substring(6).trim();

      //instantiate Base64 decoder
      BASE64Decoder decode = new BASE64Decoder();

      //decode username and password
      namePass = new String(decode.decodeBuffer(namePass));

]

      //get username and password from decoded authorization text
      String username = namePass.substring(0, colon);
      String password = namePass.substring(colon+1);

      //validate username and password (case sensitive)
      if (!username.equals(init.getSuperName()) ||!password.equals(init.getSuperPassword()))
      {
        challenge(response); //invalid credentials so challenge
      }
      else
      {
        //验证通过后就写入session
        HttpSession mySession=request.getSession(true);
        mySession.setAttribute("supername",username);
        response.sendRedirect("admin.jsp");
      }
    }
  }

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    request.setCharacterEncoding("GB2312");
    response.setContentType(CONTENT_TYPE);
    PrintWriter out=response.getWriter();
    ReadDB readDB=new ReadDB();
    Connection conn=null;
    Statement stmt=null;
    try{
      conn=dataSource.getConnection();
      stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
      if (request.getParameter("addc") != null) {
        String sql="alter table info_table2 add class"+(readDB.getNum()-1)+" float";
        stmt.executeUpdate(sql);
        out.println("<script>alert('完成');document.location='admin.jsp';</script>");
        return;
      }
      if(request.getParameter("delc")!=null){
        if(request.getParameter("classname").equals(""))
          out.println("<script>alert('请选择要删除的课程');document.location='admin.jsp';</script>");
        else{
          String sql="alter table info_table2 drop column "+request.getParameter("classname");
          stmt.executeUpdate(sql);
          out.println("<script>alert('完成');document.location='admin.jsp';</script>");
        }
        return;
      }
      String id=request.getParameter("id").replaceAll("'","''");
      String s_name=request.getParameter("s_name").replaceAll("'","''");
      String s_sex=request.getParameter("s_sex").replaceAll("'","''");
      String s_birth=request.getParameter("s_birth").replaceAll("'","''");
      String s_grade=request.getParameter("s_grade").replaceAll("'","''");
      float[] classname=new float[readDB.getNum()-2];
      for(int i=1;i<=readDB.getNum()-2;i++)
        classname[i - 1] = Float.parseFloat(request.getParameter("class" + i));
      if(id.equals("")||s_name.equals("")||s_sex.equals("")||s_birth.equals("")||s_grade.equals("")){
        out.println("<script>alert('请将所有信息填写完整');document.location='javascript:history.go(-1);'</script>");
        return;
      }
      if(id.getBytes().length>20||s_name.getBytes().length>50||s_sex.getBytes().length>10||s_birth.getBytes().length>50||s_grade.getBytes().length>50){
        out.println("<script>alert('填写的信息太长了,请重新填写');document.location='javascript:history.go(-1);'</script>");
        return;
      }
      try{
        stmt.executeUpdate("insert into info_table1 values('" + id + "','" +
                           s_name + "','" + s_sex + "','" + s_birth + "','" +
                           s_grade + "','" + Head.getTime() + "')");
        String sql = "insert into info_table2 values('" + id + "','" + s_name +
            "'";
        for (int i = 0; i < classname.length; i++) {
          sql = sql + "," + classname[i];
        }
        sql += ")";
        stmt.executeUpdate(sql);
      }
      catch(SQLException e){
        out.println("<script>alert('写数据库时出错,可能学号有重复');document.location='admin.jsp';</script>");
        return;
      }
      out.println("<script>alert('完成');document.location='admin.jsp';</script>");
    }
    catch(SQLException e){
      out.println(e);
    }
    catch(NumberFormatException e){
      out.println("<script>alert('成绩必须为实数');document.location='javascript:history.go(-1);'</script>");
    }
    finally{
      try{
        stmt.close();
        conn.close();
        LinkDB.shutdownDataSource(dataSource);
      }
      catch(SQLException e){
        out.println(e);
      }
    }
  }

//向浏览器响应401头
  private void challenge(HttpServletResponse response)
  {
    response.setStatus(response.SC_UNAUTHORIZED);
    response.setHeader("WWW-Authenticate", "Basic realm=\"Login\"");
  }
}