您的位置:首页 > 编程语言 > Java开发

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

2014-04-17 19:34 459 查看
创建数据库的代码:

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
}

}


填写个人信息界面:



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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: