javaEE实验二 Servlet与JDBC数据库连接201210405214 杨茜婷

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

昆明理工大学信息工程与自动化学院学生实验报告
(2014—2015 学年第一学期)
课程名称:javaEE 开课实验室:信自楼 443 2014 年11月12日
一、实验目的及内容
1.了解JDBC数据库的链接方式,并利用浏览器分别显示数据库中的数据和修改数据库中的数据。

2.学习使用EL来打印另一个javaBean中的属性、内容、数据等。

二、实验原理及基本技术路线图(方框原理图或程序流程图)
1.JDBC 数据库连接:
1) 程序:
Servlet工程中:src/com.city.j2ee.ch02/ShowEmployeeList.java
2) 数据库:student
表:stuinfo
3)字段如下:
1) 程序:
Servlet工程中:src/javaee.ch04/RegisterProcessAction.java
Webroot/register.jsp
Jdbc驱动程序要拷贝到工程的LIB目录下。

2)数据库:cityoa
表:userinfo1
3)字段如下:
2.el与jstl
1)app04a 工程
2)Address.Java ; Employee.java ; EmployeeServlet Page81-83
3)TestEL.java; UserValue.java; el.jsp
三、所用仪器、材料(设备名称、型号、规格等或使用软件)
电脑一台、MyEclipse10、Navicat Lite数据库查看工具
四、实验方法、步骤(或:程序代码或操作过程)
1.打开Navicat Lite,分别创建名为student、cityoa的两个数据库,并分别在两个数据库中建立名为stuinfo、userinfo1的两张表,并按实验要求建立字段,之后保存。

2.在student的数据库的stuinfo表中填入两行信息,然后将填入的信息保存,另外cityoa数据库中的userinfo1表保持原样,不用填入任何信息。

3.将servlet工程导入到myeclipse10的工作空间中,将servlet发布在tomcat7.0上,并运行tomcat7.0。

库中输入的两条信息输出在浏览器的界面上并以表格形式输出。

注册的界面,分别输入登陆账号、密码及用户姓名,点击提交按钮,这时会弹出注册成功的界面,进入cityoa数据库的
userinfo1的表中,这时刚才注册的登陆账号、密码及用户姓名都已经存在表中。

6.将app04a工程导入到myeclipse10的工作空间中,将app04a发布在tomcat
7.0上,并运行tomcat7.0。

在浏览器的地址栏输入http://localhost:8080/app04a/employee,这时在浏览器中输出四行信息。

7.更改程序代码,使程序可以输出更多的信息,比如员工的state、streetName、streetNumber、zipCode、country 等信息。

更改后的程序代码为:
<html>
<head>
<title>Employee</title>
</head>
<body>
accept-language: ${header['accept-language']}
<br/>
session id: ${pageContext.session.id}
<br/>
employee: ${}, ${employee.address.state}
<br/>
capital: ${capitals["Canada"]}
<br/>
state: ${employee.address.city}
<br/>
streetName:${employee.address.streetName}
<br/>
streetNumber:${employee.address.streetNumber}
<br/>
zipCode:${employee.address.zipCode}
<br/>
country:${employee.address.country}
</body>
</html>
更改程序后的输出结果为:
程序源代码:
Servlet工程:
1.Register.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>网上书城-用户注册</title>
</head>
<body>
<center>
<h1>用户注册</h1>
<hr/>
<form action="registerProcess" method="post">
登录帐号:<input type="text" name="userid"/><br/>
登录密码:<input type="password" name="password"/><br/>
确认密码:<input type="password" name="repassword"/><br/>
用户姓名:<input type="text" name="name"/><br/>
<input type="submit" value="提交" />
</form>
<hr/>
</center>
</body>
</html>
2. RegisterProcessAction.java:
package javaee.ch04;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.sql.*;
import javax.servlet.ServletException;
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;
@WebServlet(name = "RegisterProcessAction", urlPatterns = {
"/registerProcess"},
initParams={ } )
//用户注册处理Servlet
//数据库: cityoa 数据表: userinfo1(USERID,PASSWORD,NAME)
public class RegisterProcessAction extends HttpServlet
{
//定义数据库连接对象
private Connection cn=null;
private String driverName=null;//数据库驱动器
private String url=null;//数据库地址URL
private String user=null;
private String password=null;
//初始化方法,取得数据库连接对象
public void init() throws ServletException
{
driverName="com.mysql.jdbc.Driver";
url="jdbc:mysql://localhost/cityoa";
user="root";
password="root";
try
{
Class.forName(driverName);
cn=DriverManager.getConnection(url,user,password);
}
catch(Exception e)
{
System.out.println("取得数据库连接错误:"+e.getMessage());
}
}
//处理GET请求方法
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//取得用户注册表单提交的数据
String userid=request.getParameter("userid");
String password=request.getParameter("password");
String repassword=request.getParameter("repassword");
String name=request.getParameter("name");
//判断登录帐号为空,则自动跳转到注册页面
if(userid==null||userid.trim().length()==0)
{
response.sendRedirect("register.jsp");
}
//如果登录密码为空,自动跳转到注册页面
if(password==null||password.trim().length()==0)
{
response.sendRedirect("register.jsp");
}
//如果确认登录密码为空,自动跳转到注册页面
if(repassword==null||repassword.trim().length()==0)
{
response.sendRedirect("register.jsp");
}
//如果密码和确认密码不符,自动跳转到注册页面
if(!password.equals(repassword))
{
response.sendRedirect("register.jsp");
}
//将姓名进行汉字乱码处理
if(name!=null&&name.trim().length()>0)
{
name=new String(name.getBytes("ISO-8859-1"));
}
//增加新用户处理
String sql="insert into userinfo1(USERID,PASSWORD,NAME) values (?,?,?)";
try
{
PreparedStatement ps=cn.prepareStatement(sql);
ps.setString(1, userid);
ps.setString(2, password);
ps.setString(3, name);
ps.executeUpdate();
ps.close();
//处理结束后,跳转到注册成功提示页面
response.sendRedirect("success.jsp");
}
catch(Exception e)
{
System.out.println("错误:"+e.getMessage());
response.sendRedirect("register.jsp");
}
}
//处理POST请求方法
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request,response);
}
//销毁方法
public void destroy()
{
super.destroy();
try
{
cn.close();
}
catch(Exception e)
{
System.out.println("关闭数据库错误:"+e.getMessage());
}
}
}
3.web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0"
xmlns="/xml/ns/javaee"
xmlns:xsi="/2001/XMLSchema-instance"
xsi:schemaLocation="/xml/ns/javaee
/xml/ns/javaee/web-app_3_0.xsd">
<display-name></display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>ShowEmployeeList</servlet-name>
<servlet-class>com.city.j2ee.ch02.ShowEmployeeList</servlet-class> <init-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost/student</param-value>
</init-param>
<init-param>
<param-name>user</param-name>
<param-value>root</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>root</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ShowEmployeeList</servlet-name>
<url-pattern>/showemployeelist</url-pattern>
</servlet-mapping>
</web-app>
4.ShowEmployeeList.java:
package com.city.j2ee.ch02;
import java.io.IOException;
//数据库:student 数据表: stuinfo
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ShowEmployeeList extends HttpServlet
{private Connection cn=null;
public void init(ServletConfig config) throws ServletException
{ super.init(config);
String driver=config.getInitParameter("driver");
String url=config.getInitParameter("url");
String user=config.getInitParameter("user");
String password=config.getInitParameter("password");
try
{Class.forName(driver);
cn=DriverManager.getConnection(url,user,password);
}
catch (Exception e)
{ System.out.println("Init errors"+e.getMessage());
}
}
public void destroy()
{super.destroy();
try
{if (cn!=null&&(!cn.isClosed()))
{cn.close();
cn=null;}
}
catch (Exception e)
{System.out.println("Destroy errors"+e.getMessage());
}
}
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{response.setContentType("text/html");
response.setCharacterEncoding("GBK");
PrintWriter out=response.getWriter();
out.println("<HTML>");
out.println("<head><title>A SERVLET</title></head>");
out.println("<BODY>");
out.println("<CENTER>");
try
{String sql="select stu_id,stu_name, sex,province,area,nation from stuinfo";
PreparedStatement ps=cn.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
out.println("<h1>学生信息表</h1>");
out.println("<table border=1>");
out.println("<tr>");
out.println("<td>学号</td><td>姓名</td><td>性别</td><td>省份</td><td>成市</td><td>民族</td>"); out.println("</tr>");
while (rs.next())
{out.println("<tr>");
out.println("<td>"+rs.getString("stu_id")+"</TD>");
out.println("<td>"+rs.getString("stu_name")+"</TD>");
out.println("<td>"+rs.getString("sex")+"</TD>");
out.println("<td>"+rs.getString("province")+"</TD>");
out.println("<td>"+rs.getString("area")+"</TD>");
out.println("<td>"+rs.getString("nation")+"</TD>");
out.println("</tr>");
}
rs.close();
ps.close();
out.println("</table>");
}
catch (Exception e)
{out.println("<h2>处理客户端请求发生的错误!"+e.getMessage()+"</h2>");
}
out.println("</center>");
out.println("</body>");
out.println("</html>");
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{doGet(request,response);}
}
app04 工程:
1.address.java
package app04a.model;
public class Address {
private String streetName;
private String streetNumber;
private String city;
private String state;
private String zipCode;
private String country;
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getStreetNumber() {
return streetNumber;
}
public void setStreetNumber(String streetNumber) { this.streetNumber = streetNumber;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
2.employee.java:
package app04a.model;
public class Employee {
private int id;
private String name;
private Address address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
= name;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
3.EmployeeServlet.java
package app04a.servlet;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import app04a.model.Address;
import app04a.model.Employee;
@WebServlet(urlPatterns = {"/employee"})
public class EmployeeServlet extends HttpServlet {
private static final int serialVersionUID = -5392874;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Address address = new Address();
address.setStreetName("Rue D'Anjou");
address.setStreetNumber("5090B");
address.setCity("Brossard");
address.setState("Quebec");
address.setZipCode("A1A B2B");
address.setCountry("Canada");
Employee employee = new Employee();
employee.setId(1099);
employee.setName("Charles Unjeye");
employee.setAddress(address);
request.setAttribute("employee", employee);
Map<String, String> capitals = new HashMap<String,
String>();
capitals.put("China", "Beijing");
capitals.put("Austria", "Vienna");
capitals.put("Australia", "Canberra");
capitals.put("Canada", "Ottawa");
request.setAttribute("capitals", capitals);
RequestDispatcher rd =
request.getRequestDispatcher("/employee.jsp");
rd.forward(request, response);
}
}
4.employee.jsp:
<html>
<head>
<title>Employee</title>
</head>
<body>
accept-language: ${header['accept-language']}
<br/>
session id: ${pageContext.session.id}
<br/>
employee: ${}, ${employee.address.city}
<br/>
capital: ${capitals["Canada"]}
</body>
</html>
五、实验结果、分析和结论(误差分析与数据处理、成果总结等。

其中,绘制曲线图时必须用计算纸或程序运行结果、改进、收获)
在实验的过程中增加了自己解决问题的能力,并且自己也对编程增加了兴趣。

在以后的学习中我要学会多实践、多分析,在不停的改正错误中提高自己。

相关文档
最新文档