【Java Web】Jsp+Servlet+JavaBean+MySql入门级MVC实例

创建数据库的代码:


drop database if exists info;
create database info;
use info;
create table infotable(name varchar(20), age varchar(10), mail varchar(100), time date);

jsp文件的代码:

addInfo.jsp代码:

<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
    <form action="servlet/AddInfoServlet" method="post">
    	请登记个人信息:<br>
    	姓名:<input type="text" name="name"/><br>
    	年龄:<input type="text" name="age"/><br>
    	邮箱:<input type="text" name="mail"/><br>
    	<input type="submit" value="提交并查看"/>
    	<input type="reset" value="重置"/>
   	</form>
  </body>
</html>


viewInfo.jsp代码:

<%@ page language="java" contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*,info.*,java.util.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'viewInfo.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
    <center>所有用户信息如下:<hr>
    </center>
    
    <%
    	int infoCount=0;
    	//直接从request中获得所有记录
    	Collection messages=(Collection)request.getAttribute("messages");
    	Iterator it=messages.iterator();
    	while(it.hasNext())
    	{
    		InfoBean message=(InfoBean)it.next();
    		out.println("姓名:"+message.getName()+", 年龄:"+message.getAge()+", 邮箱:"+message.getMail()+", 时间:"+message.getDate()+"<br>");
    		out.print("\n");
    
    	}
    	
	%>
	
	
  </body>
</html>

JavaBean部分的代码:

package info;

public class InfoBean {
	
	private String name;
	private String age;
	private String mail;
	private java.sql.Date date;
	
	public void setName(String name)
	{
		this.name=name;
	}
	
	public String getName()
	{
		return name;
	}
	
	public void setAge(String age)
	{
		this.age=age;
	}
	
	public String getAge()
	{
		return age;
	}
	
	public void setMail(String mail)
	{
		this.mail=mail;
	}
	
	public String getMail()
	{
		return mail;
	}
	
	public void setDate(java.sql.Date date)
	{
		this.date=date;
	}
	
	public java.sql.Date getDate()
	{
		return date;
	}

}

Servlet部分的代码:

AddInfoServlet.java代码:

package info;

import java.util.*;

import java.sql.*;

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AddInfoServlet extends HttpServlet {

	
	private Connection con=null;
	
	/**
	 * Constructor of the object.
	 */
	public AddInfoServlet() {
		//super();
		String CLASSFORNAME="com.mysql.jdbc.Driver";
		String SERVANDDB="jdbc:mysql://127.0.0.1:3306/info";
		String USER="root";
		String PWD="123456";
		try
		{
			Class.forName(CLASSFORNAME).newInstance();
			//建立数据库连接con
			con=DriverManager.getConnection(SERVANDDB,USER,PWD);
			System.out.println( "数据库加载成功" );
		}
		catch(Exception e)
		{
			//e.printStackTrace();//捕捉可能出现的异常
			System.out.println( "数据库加载失败" );
		}
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}
	
	
	
	

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
		
	}
	

	

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		//System.out.println( "post方法" );

		response.setContentType("text/html;charset=gb2312");
		PrintWriter out = response.getWriter();
		
		String name=request.getParameter("name");
		String age=request.getParameter("age");
		String mail=request.getParameter("mail");
		
		try{
			//向表中插入信息
			PreparedStatement stm=con.prepareStatement("insert into infotable values(?,?,?,?)");
			stm.setString(1,name);
			stm.setString(2,age);
			stm.setString(3,mail);
			stm.setDate(4, new java.sql.Date(new java.util.Date().getTime()));
			
			try{
				
				stm.executeUpdate();
				System.out.println( "插入信息成功" );
			}
			catch(Exception e)
			{
				System.out.println( "插入信息失败" );
			}
			
			//将请求转向ViewInfoServlet,用于查询数据库中的所有记录,然后调用JSP界面显示
			RequestDispatcher requestDispatcher=request.getRequestDispatcher("ViewInfoServlet");
			requestDispatcher.forward(request, response);//转发请求到ViewInfoServlet			
			System.out.println( "转发request" );
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		
		
	}
	

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}

ViewInfoServlet.java代码:

package info;

import java.util.*;

import java.sql.*;

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

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ViewInfoServlet extends HttpServlet {

	private Connection con=null;
	
	
	/**
	 * Constructor of the object.
	 */
	public ViewInfoServlet() {
		//super();
		
		String CLASSFORNAME="com.mysql.jdbc.Driver";
		String SERVANDDB="jdbc:mysql://127.0.0.1:3306/info";
		String USER="root";
		String PWD="123456";
		try
		{
			Class.forName(CLASSFORNAME).newInstance();
			//建立数据库连接con
			con=DriverManager.getConnection(SERVANDDB,USER,PWD);
			System.out.println( "view连接数据库成功" );
		}
		catch(Exception e)
		{
			e.printStackTrace();//捕捉可能出现的异常
			System.out.println( "连接数据库失败" );
		}
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request,response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		PrintWriter out = response.getWriter();

		Collection ret=new ArrayList();
		try
		{
			Statement st=con.createStatement();
			
			//查询表中有几条记录
			ResultSet result=st.executeQuery("select count(*) from infotable");
			int infoCount=0;
			if(result.next())
			{
				infoCount=result.getInt(1);//得到infotable表中的记录数
				result.close();
			}
			if(infoCount>0)
			{
				//按照时间顺序查询表infotable中的所有记录
				result=st.executeQuery("select * from infotable order by time desc");
				while(result.next())
				{
					String name=result.getString("name");
					String age=result.getString("age");
					String mail=result.getString("mail");
					java.sql.Date date=result.getDate("time");
					
					//创建InfoBean对象,用于存储数据库中的数据
					InfoBean infoBO=new InfoBean();
					infoBO.setName(name);
					infoBO.setAge(age);
					infoBO.setMail(mail);
					infoBO.setDate(date);
					
					ret.add(infoBO);
				}
				result.close();
				st.close();
			}
			//将所有存储infoBO对象的集合添加到request对象中
			request.setAttribute("messages", ret);
			RequestDispatcher requestDispatcher = request.getRequestDispatcher("/viewInfo.jsp");
			requestDispatcher.forward(request, response);//将request发送出去
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		

	}

	/**
	 * Initialization of the servlet. <br>
	 *
	 * @throws ServletException if an error occurs
	 */
	public void init() throws ServletException {
		// Put your code here
	}

}


填写个人信息界面:




提交之后显示全部的个人信息界面:










  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
A. 本留言本采用jsp+javabean+servlet+mysql B. 本系统运行环境: windows/linux+ jdk1.4+resin(或tomcat)+jdbc+mysql 5.0 目录结构如下: 本版本数据库采用的是MYSQL,使用JDBC驱动,所以要求有MYSQL的JDBC的驱动程序;将驱动程序放在lib目录下,将WEB-INF目录下的web.xml文件考到你的发布目录下,web.xml是一些servlet的指向 同时将打包的note.jar文件放在lib目录下 本程序的所有的javabeanservlet类文件在src目录下 3、配置文件 修改本软件的数据库连接的配置文件在classes目录下,其中“isLog=on”代表打开日志功能,如果是“isLog=off”的话就表示关闭日志, logPath=D:\\jsp\\com\\ntsky\\log日志路径,logFile=DBConnectionManager.log,日志名相关的请看db.properties(解释得很详细) 不过注意在windows下和linux下路径稍微有点区别,在linux下文档为logPath=/www/log 表示在/www/log目录下。 请填写好你的URL访问路径,比如你的jsp在你的发布目录的note下,就请将你的SiteBaseURL设置成“SiteBaseURL=http://127.0.0.1:8080/note/” 端口号可以改 注意note后还有个/ 4、 数据库 数据库采用mysql 数据库的源文件在sql下的mysql.txt 对应的在sql下还有一份note.sql,你可以通过mysql –u root –p note<note.sql文件路径还原note数据库(前提是你的数据库先有一个空的数据库名为note的库)。 5、 系统初始话 请先运行note目录下的jspInIt.jsp,进行后台密码的初始话,管理后台的密码进行了MD5加密,降低了了秘密被人盗用的几率 6、 此留言本实现了MVC模式,完全是通过servlet控制数据,而且使用了连接池,一些基本的类也是完全提供,对学习jspMVC模式有很大的帮助。
Java web是一种使用Java语言进行Web开发的技术栈,它结合了JSPServletJavaBean等技术。学生交流论坛系统可以使用Java web技术来构建。 JSPJavaServer Pages)是一种动态网页开发技术,它允许我们在HTML页面中插入Java代码,从而实现动态内容的生成和展示。在学生交流论坛系统中,我们可以使用JSP来创建前端界面并与后端进行交互。例如,我们可以通过JSP页面显示学生的个人信息、发帖内容等。 Servlet是一种服务器端的Java程序,它能够接受并处理客户端的请求,并生成对应的响应。在学生交流论坛系统中,我们可以使用Servlet来处理用户注册、登录、发帖等操作。Servlet可以通过调用JavaBean的方法来完成具体的业务逻辑。例如,当用户提交注册信息时,Servlet可以调用JavaBean中的方法进行用户信息的验证和存储。 JavaBean是一种Java类,它通常包含私有的成员变量、公共的访问方法和无参数的构造方法。在学生交流论坛系统中,JavaBean可以作为数据模型来存储学生信息、帖子内容等。我们可以通过JavaBean提供的方法来获取、修改和删除这些数据。例如,我们可以定义一个帖子的JavaBean,其中包含标题、内容和发帖时间等属性,以及获取和设置这些属性的方法。 综上所述,Java web技术的JSPServletJavaBean可以协同工作,构建一个学生交流论坛系统。JSP用于前端界面的展示,Servlet用于接受和处理用户的请求,JavaBean用于存储和管理系统的数据。通过这些技术的结合,我们可以实现一个功能完善的学生交流论坛系统。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值