赞
踩
1. JDBC连接数据库。
2. 对数据库的增删改查操作。
3. 分页操作。
4. 掌握数据库连接及数据处理技术,理解分页技术,掌握一种基本的分页技术。
1、教材8.12.1节 查询成绩。
2、教材8.12.2节 管理学生成绩。
3、教材8.12.3节 小星星广告网。
1.查询成绩
① 实验代码
文件:ch8_1.jsp
- <%@ page contentType="text/html" %>
- <%@ page pageEncoding = "utf-8" %>
- <style>
- #tom{
- font-family:宋体;font-size:28;color:black
- }
- </style>
- <HTML>
- <body bgcolor = "#ffccff">
- <form action="ch8_2.jsp" id="tom" method="post" >
- 输入学号或姓名查询成绩:<br>
- <input type="text" id="tom" name="mess" /><br>
- <input type="submit" id="tom" name="submit" value="按姓名查询"/>
- <input type="submit" id="tom" name="submit" value="按学号查询"/>
- </form>
- </body>
- </HTML>
文件:ch8_2.jsp
- <%@ page contentType="text/html" %>
- <%@ page pageEncoding = "utf-8" %>
- <%@ page import="java.sql.*" %>
- <style>
- #tom{
- font-family:宋体;font-size:18;color:blue
- }
- </style>
- <HTML>
- <body bgcolor="#EEDDFF">
- <%
- request.setCharacterEncoding("utf-8");
- String mess = request.getParameter("mess");
- mess = mess.trim();
- String submit = request.getParameter("submit");
- if(mess.length() == 0){
- response.sendRedirect("ch8_1.jsp");
- return;
- }
- Connection con=null;
- Statement sql;
- ResultSet rs;
- try{
- Class.forName("com.mysql.cj.jdbc.Driver");
- }
- catch(Exception e){
- out.print("<h1>"+e);
- }
- String url = "jdbc:mysql://localhost:3306/student?"+
- "useSSL=false&serverTimezone=CST&characterEncoding=utf-8";
- String user ="root";
- String password ="1234";
- out.print("<table border=1>");
- out.print("<tr>");
- out.print("<th id=tom width=100>"+"学号");
- out.print("<th id=tom width=100>"+"姓名");
- out.print("<th id=tom width=50>"+"数学成绩");
- out.print("<th id=tom width=50>"+"英语成绩");
- out.print("</tr>");
- try{
- con = DriverManager.getConnection(url,user,password);
- sql=con.createStatement();
- String SQL = null;
- if(submit.contains("姓名")){
- SQL = "SELECT * FROM scoreReport where name like '%"+mess+"%'";
- }
- else if(submit.contains("学号")){
- SQL = "SELECT * FROM scoreReport where id='"+mess+"'";
- }
- rs=sql.executeQuery(SQL);
- while(rs.next()) {
- out.print("<tr>");
- out.print("<td id=tom>"+rs.getString(1)+"</td>");
- out.print("<td id=tom>"+rs.getString(2)+"</td>");
- out.print("<td id=tom>"+rs.getInt(3)+"</td>");
- out.print("<td id=tom>"+rs.getInt(4)+"</td>");
- out.print("</tr>") ;
- }
- out.print("</table>");
- con.close();
- }
- catch(SQLException e) {
- out.print("<h1>"+e);
- }
- %>
- </body>
- </HTML>
② 运行结果
2.管理学生成绩
① 实验代码
文件:context.xml
- <?xml version="1.0" encoding="utf-8" ?>
- <Context>
- <Resource
- name = "studentConn"
- type ="javax.sql.DataSource"
- driverClassName = "com.mysql.cj.jdbc.Driver"
- url = "jdbc:mysql://127.0.0.1:3306/student?
- &serverTimezone=CST&characterEncoding=utf-8"
- username ="root"
- password ="1234"
- maxActive ="5"
- maxIdle ="5"
- minIdle ="1"
- maxWait ="5000"
- />
- </Context>
文件:ch8_3.jsp
- <%@ page contentType="text/html" %>
- <%@ page pageEncoding = "utf-8" %>
- <%@ page import="java.sql.*" %>
- <%@ page import="javax.sql.DataSource" %>
- <%@ page import="javax.naming.Context" %>
- <%@ page import="javax.naming.InitialContext" %>
- <style>
- #tom{
- font-family:宋体;font-size:28;color:black
- }
- </style>
- <%
- request.setCharacterEncoding("utf-8");
- Connection con=null;
- PreparedStatement pre=null;
- ResultSet rs;
- Context context =new InitialContext();
- Context contextNeeded=(Context)context.lookup("java:comp/env");
- DataSource ds=
- (DataSource)contextNeeded.lookup("studentConn");
- try{
- con = ds.getConnection();
- }
- catch(Exception exp){ }
- String updateSQL =
- "update scoreReport set name =?,mathScore=?,englishScore=? where id=?";
- String insertSQL ="insert into scoreReport values(?,?,?,?)";
- String deleteSQL ="delete from scoreReport where id =?";
- String querySQL = "select * from scoreReport where id =?";
- String mess = request.getParameter("submit");
- if(mess == null) mess ="";
- String id = request.getParameter("id");
- String name = request.getParameter("name");
- String math = request.getParameter("mathScore");
- String english = request.getParameter("englishScore");
- try{
- if(mess.contains("查看")){
- pre = con.prepareStatement(querySQL);
- pre.setString(1,id);
- rs = pre.executeQuery();
- if(rs.next()){
- id = rs.getString(1);
- name = rs.getString(2);
- math = rs.getString(3);
- english = rs.getString(4);
- }
- }
- else if(mess.contains("更新")){
- pre = con.prepareStatement(updateSQL);
- pre.setString(1,name);
- pre.setInt(2,Integer.parseInt(math));
- pre.setInt(3,Integer.parseInt(english));
- pre.setString(4,id);
- pre.executeUpdate();
- out.print("<h3>更新成功</h3>");
- }
- else if(mess.contains("添加")){
- pre = con.prepareStatement(insertSQL);
- pre.setString(1,id);
- pre.setString(2,name);
- pre.setInt(3,Integer.parseInt(math));
- pre.setInt(4,Integer.parseInt(english));
- pre.executeUpdate();
- out.print("<h3>添加成功</h3>");
- }
- else if(mess.contains("删除")){
- pre = con.prepareStatement(deleteSQL);
- pre.setString(1,id);
- pre.executeUpdate();
- out.print("<h3>删除成功</h3>");
- }
- con.close();//连接放回连接池。
- }
- catch(SQLException e) {
- out.print("<h1>学号不能重复");
- try{
- con.close();//连接放回连接池。
- }
- catch(SQLException exp){}
- }
- %>
- <HTML>
- <body bgcolor = "#ffccff">
- <form action="" id="tom" method="post">
- 输入学号查看或删除(信息):<br>
- <input type="text" id="tom" name="id" size=10 /><br>
- <input type="submit" id="tom" name="submit" value="查看"/>
- <input type="submit" id="tom" name="submit" value="删除"/>
- </form>
- <form action="" id="tom" method="post">
- 更新(或添加)
- <input type="text" id="tom" name="id" value =<%=id%> size=9 />
- 学号的信息:
- <br>姓名:
- <input type="text" id="tom" name="name" value ='<%=name%>'size=11/>
- <br>数学成绩:
- <input type="text" id="tom" name="mathScore" value ='<%=math%>'size=7 />
- <br>英语成绩:
- <input type="text" id="tom" name="englishScore" value ='<%=english%>'size=7/>
- <br><input type="submit" id="tom" name="submit" value="更新"/>
- <input type="submit" id="tom" name="submit" value="添加"/>
- </form>
- </body>
- </HTML>
② 运行结果
3.小星星广告网
① 实验代码
文件:context2.xml
- <?xml version="1.0" encoding="utf-8" ?>
- <Context>
- <Resource
- name = "adverConn"
- type ="javax.sql.DataSource"
- driverClassName = "com.mysql.cj.jdbc.Driver"
- url = "jdbc:mysql://127.0.0.1:3306/adertisement?
- &serverTimezone=CST&characterEncoding=utf-8"
- username ="root"
- password ="1234"
- maxActive ="15"
- maxIdle ="15"
- minIdle ="1"
- maxWait ="1000"
- />
- </Context>
文件:head.jsp
- <style>
- #jerry{
- font-family:隶书;font-size:58;color:blue;
-
- }
- #tom{
- font-family:楷体;font-size:33;color:blue;
-
- }
- </style>
- <div align="center">
- <p id=jerry>小星星广告网</p>
- <table width="600" align="center" border="0" >
- <tr valign="bottom">
- <td id=tom><a href="register.jsp">注册</a></td>
- <td id=tom><a href="login.jsp">登录</a></td>
- <td id=tom><a href="publishAdver.jsp">发布广告</a></td>
- <td id=tom><a href="browseAdver.jsp">浏览广告</a></td>
- <td id=tom><a href="index.jsp">主页</a></td>
- </tr>
- </table>
- </div>
文件:index.jsp
- <%@ page contentType="text/html" %>
- <%@ page pageEncoding = "utf-8" %>
- <title>小星星广告网</title>
- <HEAD><%@ include file="head.txt" %></HEAD>
- <style>
- #ok{
- font-family:楷体;font-size:50;color:green
- }
- </style>
- <HTML>
- <body bgcolor ="pink">
- <center id ="ok">
- 欢迎注册,发布广告。
- </center>
- </body>
- </HTML>
文件:web.xml
- <?xml version="1.0" encoding="utf-8"?>
- <web-app>
- <servlet>
- <servlet-name>registerServlet</servlet-name>
- <servlet-class>handle.data.HandleRegister</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>registerServlet</servlet-name>
- <url-pattern>/registerServlet</url-pattern>
- </servlet-mapping>
- <servlet>
- <servlet-name>loginServlet</servlet-name>
- <servlet-class>handle.data.HandleLogin</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>loginServlet</servlet-name>
- <url-pattern>/loginServlet</url-pattern>
- </servlet-mapping>
- <servlet>
- <servlet-name>upFile</servlet-name>
- <servlet-class>handle.data.UpFile</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>upFile</servlet-name>
- <url-pattern>/upFile</url-pattern>
- </servlet-mapping>
- </web-app>
文件:register.jsp
- <%@ page contentType="text/html" %>
- <%@ page pageEncoding = "utf-8" %>
- <jsp:useBean id="userBean" class="save.data.Register" scope="request"/>
- <HEAD><%@ include file="head.txt" %></HEAD>
- <title>注册页面</title>
- <style>
- #ok{
- font-family:宋体;font-size:26;color:black;
- }
- </style>
- <HTML>
- <body id="ok" bgcolor ="cyan">
- <form action="registerServlet" id=ok method="post">
- 用户名由字母、数字、下划线构成,*注释的项必须填写。<br>
- *用户名称:<input type=text id=ok name="logname" /><br>
- *用户密码:<input type=password id=ok name="password"/><br>
- *重复密码:<input type=password id=ok name="again_password"/><br>
- <input type=submit id=ok value="提交"><tr>
- </form>
- 注册反馈:
- <jsp:getProperty name="userBean" property="logname"/>
- <jsp:getProperty name="userBean" property="backNews" />
- </body>
- </HTML>
文件:Register.java
- package save.data;
- public class Register{
- String logname="",
- backNews="请输入注册信息";
- public void setLogname(String logname){
- this.logname=logname;
- }
- public String getLogname(){
- return logname;
- }
- public void setBackNews(String backNews){
- this.backNews=backNews;
- }
- public String getBackNews(){
- return backNews;
- }
- }
文件:Encrypt.java
- package handle.data;
- public class Encrypt {
- static String encrypt(String sourceString,String password) {
- char [] p= password.toCharArray();
- int n = p.length;
- char [] c = sourceString.toCharArray();
- int m = c.length;
- for(int k=0;k<m;k++){
- int mima=c[k]+p[k%n];
- c[k]=(char)mima;
- }
- return new String(c);
- }
- }
文件:HandleRegister.java
- package handle.data;
- import save.data.Register;
- import java.sql.*;
- import java.io.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
- import javax.sql.DataSource;
- import javax.naming.Context;
- import javax.naming.InitialContext;
- import javax.naming.NamingException;
- public class HandleRegister extends HttpServlet {
- public void init(ServletConfig config) throws ServletException {
- super.init(config);
- }
- public void service(HttpServletRequest request,
- HttpServletResponse response)
- throws ServletException,IOException {
- request.setCharacterEncoding("utf-8");
- Connection con =null;
- PreparedStatement sql=null;
- Register userBean=new Register();
- request.setAttribute("userBean",userBean);
- String logname=request.getParameter("logname").trim();
- String password=request.getParameter("password").trim();
- String again_password=request.getParameter("again_password").trim();
- if(logname==null)
- logname="";
- if(password==null)
- password="";
- if(!password.equals(again_password)) {
- userBean.setBackNews("两次密码不同,注册失败,");
- RequestDispatcher dispatcher=
- request.getRequestDispatcher("register.jsp");
- dispatcher.forward(request, response);
- return;
- }
- boolean isLD=true;
- for(int i=0;i<logname.length();i++){
- char c=logname.charAt(i);
- if(!(Character.isLetterOrDigit(c)||c=='_'))
- isLD=false;
- }
- boolean boo=logname.length()>0&&password.length()>0&&isLD;
- String backNews="";
- try{ Context context = new InitialContext();
- Context contextNeeded =
- (Context)context.lookup("java:comp/env");
- DataSource ds=
- (DataSource)contextNeeded.lookup("adverConn");
- con= ds.getConnection();
- String insertCondition="INSERT INTO user VALUES (?,?)";
- sql=con.prepareStatement(insertCondition);
- if(boo){
- sql.setString(1,logname);
- password =
- Encrypt.encrypt(password,"javajsp");
- sql.setString(2,password);
- int m=sql.executeUpdate();
- if(m!=0){
- backNews="注册成功";
- userBean.setBackNews(backNews);
- userBean.setLogname(logname);
- }
- }
- else {
- backNews="信息填写不完整或名字中有非法字符";
- userBean.setBackNews(backNews);
- }
- con.close();
- }
- catch(SQLException exp){
- backNews="该会员名已被使用,请您更换名字"+exp;
- userBean.setBackNews(backNews);
- }
- catch(NamingException exp){
- backNews="没有设置连接池"+exp;
- userBean.setBackNews(backNews);
- }
- finally{
- try{
- con.close();
- }
- catch(Exception ee){}
- }
- RequestDispatcher dispatcher=
- request.getRequestDispatcher("register.jsp");
- dispatcher.forward(request, response);
- }
- }
文件:login.jsp
- <%@ page contentType="text/html" %>
- <%@ page pageEncoding = "utf-8" %>
- <jsp:useBean id="loginBean" class="save.data.Login" scope="session"/>
- <HEAD><%@ include file="head.txt" %></HEAD>
- <title>登录页面</title>
- <style>
- #tom{
- font-family:宋体;font-size:30;color:black;
- }
- </style>
- <HTML>
- <body id="tom" bgcolor ="pink">
- <form action="loginServlet" method="post">
- 登录用户:<input type="text" id="tom" name="logname" size=12><br>
- 输入密码:<input type="password" id="tom" name="password" size=12><br>
- <input type="submit" id="tom" value="提交"><br>
- 登录反馈信息:<br>
- 登录名称:<br><jsp:getProperty name="loginBean" property="logname"/>
- <jsp:getProperty name="loginBean" property="backNews"/>
- </form>
- </body>
- </HTML>
文件:Login.java
- package save.data;
- import java.util.*;
- public class Login {
- String logname="",
- backNews="未登录";
- public void setLogname(String logname){
- this.logname = logname;
- }
- public String getLogname(){
- return logname;
- }
- public void setBackNews(String s) {
- backNews = s;
- }
- public String getBackNews(){
- return backNews;
- }
- }
文件:HandleLogin.java
- package handle.data;
- import save.data.*;
- import java.sql.*;
- import java.io.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
- import javax.sql.DataSource;
- import javax.naming.Context;
- import javax.naming.InitialContext;
- import javax.naming.NamingException;
- public class HandleLogin extends HttpServlet{
- public void init(ServletConfig config) throws ServletException{
- super.init(config);
- }
- public void service(HttpServletRequest request,
- HttpServletResponse response)
- throws ServletException,IOException{
- request.setCharacterEncoding("utf-8");
- Connection con =null;
- Statement sql;
- String logname=request.getParameter("logname").trim(),
- password=request.getParameter("password").trim();
- password = Encrypt.encrypt(password,"javajsp");
- boolean boo=(logname.length()>0)&&(password.length()>0);
- try{
- Context context = new InitialContext();
- Context contextNeeded=
- (Context)context.lookup("java:comp/env");
- DataSource ds=
- (DataSource)contextNeeded.lookup("adverConn");
- con= ds.getConnection();//使用连接池中的连接。
- String condition="select * from user where logname = '"+
- logname+"' and password ='"+password+"'";
- sql=con.createStatement();
- if(boo){
- ResultSet rs=sql.executeQuery(condition);
- boolean m=rs.next();
- if(m==true){
- //调用登录成功的方法:
- success(request,response,logname,password);
- RequestDispatcher dispatcher=
- request.getRequestDispatcher("login.jsp");
- dispatcher.forward(request,response);
- }
- else{
- String backNews="您输入的用户名不存在,或密码不般配";
- //调用登录失败的方法:
- fail(request,response,logname,backNews);
- }
- }
- else{
- String backNews="请输入用户名和密码";
- fail(request,response,logname,backNews);
- }
- con.close();
- }
- catch(SQLException exp){
- String backNews=""+exp;
- fail(request,response,logname,backNews);
- }
- catch(NamingException exp){
- String backNews="没有设置连接池"+exp;
- fail(request,response,logname,backNews);
- }
- finally{
- try{
- con.close();
- }
- catch(Exception ee){}
- }
- }
- public void success(HttpServletRequest request,
- HttpServletResponse response,
- String logname,String password) {
- Login loginBean=null;
- HttpSession session=request.getSession(true);
- try{ loginBean=(Login)session.getAttribute("loginBean");
- if(loginBean==null){
- loginBean=new Login();
- session.setAttribute("loginBean",loginBean);
- loginBean=(Login)session.getAttribute("loginBean");
- }
- String name =loginBean.getLogname();
- if(name.equals(logname)) {
- loginBean.setBackNews(logname+"已经登录了");
- loginBean.setLogname(logname);
- }
- else { //数据模型存储新的登录用户:
- loginBean.setBackNews(logname+"登录成功");
- loginBean.setLogname(logname);
- }
- }
- catch(Exception ee){
- loginBean=new Login();
- session.setAttribute("loginBean",loginBean);
- loginBean.setBackNews(""+ee);
- loginBean.setLogname(logname);
- }
- }
- public void fail(HttpServletRequest request,
- HttpServletResponse response,
- String logname,String backNews) {
- response.setContentType("text/html;charset=utf-8");
- try {
- PrintWriter out=response.getWriter();
- out.println("<html><body>");
- out.println("<h2>"+logname+"登录反馈结果<br>"+backNews+"</h2>") ;
- out.println("返回登录页面或主页<br>");
- out.println("<a href =login.jsp>登录页面</a>");
- out.println("<br><a href =index.jsp>主页</a>");
- out.println("</body></html>");
- }
- catch(IOException exp){}
- }
- }
文件:publishAdver.jsp
- <%@ page contentType="text/html" %>
- <%@ page pageEncoding = "utf-8" %>
- <HEAD><%@ include file="head.txt" %></HEAD>
- <title>发布广告页面</title>
- <style>
- #tom{
- font-family:宋体;font-size:26;color:black;
- }
- </style>
- <HTML>
- <body id ="tom" bgcolor="#FFBBFF">
- 选择要上传的文件:<br>
- <form action="upFile" method="post" ENCTYPE="multipart/form-data">
- <input type="FILE" name="file" id ="tom" size="45"><br>
- <input type="submit" id ="tom" name ="submit" value="提交">
- </form>
- </body>
- </HTML>
文件:UpFile.java
- package handle.data;
- import save.data.Login;
- import java.io.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
- public class UpFile extends HttpServlet{
- public void init(ServletConfig config) throws ServletException{
- super.init(config);
- }
- public void service(HttpServletRequest request,
- HttpServletResponse response)
- throws ServletException,IOException{
- String backMess ="";
- request.setCharacterEncoding("utf-8");
- Login loginBean=null;
- HttpSession session=request.getSession(true);
- String fileName=null;
- try{
- loginBean = (Login)session.getAttribute("loginBean");
- if(loginBean==null){
- response.sendRedirect("login.jsp");
- return;
- }
- else {
- boolean b =loginBean.getLogname()==null||
- loginBean.getLogname().length()==0;
- if(b){
- response.sendRedirect("login.jsp");
- return;
- }
- }
- }
- catch(Exception exp){
- response.sendRedirect("login.jsp");
- return;
- }
- try{
- String tempFileName=(String)session.getId();
- String webDir = request.getContextPath();
- webDir = webDir.substring(1);
- File f= new File("");
- String path = f.getAbsolutePath();
- int index = path.indexOf("bin");
- String tomcatDir = path.substring(0,index);
- File dir=new File(tomcatDir+"/webapps/"+webDir+"/image");
- dir.mkdir();//建立目录。
- File fileTemp=new File(dir,tempFileName);
- RandomAccessFile randomWrite = new RandomAccessFile(fileTemp,"rw");
- InputStream in=request.getInputStream();
- byte b[]=new byte[10000];
- int n;
- while( (n=in.read(b))!=-1){
- randomWrite.write(b,0,n);
- }
- randomWrite.close();
- in.close();
- RandomAccessFile randomRead=new RandomAccessFile(fileTemp,"r");
- int second=1;
- String secondLine=null;
- while(second<=2) {
- secondLine=randomRead.readLine();
- second++;
- }
- int position=secondLine.lastIndexOf("=");
- fileName=secondLine.substring(position+2,secondLine.length()-1);
- randomRead.seek(0);
- long forthEndPosition=0;
- int forth=1;
- while((n=randomRead.readByte())!=-1&&(forth<=4)){
- if(n=='\n'){
- forthEndPosition=randomRead.getFilePointer();
- forth++;
- }
- }
- byte cc[]=fileName.getBytes("iso-8859-1");
- fileName=new String(cc,"utf-8");
- fileName =(loginBean.getLogname()).concat(fileName);
- File fileUser= new File(dir,fileName);
- randomWrite = new RandomAccessFile(fileUser,"rw");
- randomRead.seek(randomRead.length());
- long endPosition=randomRead.getFilePointer();
- long mark=endPosition;
- int j=1;
- while((mark>=0)&&(j<=6)) {
- mark--;
- randomRead.seek(mark);
- n=randomRead.readByte();
- if(n=='\n'){
- endPosition=randomRead.getFilePointer();
- j++;
- }
- }
- randomRead.seek(forthEndPosition);
- long startPoint=randomRead.getFilePointer();
- while(startPoint<endPosition-1){
- n=randomRead.readByte();
- randomWrite.write(n);
- startPoint=randomRead.getFilePointer();
- }
- randomWrite.close();
- randomRead.close();
- backMess ="上传成功";
- fileTemp.delete();
- }
- catch(Exception ee) {
- backMess ="没有选择文件或上传失败";
- }
- response.setContentType("text/html;charset=utf-8");
- try {
- PrintWriter out=response.getWriter();
- out.println("<html><body>");
- out.println("<h2>"+loginBean.getLogname()+":"+backMess+"</h2>") ;
- out.println("<br>返回主页");
- out.println("<br><a href =index.jsp>主页</a>");
- out.println("</body></html>");
- }
- catch(IOException exp){}
- }
- }
文件:browseAdver.jsp
- <%@ page contentType="text/html" %>
- <%@ page pageEncoding = "utf-8" %>
- <%@ page import="java.sql.*" %>
- <%@ page import="javax.sql.DataSource" %>
- <%@ page import="javax.naming.Context" %>
- <%@ page import="javax.naming.InitialContext" %>
- <HEAD><%@ include file="head.txt" %></HEAD>
- <title>浏览广告页面</title>
- <style>
- #tom{
- font-family:宋体;font-size:26;color:black;
- }
- </style>
- <HTML>
- <body id="tom" bgcolor="#EEDDFF">
- <%
- Context context = new InitialContext();
- Context contextNeeded = (Context)context.lookup("java:comp/env");
- DataSource ds = (DataSource)contextNeeded.lookup("adverConn");
- Connection con =null;
- Statement sql;
- ResultSet rs;
- try{
- con = ds.getConnection();
- sql=con.createStatement();
- String SQL = "SELECT logname FROM user";//SQL语句。
- rs=sql.executeQuery(SQL);
- while(rs.next()) {
- String logname = rs.getString(1);
- out.print("<br><a href = showAdver.jsp?logname="+logname+
- ">浏览"+logname+"发布的广告</a>");
- }
- con.close() ;
- }
- catch(SQLException e) {
- out.print("<h1>"+e);
- }
- finally{
- try{
- con.close();
- }
- catch(Exception ee){}
- }
- %>
- </body>
- </HTML>
文件:showAdver.jsp
- <%@ page contentType="text/html" %>
- <%@ page pageEncoding = "utf-8" %>
- <jsp:useBean id="play" class="save.data.Play" scope="session" />
- <HEAD><%@ include file="head.txt" %></HEAD>
- <title>浏览广告图</title>
- <style>
- #textStyle{
- font-family:宋体;font-size:16;color:blue
- }
- </style>
- <% request.setCharacterEncoding("utf-8");
- %>
- <%
- String logname = request.getParameter("logname");
- String webDir = request.getContextPath();
- webDir = webDir.substring(1);
- %>
- <jsp:setProperty name="play" property="logname" value="<%= logname %>"/>
- <jsp:setProperty name="play" property="webDir" value="<%= webDir %>"/>
- <jsp:setProperty name="play" property="index" param = "index" />
- <HTML>
- <center>
- <body bgcolor="pink">
- <p id=textStyle></p><br><%=play.logname%>的广告:<br>
- <image src = image/<jsp:getProperty name="play" property="showImage"/>
- width =300 height =200></image><br>
- <a href ="?index=<%=play.getIndex()+1 %>&logname=<%= play.logname %>">下一张</a>
- <a href ="?index=<%=play.getIndex()-1 %>&logname=<%= play.logname %>">上一张</a>
- </body>
- <center>
- </HTML>
文件:Play.java
- package save.data;
- import java.io.*;
- import java.util.regex.Pattern;
- import java.util.regex.Matcher;
- public class Play {
- public String logname;
- String pictureName[];
- public String showImage;
- public String webDir="D:\apache-tomcat-8.5.87\webapps\ch8_1\WEB-INF"; //web服务目录的名字。
- public String tomcatDir;
- int index = 0;
- public Play() {
- File f= new File("");
- String path = f.getAbsolutePath();
- int index = path.indexOf("bin");
- tomcatDir = path.substring(0,index);
- }
- public void setLogname(String s){
- showImage="";
- logname = s;
- }
- public void setWebDir(String s) {
- webDir = s;
- File dirImage = new File(tomcatDir+"/webapps/"+webDir+"/image");
- pictureName = dirImage.list(new FileStartName(logname));
- }
- public String getShowImage() {
- try {
- showImage = pictureName[index];
- return showImage;
- }
- catch(Exception exp){
- return "flower.jpg";
- }
- }
- public void setIndex(int i) {
- index = i;
- if(index>=pictureName.length)
- index = 0;
- if(index < 0)
- index = pictureName.length-1;
- }
- public int getIndex() {
- return index ;
- }
- }
- class FileStartName implements FilenameFilter {
- String logname=null;
- Pattern pattern;
- Matcher matcher;
- FileStartName(String logname) {
- this.logname = logname;
- pattern = Pattern.compile(logname);
- }
- public boolean accept(File dir,String name) {
- matcher = pattern.matcher(name);
- if(matcher.find())
- return true;
- else
- return false;
- }
- }
② 运行结果
本次实验应用了MySQL数据库与jsp页面的链接,前两个小实验比较简单,最后一个实验涉及到的页面较多,比较复杂,完成了一整套的小系统。将jsp页面、数据库和Java综合到了一起。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。