当前位置:   article > 正文

JSP实用教程实验八JDBC操作数据库_jsp实验8

jsp实验8

实验八  JDBC操作数据库

一、实验目的

1. JDBC连接数据库

2. 对数据库的增删改查操作。

3. 分页操作。

4. 掌握数据库连接及数据处理技术,理解分页技术,掌握一种基本的分页技术。

二、实验内容

1、教材8.12.1节 查询成绩。

2、教材8.12.2节 管理学生成绩。

3、教材8.12.3节 小星星广告网。

三、实验步骤

1.查询成绩

① 实验代码

文件:ch8_1.jsp

  1. <%@ page contentType="text/html" %>
  2. <%@ page pageEncoding = "utf-8" %>
  3. <style>
  4. #tom{
  5. font-family:宋体;font-size:28;color:black
  6. }
  7. </style>
  8. <HTML>
  9. <body bgcolor = "#ffccff">
  10. <form action="ch8_2.jsp" id="tom" method="post" >
  11. 输入学号或姓名查询成绩:<br>
  12. <input type="text" id="tom" name="mess" /><br>
  13. <input type="submit" id="tom" name="submit" value="按姓名查询"/>
  14. <input type="submit" id="tom" name="submit" value="按学号查询"/>
  15. </form>
  16. </body>
  17. </HTML>

文件:ch8_2.jsp

  1. <%@ page contentType="text/html" %>
  2. <%@ page pageEncoding = "utf-8" %>
  3. <%@ page import="java.sql.*" %>
  4. <style>
  5. #tom{
  6. font-family:宋体;font-size:18;color:blue
  7. }
  8. </style>
  9. <HTML>
  10. <body bgcolor="#EEDDFF">
  11. <%
  12. request.setCharacterEncoding("utf-8");
  13. String mess = request.getParameter("mess");
  14. mess = mess.trim();
  15. String submit = request.getParameter("submit");
  16. if(mess.length() == 0){
  17. response.sendRedirect("ch8_1.jsp");
  18. return;
  19. }
  20. Connection con=null;
  21. Statement sql;
  22. ResultSet rs;
  23. try{
  24. Class.forName("com.mysql.cj.jdbc.Driver");
  25. }
  26. catch(Exception e){
  27. out.print("<h1>"+e);
  28. }
  29. String url = "jdbc:mysql://localhost:3306/student?"+
  30. "useSSL=false&serverTimezone=CST&characterEncoding=utf-8";
  31. String user ="root";
  32. String password ="1234";
  33. out.print("<table border=1>");
  34. out.print("<tr>");
  35. out.print("<th id=tom width=100>"+"学号");
  36. out.print("<th id=tom width=100>"+"姓名");
  37. out.print("<th id=tom width=50>"+"数学成绩");
  38. out.print("<th id=tom width=50>"+"英语成绩");
  39. out.print("</tr>");
  40. try{
  41. con = DriverManager.getConnection(url,user,password);
  42. sql=con.createStatement();
  43. String SQL = null;
  44. if(submit.contains("姓名")){
  45. SQL = "SELECT * FROM scoreReport where name like '%"+mess+"%'";
  46. }
  47. else if(submit.contains("学号")){
  48. SQL = "SELECT * FROM scoreReport where id='"+mess+"'";
  49. }
  50. rs=sql.executeQuery(SQL);
  51. while(rs.next()) {
  52. out.print("<tr>");
  53. out.print("<td id=tom>"+rs.getString(1)+"</td>");
  54. out.print("<td id=tom>"+rs.getString(2)+"</td>");
  55. out.print("<td id=tom>"+rs.getInt(3)+"</td>");
  56. out.print("<td id=tom>"+rs.getInt(4)+"</td>");
  57. out.print("</tr>") ;
  58. }
  59. out.print("</table>");
  60. con.close();
  61. }
  62. catch(SQLException e) {
  63. out.print("<h1>"+e);
  64. }
  65. %>
  66. </body>
  67. </HTML>

② 运行结果

2.管理学生成绩

① 实验代码

文件:context.xml

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <Context>
  3. <Resource
  4. name = "studentConn"
  5. type ="javax.sql.DataSource"
  6. driverClassName = "com.mysql.cj.jdbc.Driver"
  7. url = "jdbc:mysql://127.0.0.1:3306/student?
  8. &amp;serverTimezone=CST&amp;characterEncoding=utf-8"
  9. username ="root"
  10. password ="1234"
  11. maxActive ="5"
  12. maxIdle ="5"
  13. minIdle ="1"
  14. maxWait ="5000"
  15. />
  16. </Context>

 文件:ch8_3.jsp

  1. <%@ page contentType="text/html" %>
  2. <%@ page pageEncoding = "utf-8" %>
  3. <%@ page import="java.sql.*" %>
  4. <%@ page import="javax.sql.DataSource" %>
  5. <%@ page import="javax.naming.Context" %>
  6. <%@ page import="javax.naming.InitialContext" %>
  7. <style>
  8. #tom{
  9. font-family:宋体;font-size:28;color:black
  10. }
  11. </style>
  12. <%
  13. request.setCharacterEncoding("utf-8");
  14. Connection con=null;
  15. PreparedStatement pre=null;
  16. ResultSet rs;
  17. Context context =new InitialContext();
  18. Context contextNeeded=(Context)context.lookup("java:comp/env");
  19. DataSource ds=
  20. (DataSource)contextNeeded.lookup("studentConn");
  21. try{
  22. con = ds.getConnection();
  23. }
  24. catch(Exception exp){ }
  25. String updateSQL =
  26. "update scoreReport set name =?,mathScore=?,englishScore=? where id=?";
  27. String insertSQL ="insert into scoreReport values(?,?,?,?)";
  28. String deleteSQL ="delete from scoreReport where id =?";
  29. String querySQL = "select * from scoreReport where id =?";
  30. String mess = request.getParameter("submit");
  31. if(mess == null) mess ="";
  32. String id = request.getParameter("id");
  33. String name = request.getParameter("name");
  34. String math = request.getParameter("mathScore");
  35. String english = request.getParameter("englishScore");
  36. try{
  37. if(mess.contains("查看")){
  38. pre = con.prepareStatement(querySQL);
  39. pre.setString(1,id);
  40. rs = pre.executeQuery();
  41. if(rs.next()){
  42. id = rs.getString(1);
  43. name = rs.getString(2);
  44. math = rs.getString(3);
  45. english = rs.getString(4);
  46. }
  47. }
  48. else if(mess.contains("更新")){
  49. pre = con.prepareStatement(updateSQL);
  50. pre.setString(1,name);
  51. pre.setInt(2,Integer.parseInt(math));
  52. pre.setInt(3,Integer.parseInt(english));
  53. pre.setString(4,id);
  54. pre.executeUpdate();
  55. out.print("<h3>更新成功</h3>");
  56. }
  57. else if(mess.contains("添加")){
  58. pre = con.prepareStatement(insertSQL);
  59. pre.setString(1,id);
  60. pre.setString(2,name);
  61. pre.setInt(3,Integer.parseInt(math));
  62. pre.setInt(4,Integer.parseInt(english));
  63. pre.executeUpdate();
  64. out.print("<h3>添加成功</h3>");
  65. }
  66. else if(mess.contains("删除")){
  67. pre = con.prepareStatement(deleteSQL);
  68. pre.setString(1,id);
  69. pre.executeUpdate();
  70. out.print("<h3>删除成功</h3>");
  71. }
  72. con.close();//连接放回连接池。
  73. }
  74. catch(SQLException e) {
  75. out.print("<h1>学号不能重复");
  76. try{
  77. con.close();//连接放回连接池。
  78. }
  79. catch(SQLException exp){}
  80. }
  81. %>
  82. <HTML>
  83. <body bgcolor = "#ffccff">
  84. <form action="" id="tom" method="post">
  85. 输入学号查看或删除(信息):<br>
  86. <input type="text" id="tom" name="id" size=10 /><br>
  87. <input type="submit" id="tom" name="submit" value="查看"/>
  88. <input type="submit" id="tom" name="submit" value="删除"/>
  89. </form>
  90. <form action="" id="tom" method="post">
  91. 更新(或添加)
  92. <input type="text" id="tom" name="id" value =<%=id%> size=9 />
  93. 学号的信息:
  94. <br>姓名:
  95. <input type="text" id="tom" name="name" value ='<%=name%>'size=11/>
  96. <br>数学成绩:
  97. <input type="text" id="tom" name="mathScore" value ='<%=math%>'size=7 />
  98. <br>英语成绩:
  99. <input type="text" id="tom" name="englishScore" value ='<%=english%>'size=7/>
  100. <br><input type="submit" id="tom" name="submit" value="更新"/>
  101. <input type="submit" id="tom" name="submit" value="添加"/>
  102. </form>
  103. </body>
  104. </HTML>

② 运行结果

3.小星星广告网

① 实验代码

文件:context2.xml

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <Context>
  3. <Resource
  4. name = "adverConn"
  5. type ="javax.sql.DataSource"
  6. driverClassName = "com.mysql.cj.jdbc.Driver"
  7. url = "jdbc:mysql://127.0.0.1:3306/adertisement?
  8. &amp;serverTimezone=CST&amp;characterEncoding=utf-8"
  9. username ="root"
  10. password ="1234"
  11. maxActive ="15"
  12. maxIdle ="15"
  13. minIdle ="1"
  14. maxWait ="1000"
  15. />
  16. </Context>

 文件:head.jsp

  1. <style>
  2. #jerry{
  3. font-family:隶书;font-size:58;color:blue;
  4. }
  5. #tom{
  6. font-family:楷体;font-size:33;color:blue;
  7. }
  8. </style>
  9. <div align="center">
  10. <p id=jerry>小星星广告网</p>
  11. <table width="600" align="center" border="0" >
  12. <tr valign="bottom">
  13. <td id=tom><a href="register.jsp">注册</a></td>
  14. <td id=tom><a href="login.jsp">登录</a></td>
  15. <td id=tom><a href="publishAdver.jsp">发布广告</a></td>
  16. <td id=tom><a href="browseAdver.jsp">浏览广告</a></td>
  17. <td id=tom><a href="index.jsp">主页</a></td>
  18. </tr>
  19. </table>
  20. </div>

文件:index.jsp

  1. <%@ page contentType="text/html" %>
  2. <%@ page pageEncoding = "utf-8" %>
  3. <title>小星星广告网</title>
  4. <HEAD><%@ include file="head.txt" %></HEAD>
  5. <style>
  6. #ok{
  7. font-family:楷体;font-size:50;color:green
  8. }
  9. </style>
  10. <HTML>
  11. <body bgcolor ="pink">
  12. <center id ="ok">
  13. 欢迎注册,发布广告。
  14. </center>
  15. </body>
  16. </HTML>

文件:web.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <web-app>
  3. <servlet>
  4. <servlet-name>registerServlet</servlet-name>
  5. <servlet-class>handle.data.HandleRegister</servlet-class>
  6. </servlet>
  7. <servlet-mapping>
  8. <servlet-name>registerServlet</servlet-name>
  9. <url-pattern>/registerServlet</url-pattern>
  10. </servlet-mapping>
  11. <servlet>
  12. <servlet-name>loginServlet</servlet-name>
  13. <servlet-class>handle.data.HandleLogin</servlet-class>
  14. </servlet>
  15. <servlet-mapping>
  16. <servlet-name>loginServlet</servlet-name>
  17. <url-pattern>/loginServlet</url-pattern>
  18. </servlet-mapping>
  19. <servlet>
  20. <servlet-name>upFile</servlet-name>
  21. <servlet-class>handle.data.UpFile</servlet-class>
  22. </servlet>
  23. <servlet-mapping>
  24. <servlet-name>upFile</servlet-name>
  25. <url-pattern>/upFile</url-pattern>
  26. </servlet-mapping>
  27. </web-app>

文件:register.jsp

  1. <%@ page contentType="text/html" %>
  2. <%@ page pageEncoding = "utf-8" %>
  3. <jsp:useBean id="userBean" class="save.data.Register" scope="request"/>
  4. <HEAD><%@ include file="head.txt" %></HEAD>
  5. <title>注册页面</title>
  6. <style>
  7. #ok{
  8. font-family:宋体;font-size:26;color:black;
  9. }
  10. </style>
  11. <HTML>
  12. <body id="ok" bgcolor ="cyan">
  13. <form action="registerServlet" id=ok method="post">
  14. 用户名由字母、数字、下划线构成,*注释的项必须填写。<br>
  15. *用户名称:<input type=text id=ok name="logname" /><br>
  16. *用户密码:<input type=password id=ok name="password"/><br>
  17. *重复密码:<input type=password id=ok name="again_password"/><br>
  18. <input type=submit id=ok value="提交"><tr>
  19. </form>
  20. 注册反馈:
  21. <jsp:getProperty name="userBean" property="logname"/>
  22. <jsp:getProperty name="userBean" property="backNews" />
  23. </body>
  24. </HTML>

文件:Register.java

  1. package save.data;
  2. public class Register{
  3. String logname="",
  4. backNews="请输入注册信息";
  5. public void setLogname(String logname){
  6. this.logname=logname;
  7. }
  8. public String getLogname(){
  9. return logname;
  10. }
  11. public void setBackNews(String backNews){
  12. this.backNews=backNews;
  13. }
  14. public String getBackNews(){
  15. return backNews;
  16. }
  17. }

文件:Encrypt.java

  1. package handle.data;
  2. public class Encrypt {
  3. static String encrypt(String sourceString,String password) {
  4. char [] p= password.toCharArray();
  5. int n = p.length;
  6. char [] c = sourceString.toCharArray();
  7. int m = c.length;
  8. for(int k=0;k<m;k++){
  9. int mima=c[k]+p[k%n];
  10. c[k]=(char)mima;
  11. }
  12. return new String(c);
  13. }
  14. }

文件:HandleRegister.java

  1. package handle.data;
  2. import save.data.Register;
  3. import java.sql.*;
  4. import java.io.*;
  5. import javax.servlet.*;
  6. import javax.servlet.http.*;
  7. import javax.sql.DataSource;
  8. import javax.naming.Context;
  9. import javax.naming.InitialContext;
  10. import javax.naming.NamingException;
  11. public class HandleRegister extends HttpServlet {
  12. public void init(ServletConfig config) throws ServletException {
  13. super.init(config);
  14. }
  15. public void service(HttpServletRequest request,
  16. HttpServletResponse response)
  17. throws ServletException,IOException {
  18. request.setCharacterEncoding("utf-8");
  19. Connection con =null;
  20. PreparedStatement sql=null;
  21. Register userBean=new Register();
  22. request.setAttribute("userBean",userBean);
  23. String logname=request.getParameter("logname").trim();
  24. String password=request.getParameter("password").trim();
  25. String again_password=request.getParameter("again_password").trim();
  26. if(logname==null)
  27. logname="";
  28. if(password==null)
  29. password="";
  30. if(!password.equals(again_password)) {
  31. userBean.setBackNews("两次密码不同,注册失败,");
  32. RequestDispatcher dispatcher=
  33. request.getRequestDispatcher("register.jsp");
  34. dispatcher.forward(request, response);
  35. return;
  36. }
  37. boolean isLD=true;
  38. for(int i=0;i<logname.length();i++){
  39. char c=logname.charAt(i);
  40. if(!(Character.isLetterOrDigit(c)||c=='_'))
  41. isLD=false;
  42. }
  43. boolean boo=logname.length()>0&&password.length()>0&&isLD;
  44. String backNews="";
  45. try{ Context context = new InitialContext();
  46. Context contextNeeded =
  47. (Context)context.lookup("java:comp/env");
  48. DataSource ds=
  49. (DataSource)contextNeeded.lookup("adverConn");
  50. con= ds.getConnection();
  51. String insertCondition="INSERT INTO user VALUES (?,?)";
  52. sql=con.prepareStatement(insertCondition);
  53. if(boo){
  54. sql.setString(1,logname);
  55. password =
  56. Encrypt.encrypt(password,"javajsp");
  57. sql.setString(2,password);
  58. int m=sql.executeUpdate();
  59. if(m!=0){
  60. backNews="注册成功";
  61. userBean.setBackNews(backNews);
  62. userBean.setLogname(logname);
  63. }
  64. }
  65. else {
  66. backNews="信息填写不完整或名字中有非法字符";
  67. userBean.setBackNews(backNews);
  68. }
  69. con.close();
  70. }
  71. catch(SQLException exp){
  72. backNews="该会员名已被使用,请您更换名字"+exp;
  73. userBean.setBackNews(backNews);
  74. }
  75. catch(NamingException exp){
  76. backNews="没有设置连接池"+exp;
  77. userBean.setBackNews(backNews);
  78. }
  79. finally{
  80. try{
  81. con.close();
  82. }
  83. catch(Exception ee){}
  84. }
  85. RequestDispatcher dispatcher=
  86. request.getRequestDispatcher("register.jsp");
  87. dispatcher.forward(request, response);
  88. }
  89. }

文件:login.jsp

  1. <%@ page contentType="text/html" %>
  2. <%@ page pageEncoding = "utf-8" %>
  3. <jsp:useBean id="loginBean" class="save.data.Login" scope="session"/>
  4. <HEAD><%@ include file="head.txt" %></HEAD>
  5. <title>登录页面</title>
  6. <style>
  7. #tom{
  8. font-family:宋体;font-size:30;color:black;
  9. }
  10. </style>
  11. <HTML>
  12. <body id="tom" bgcolor ="pink">
  13. <form action="loginServlet" method="post">
  14. 登录用户:<input type="text" id="tom" name="logname" size=12><br>
  15. 输入密码:<input type="password" id="tom" name="password" size=12><br>
  16. <input type="submit" id="tom" value="提交"><br>
  17. 登录反馈信息:<br>
  18. 登录名称:<br><jsp:getProperty name="loginBean" property="logname"/>
  19. <jsp:getProperty name="loginBean" property="backNews"/>
  20. </form>
  21. </body>
  22. </HTML>

文件:Login.java

  1. package save.data;
  2. import java.util.*;
  3. public class Login {
  4. String logname="",
  5. backNews="未登录";
  6. public void setLogname(String logname){
  7. this.logname = logname;
  8. }
  9. public String getLogname(){
  10. return logname;
  11. }
  12. public void setBackNews(String s) {
  13. backNews = s;
  14. }
  15. public String getBackNews(){
  16. return backNews;
  17. }
  18. }

文件:HandleLogin.java

  1. package handle.data;
  2. import save.data.*;
  3. import java.sql.*;
  4. import java.io.*;
  5. import javax.servlet.*;
  6. import javax.servlet.http.*;
  7. import javax.sql.DataSource;
  8. import javax.naming.Context;
  9. import javax.naming.InitialContext;
  10. import javax.naming.NamingException;
  11. public class HandleLogin extends HttpServlet{
  12. public void init(ServletConfig config) throws ServletException{
  13. super.init(config);
  14. }
  15. public void service(HttpServletRequest request,
  16. HttpServletResponse response)
  17. throws ServletException,IOException{
  18. request.setCharacterEncoding("utf-8");
  19. Connection con =null;
  20. Statement sql;
  21. String logname=request.getParameter("logname").trim(),
  22. password=request.getParameter("password").trim();
  23. password = Encrypt.encrypt(password,"javajsp");
  24. boolean boo=(logname.length()>0)&&(password.length()>0);
  25. try{
  26. Context context = new InitialContext();
  27. Context contextNeeded=
  28. (Context)context.lookup("java:comp/env");
  29. DataSource ds=
  30. (DataSource)contextNeeded.lookup("adverConn");
  31. con= ds.getConnection();//使用连接池中的连接。
  32. String condition="select * from user where logname = '"+
  33. logname+"' and password ='"+password+"'";
  34. sql=con.createStatement();
  35. if(boo){
  36. ResultSet rs=sql.executeQuery(condition);
  37. boolean m=rs.next();
  38. if(m==true){
  39. //调用登录成功的方法:
  40. success(request,response,logname,password);
  41. RequestDispatcher dispatcher=
  42. request.getRequestDispatcher("login.jsp");
  43. dispatcher.forward(request,response);
  44. }
  45. else{
  46. String backNews="您输入的用户名不存在,或密码不般配";
  47. //调用登录失败的方法:
  48. fail(request,response,logname,backNews);
  49. }
  50. }
  51. else{
  52. String backNews="请输入用户名和密码";
  53. fail(request,response,logname,backNews);
  54. }
  55. con.close();
  56. }
  57. catch(SQLException exp){
  58. String backNews=""+exp;
  59. fail(request,response,logname,backNews);
  60. }
  61. catch(NamingException exp){
  62. String backNews="没有设置连接池"+exp;
  63. fail(request,response,logname,backNews);
  64. }
  65. finally{
  66. try{
  67. con.close();
  68. }
  69. catch(Exception ee){}
  70. }
  71. }
  72. public void success(HttpServletRequest request,
  73. HttpServletResponse response,
  74. String logname,String password) {
  75. Login loginBean=null;
  76. HttpSession session=request.getSession(true);
  77. try{ loginBean=(Login)session.getAttribute("loginBean");
  78. if(loginBean==null){
  79. loginBean=new Login();
  80. session.setAttribute("loginBean",loginBean);
  81. loginBean=(Login)session.getAttribute("loginBean");
  82. }
  83. String name =loginBean.getLogname();
  84. if(name.equals(logname)) {
  85. loginBean.setBackNews(logname+"已经登录了");
  86. loginBean.setLogname(logname);
  87. }
  88. else { //数据模型存储新的登录用户:
  89. loginBean.setBackNews(logname+"登录成功");
  90. loginBean.setLogname(logname);
  91. }
  92. }
  93. catch(Exception ee){
  94. loginBean=new Login();
  95. session.setAttribute("loginBean",loginBean);
  96. loginBean.setBackNews(""+ee);
  97. loginBean.setLogname(logname);
  98. }
  99. }
  100. public void fail(HttpServletRequest request,
  101. HttpServletResponse response,
  102. String logname,String backNews) {
  103. response.setContentType("text/html;charset=utf-8");
  104. try {
  105. PrintWriter out=response.getWriter();
  106. out.println("<html><body>");
  107. out.println("<h2>"+logname+"登录反馈结果<br>"+backNews+"</h2>") ;
  108. out.println("返回登录页面或主页<br>");
  109. out.println("<a href =login.jsp>登录页面</a>");
  110. out.println("<br><a href =index.jsp>主页</a>");
  111. out.println("</body></html>");
  112. }
  113. catch(IOException exp){}
  114. }
  115. }

文件:publishAdver.jsp

  1. <%@ page contentType="text/html" %>
  2. <%@ page pageEncoding = "utf-8" %>
  3. <HEAD><%@ include file="head.txt" %></HEAD>
  4. <title>发布广告页面</title>
  5. <style>
  6. #tom{
  7. font-family:宋体;font-size:26;color:black;
  8. }
  9. </style>
  10. <HTML>
  11. <body id ="tom" bgcolor="#FFBBFF">
  12. 选择要上传的文件:<br>
  13. <form action="upFile" method="post" ENCTYPE="multipart/form-data">
  14. <input type="FILE" name="file" id ="tom" size="45"><br>
  15. <input type="submit" id ="tom" name ="submit" value="提交">
  16. </form>
  17. </body>
  18. </HTML>

文件:UpFile.java

  1. package handle.data;
  2. import save.data.Login;
  3. import java.io.*;
  4. import javax.servlet.*;
  5. import javax.servlet.http.*;
  6. public class UpFile extends HttpServlet{
  7. public void init(ServletConfig config) throws ServletException{
  8. super.init(config);
  9. }
  10. public void service(HttpServletRequest request,
  11. HttpServletResponse response)
  12. throws ServletException,IOException{
  13. String backMess ="";
  14. request.setCharacterEncoding("utf-8");
  15. Login loginBean=null;
  16. HttpSession session=request.getSession(true);
  17. String fileName=null;
  18. try{
  19. loginBean = (Login)session.getAttribute("loginBean");
  20. if(loginBean==null){
  21. response.sendRedirect("login.jsp");
  22. return;
  23. }
  24. else {
  25. boolean b =loginBean.getLogname()==null||
  26. loginBean.getLogname().length()==0;
  27. if(b){
  28. response.sendRedirect("login.jsp");
  29. return;
  30. }
  31. }
  32. }
  33. catch(Exception exp){
  34. response.sendRedirect("login.jsp");
  35. return;
  36. }
  37. try{
  38. String tempFileName=(String)session.getId();
  39. String webDir = request.getContextPath();
  40. webDir = webDir.substring(1);
  41. File f= new File("");
  42. String path = f.getAbsolutePath();
  43. int index = path.indexOf("bin");
  44. String tomcatDir = path.substring(0,index);
  45. File dir=new File(tomcatDir+"/webapps/"+webDir+"/image");
  46. dir.mkdir();//建立目录。
  47. File fileTemp=new File(dir,tempFileName);
  48. RandomAccessFile randomWrite = new RandomAccessFile(fileTemp,"rw");
  49. InputStream in=request.getInputStream();
  50. byte b[]=new byte[10000];
  51. int n;
  52. while( (n=in.read(b))!=-1){
  53. randomWrite.write(b,0,n);
  54. }
  55. randomWrite.close();
  56. in.close();
  57. RandomAccessFile randomRead=new RandomAccessFile(fileTemp,"r");
  58. int second=1;
  59. String secondLine=null;
  60. while(second<=2) {
  61. secondLine=randomRead.readLine();
  62. second++;
  63. }
  64. int position=secondLine.lastIndexOf("=");
  65. fileName=secondLine.substring(position+2,secondLine.length()-1);
  66. randomRead.seek(0);
  67. long forthEndPosition=0;
  68. int forth=1;
  69. while((n=randomRead.readByte())!=-1&&(forth<=4)){
  70. if(n=='\n'){
  71. forthEndPosition=randomRead.getFilePointer();
  72. forth++;
  73. }
  74. }
  75. byte cc[]=fileName.getBytes("iso-8859-1");
  76. fileName=new String(cc,"utf-8");
  77. fileName =(loginBean.getLogname()).concat(fileName);
  78. File fileUser= new File(dir,fileName);
  79. randomWrite = new RandomAccessFile(fileUser,"rw");
  80. randomRead.seek(randomRead.length());
  81. long endPosition=randomRead.getFilePointer();
  82. long mark=endPosition;
  83. int j=1;
  84. while((mark>=0)&&(j<=6)) {
  85. mark--;
  86. randomRead.seek(mark);
  87. n=randomRead.readByte();
  88. if(n=='\n'){
  89. endPosition=randomRead.getFilePointer();
  90. j++;
  91. }
  92. }
  93. randomRead.seek(forthEndPosition);
  94. long startPoint=randomRead.getFilePointer();
  95. while(startPoint<endPosition-1){
  96. n=randomRead.readByte();
  97. randomWrite.write(n);
  98. startPoint=randomRead.getFilePointer();
  99. }
  100. randomWrite.close();
  101. randomRead.close();
  102. backMess ="上传成功";
  103. fileTemp.delete();
  104. }
  105. catch(Exception ee) {
  106. backMess ="没有选择文件或上传失败";
  107. }
  108. response.setContentType("text/html;charset=utf-8");
  109. try {
  110. PrintWriter out=response.getWriter();
  111. out.println("<html><body>");
  112. out.println("<h2>"+loginBean.getLogname()+":"+backMess+"</h2>") ;
  113. out.println("<br>返回主页");
  114. out.println("<br><a href =index.jsp>主页</a>");
  115. out.println("</body></html>");
  116. }
  117. catch(IOException exp){}
  118. }
  119. }

文件:browseAdver.jsp

  1. <%@ page contentType="text/html" %>
  2. <%@ page pageEncoding = "utf-8" %>
  3. <%@ page import="java.sql.*" %>
  4. <%@ page import="javax.sql.DataSource" %>
  5. <%@ page import="javax.naming.Context" %>
  6. <%@ page import="javax.naming.InitialContext" %>
  7. <HEAD><%@ include file="head.txt" %></HEAD>
  8. <title>浏览广告页面</title>
  9. <style>
  10. #tom{
  11. font-family:宋体;font-size:26;color:black;
  12. }
  13. </style>
  14. <HTML>
  15. <body id="tom" bgcolor="#EEDDFF">
  16. <%
  17. Context context = new InitialContext();
  18. Context contextNeeded = (Context)context.lookup("java:comp/env");
  19. DataSource ds = (DataSource)contextNeeded.lookup("adverConn");
  20. Connection con =null;
  21. Statement sql;
  22. ResultSet rs;
  23. try{
  24. con = ds.getConnection();
  25. sql=con.createStatement();
  26. String SQL = "SELECT logname FROM user";//SQL语句。
  27. rs=sql.executeQuery(SQL);
  28. while(rs.next()) {
  29. String logname = rs.getString(1);
  30. out.print("<br><a href = showAdver.jsp?logname="+logname+
  31. ">浏览"+logname+"发布的广告</a>");
  32. }
  33. con.close() ;
  34. }
  35. catch(SQLException e) {
  36. out.print("<h1>"+e);
  37. }
  38. finally{
  39. try{
  40. con.close();
  41. }
  42. catch(Exception ee){}
  43. }
  44. %>
  45. </body>
  46. </HTML>

文件:showAdver.jsp

  1. <%@ page contentType="text/html" %>
  2. <%@ page pageEncoding = "utf-8" %>
  3. <jsp:useBean id="play" class="save.data.Play" scope="session" />
  4. <HEAD><%@ include file="head.txt" %></HEAD>
  5. <title>浏览广告图</title>
  6. <style>
  7. #textStyle{
  8. font-family:宋体;font-size:16;color:blue
  9. }
  10. </style>
  11. <% request.setCharacterEncoding("utf-8");
  12. %>
  13. <%
  14. String logname = request.getParameter("logname");
  15. String webDir = request.getContextPath();
  16. webDir = webDir.substring(1);
  17. %>
  18. <jsp:setProperty name="play" property="logname" value="<%= logname %>"/>
  19. <jsp:setProperty name="play" property="webDir" value="<%= webDir %>"/>
  20. <jsp:setProperty name="play" property="index" param = "index" />
  21. <HTML>
  22. <center>
  23. <body bgcolor="pink">
  24. <p id=textStyle></p><br><%=play.logname%>的广告:<br>
  25. <image src = image/<jsp:getProperty name="play" property="showImage"/>
  26. width =300 height =200></image><br>
  27. <a href ="?index=<%=play.getIndex()+1 %>&logname=<%= play.logname %>">下一张</a>
  28. <a href ="?index=<%=play.getIndex()-1 %>&logname=<%= play.logname %>">上一张</a>
  29. </body>
  30. <center>
  31. </HTML>

文件:Play.java

  1. package save.data;
  2. import java.io.*;
  3. import java.util.regex.Pattern;
  4. import java.util.regex.Matcher;
  5. public class Play {
  6. public String logname;
  7. String pictureName[];
  8. public String showImage;
  9. public String webDir="D:\apache-tomcat-8.5.87\webapps\ch8_1\WEB-INF"; //web服务目录的名字。
  10. public String tomcatDir;
  11. int index = 0;
  12. public Play() {
  13. File f= new File("");
  14. String path = f.getAbsolutePath();
  15. int index = path.indexOf("bin");
  16. tomcatDir = path.substring(0,index);
  17. }
  18. public void setLogname(String s){
  19. showImage="";
  20. logname = s;
  21. }
  22. public void setWebDir(String s) {
  23. webDir = s;
  24. File dirImage = new File(tomcatDir+"/webapps/"+webDir+"/image");
  25. pictureName = dirImage.list(new FileStartName(logname));
  26. }
  27. public String getShowImage() {
  28. try {
  29. showImage = pictureName[index];
  30. return showImage;
  31. }
  32. catch(Exception exp){
  33. return "flower.jpg";
  34. }
  35. }
  36. public void setIndex(int i) {
  37. index = i;
  38. if(index>=pictureName.length)
  39. index = 0;
  40. if(index < 0)
  41. index = pictureName.length-1;
  42. }
  43. public int getIndex() {
  44. return index ;
  45. }
  46. }
  47. class FileStartName implements FilenameFilter {
  48. String logname=null;
  49. Pattern pattern;
  50. Matcher matcher;
  51. FileStartName(String logname) {
  52. this.logname = logname;
  53. pattern = Pattern.compile(logname);
  54. }
  55. public boolean accept(File dir,String name) {
  56. matcher = pattern.matcher(name);
  57. if(matcher.find())
  58. return true;
  59. else
  60. return false;
  61. }
  62. }

② 运行结果

 

四、实验总结

本次实验应用了MySQL数据库与jsp页面的链接,前两个小实验比较简单,最后一个实验涉及到的页面较多,比较复杂,完成了一整套的小系统。将jsp页面、数据库和Java综合到了一起。

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/575380
推荐阅读
相关标签
  

闽ICP备14008679号