jsp与javabean编程

web前端课程实验 专栏收录该内容
6 篇文章 1 订阅

jspjavabean编程

1、实验内容:

1)增加一个消息留言录入页面msgadd.jsp,用户在输入框输入留言信息,点击“提交”后表单提交给名为messageServletservlet(由其充当控制器),该servlet将请求转发到message.jsp;由message.jsp利用setproperty的办法将数据设置到名为msgjbjavabeanmessageServlet在上述请求转发后,等待2秒钟(确保message.jsp已经处理完毕),然后将msgjb的数据取出来并写入数据库。

 

2)增加一个名为msgshow的消息留言servlet(作为控制器),当用户访问该servlet时,由其读取数据库的消息,并存储到上一步所创建的msgjb(每条记录存到一个msgjb的对象,每个对象都被插入到名为msglistlist对象,最后该list插入到session),并将请求转发到msgshow.jsp,由其读取session里面的list,并遍历每个元素(javabean),通过get方法将具体消息显示在一个表格上。

 

注意:上述连接数据库的配置信息,包括主机,数据库,用户名,密码均不能写死到程序里面,要从配置文件或者servlet初始化参数(web.xml)读取。

2、实验步骤:

(1)首先编写一个名为msgadd.jsp的文件用于录入用户的留言信息,并将信息通过表单发送到servlet,以便做后续的处理。

(2)编写名为messageServlet.servlet(没有进行web.xml文件的配置,因为用的是servlet3.0,所以直接使用注解的方法进行配置的。不过后来由于连接数据库需要从配置文件读取数据,为了方便数据操作,还是手动创建了一个只包含context-param web.xml文件)用于将表单信息转发到message.jsp,再编写message.jsp用于将信息存入到Javabean中,2秒后messageservlet通过读取msgjbjavabean中数据存入数据库中。

(3)编写一个read.html其中只有一个按钮用于查询数据中的信息,数据中读取的输入首先是缓存再Javabean中然后再把它存在list中,插入到session中,之后把它转发到msgshow.jsp中,最后将输入读出来放入表格之中。

3.主要代码

web.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app id="WebApp_ID1">
	<display-name>jspproject</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>
	<context-param>
   <param-name>driver</param-name>
   <param-value>com.mysql.jdbc.Driver</param-value>
   </context-param>
   <context-param>
   <param-name>url</param-name>
   <param-value>jdbc:mysql://localhost:3306/webdb</param-value>
</context-param>
<context-param>
   <param-name>username</param-name>
   <param-value>root</param-value>
</context-param>
<context-param>
   <param-name>password</param-name>
   <param-value>*****</param-value>
</context-param>	
</web-app>

msgadd.jsp文件:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>请写下你的留言</title>
 <style>
        textarea{
            width: 20em;
            height: 10em;
            display: block;
            margin: 10px;
        }

    </style>
</head>
<body>
<div>
    
      <form action="messageServlet" method="post">
       <table>
			<td><label for="name1">用户名字:</label>
			 <td><input type="text" name="name1" id="name1"> 
			 <tr></tr>
			 <br> 
			 <td><label for="name2">留言标题:</label>
			  <td><input type="text" name="name2" id="name2">		
			   <tr></tr>
			  <br>
			   
			      </table>
			        <textarea name="name3" id="name3">请在此处编辑您的留言</textarea>
			    <input type="submit" value="提交"> 
			   
			    <input type="reset" value="重置">
		</form>
   </div>
</body>
</html>

Messageservlet.servlet文件:

package jspproject;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.sql.*;
/**
 * Servlet implementation class messageServlet
 */

//特别要注意@WebInitParam注解应该放置的位置
@WebServlet(name="messageServlet",urlPatterns= {"/messageServlet"}
		
		)

public class messageServlet extends HttpServlet {
	public void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		
		
		
		
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("gb2312");
		PrintWriter out=response.getWriter();
		//将请求转发到message.jsp
		request.getRequestDispatcher("message.jsp").forward(request, response);
		//out.println(""+request.getParameter("name1"));
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		//out.println(""+request.getParameter("name3"));
		msgib msbean=(msgib)request.getAttribute("testmessage");
		//out.print("++++++++++++++++++"+ms.getUser_name());
		
		/***
		 * 数据库链接暂时用程序内置的链接方式,之后再改进
		 */
		try {
			/*Class.forName("com.mysql.jdbc.Driver");
			Connection conn=null;
			conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/webdb", "root","peng");
			*/
			//从配置文件读取链接数据库所需要的各种数据
			String mysqldriver=getServletContext().getInitParameter("driver");
			String mysqlurl=getServletContext().getInitParameter("url");
			String mysqlname=getServletContext().getInitParameter("username");
			String mysqlpassword=getServletContext().getInitParameter("password");
			Class.forName(""+mysqldriver);
			Connection conn=null;
			conn=DriverManager.getConnection(""+mysqlurl, ""+mysqlname,
					""+mysqlpassword);
			
		   PreparedStatement pstmt=conn.prepareStatement(""
		    		+ "INSERT INTO message VALUES(?,?,?)");
		  // request.getAttribute("msgib");
		   
		   pstmt.setString(1, msbean.getUser_name());
		   pstmt.setString(2, msbean.getUser_messagename());
		   pstmt.setString(3, msbean.getUser_message());
		   pstmt.executeUpdate();
		   out.println("数据插入成功********************");
		   
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}	
	}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}

Message.jsp文件:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>message.jsp利用setproperty的办法将数据设置到名为msgjb的javabean</title>
</head>
<jsp:useBean id="messagegather" scope="session" class="jspproject.msgib" />
<jsp:setProperty name="messagegather" property="user_name" param="name1" />
<jsp:setProperty name="messagegather" property="user_messagename" param="name2" />
<jsp:setProperty name="messagegather" property="user_message" param="name3" />

<body>
<%
  String name=messagegather.getUser_name();
  
  request.setAttribute("testmessage", messagegather);
 
  //request.getRequestDispatcher("messageServlet.java").forward(request, response);
  //response.sendRedirect("messageServlet.java");
  
%>
<%=name %>
你的留言提交成功

</body>
</html>

Read.html文件:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>从数据库读取数据到表格</title>
</head>
<body>
<form action="msgshow" method="post">
   
   <input type="submit" value="读取数据">

</form>
</body>
</html>

Msgshow.jsp文件:

<%@ page language="java"  import="java.util.*"  contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"   isELIgnored="false"  %>
 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>将信息显示到表格</title>
</head>
<body>
<table id="tBody" border="1" cellspacing="0" cellpadding="0">
  
<!--  此处应特别主要包的导入,以及jar的导入,还有taglib的设置 -->
   <c:forEach  items="${list}" var="list">
  <tr>
   <td>${list.user_name}</td>
    <td>${list.user_messagename}</td>
   <td>${list.user_message}</td> 
   </tr>
   </c:forEach>
</table>
</body>
</html>

Msgshow.java文件:

package jspproject;

import java.awt.*;
import java.awt.List;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class msgshow
 */
//@WebServlet("/msgshow")
@WebServlet(name="msgshow",urlPatterns= {"/msgshow"}
)
public class msgshow extends HttpServlet {
	public void processRequest(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException{
		
	//	ArrayList list=new ArrayList();
		//*************************************************************************************
		java.util.List<msgib> list=new ArrayList<msgib>();
		/*****************************************************************************************/
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("gb2312");
		PrintWriter out=response.getWriter();
		
		
		/***
		 * 数据库链接暂时用程序内置的链接方式,之后再改进
		 */
		try {
			/*Class.forName("com.mysql.jdbc.Driver");
			Connection conn=null;
			conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/webdb", "root","peng");*/
			
			/*ServletConfig config=getServletConfig();
			String mysqldriver=config.getInitParameter("driver");
			String mysqlurl=config.getInitParameter("url");
			String mysqlname=config.getInitParameter("username");
			String mysqlpassword=config.getInitParameter("password");
			Class.forName(""+mysqldriver);
			Connection conn=null;
			conn=DriverManager.getConnection(""+mysqlurl, ""+mysqlname,
					""+mysqlpassword);
*/			
			
			
			//ServletConfig config=getServletConfig();
			String mysqldriver=getServletContext().getInitParameter("driver");
			String mysqlurl=getServletContext().getInitParameter("url");
			String mysqlname=getServletContext().getInitParameter("username");
			String mysqlpassword=getServletContext().getInitParameter("password");
			Class.forName(""+mysqldriver);
			Connection conn=null;
			conn=DriverManager.getConnection(""+mysqlurl, ""+mysqlname,
					""+mysqlpassword);

		   Statement stm=conn.createStatement();
		   ResultSet rs=stm.executeQuery("SELECT* FROM message");
		   while(rs.next())
		   {
			  msgib msgbean=new msgib();
			  msgbean.setUser_name(rs.getString("user_name"));
			  msgbean.setUser_messagename(rs.getString("user_messagename"));
			  msgbean.setUser_message(rs.getString("user_message"));
			  list.add(msgbean);	
			  
		   }
		   
		   //将数据存入list,并将session转发到msgshow.jsp
		   HttpSession session=request.getSession();
		   session.setAttribute("list", list);
		   request.getRequestDispatcher("msgshow.jsp").forward(request, response);
		   		 
		   
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}

Msgib.java文件:

package jspproject;

public class msgib {
	private String user_name="";
	private String user_messagename="";
	private String user_message="";
	
	public String getUser_name() {
		return user_name;
	}
	public void setUser_name(String user_name) {
		this.user_name = user_name;
	}
	public String getUser_messagename() {
		return user_messagename;
	}
	public void setUser_messagename(String user_messagename) {
		this.user_messagename = user_messagename;
	}
	public String getUser_message() {
		return user_message;
	}
	public void setUser_message(String user_message) {
		this.user_message = user_message;
	}	
}

附录:msgshow1.jsp的第二种方法(使用get获得list中的数据)

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
    <%@ page import="jspproject.*" %>
    <%@ page import="java.util.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
 <table id="tBody" border="1" cellspacing="0" cellpadding="0">
 <%
 java.util.List<msgib> list=(List)session.getAttribute("list");
 for(int i=0;i<list.size();i++)
 {
	 msgib ms=list.get(i);
 %>
	<!--  System.out.println("数据为"+ms.getUser_name()+""+ms.getUser_messagename()+""+ms.getUser_message()); -->	
	<tr>
	<td><%=ms.getUser_name() %></td>
	<td><%=ms.getUser_messagename() %></td>
	<td><%=ms.getUser_message() %></td>	
	</tr>
	
<%  } 
 %>
</table>

</body>
</html>

4、运行结果(截图)及总结:

输入需要留言的信息


说明数据成功存入数据库



通过读取按钮来从数据库读取信息



注意点:

  1. 首先第一个需要注意的就是不能忘了导入各种包
  2. 然后就是各种包应该存放的位置
  3. web.xml文件放在servlet3.0中会出现一个叉但是并不会出错或者编译不成功


  • 0
    点赞
  • 1
    评论
  • 0
    收藏
  • 打赏
    打赏
  • 扫一扫,分享海报

©️2022 CSDN 皮肤主题:大白 设计师:CSDN官方博客 返回首页

打赏作者

兮兮子玉

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值