个人觉得这种模式是MVC模式
- 先写一个类,类里面有几个属性。
- 写一个接口。里面有增删改查的方法。 (写在service里)
- 写一个类实现这个接口(实现里面的增删改查等操作) (写在service里)
- 连接数据库
- 写 servlet操作, 处理增删改查的信息。
- Jsp页面 (写页面显示或者上传,添加的页面布局等)与servlet实现交互,从而实现以上功能。
增删改查具体实例如下———— 具体代码:
XinxManager.java
package cn.hpu.service;
import java.util.List;
import cn.hpu.gu.Xinx;
//定义接口 增删改查,获取表单信息,通过id获取信息等方法
public interface XinxManager{
public List<Xinx>getXinxs();
public boolean add(Xinx xin);
public boolean del(String id);
public boolean update( Xinx xin);
public boolean select(String name,String password);
public Xinx getXinxById(String id);
}
//定义一个类实现这个接口的方法
XinxManagerImp.Java
package cn.hpu.service;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import cn.hpu.gu.Xinx;
import cn.hpu.util.util;
import com.mysql.jdbc.PreparedStatement;
public class XinxManagerImp implements XinxManager{
//增加
public boolean add(Xinx xin) {
boolean flag = false;
//定义一个标志,赋值为false
Connection conn = null;
PreparedStatement pst =null;
conn = util.getConnection();
String sql="insert into report( title,speaker ,address ,unit , time,content ,dateposted)values(?,?,?,?,?,?,?)";
//几个参数几个问号,这里id设置的是自增的所以没必要添加
try{
conn = util.getConnection();
pst = (PreparedStatement) conn.prepareStatement(sql);
//pst.setString(1, xin.getId());
//pst.setInt(1, xin.getId());
//get所要添加的信息,set到数据库对应的位置
pst.seString(, xin.getTitle());
pst.setString(2, xin.getSpeaker());
pst.setString(3, xin.getAddress());
pst.setString(4, xin.getUnit());
pst.setString(5, xin.getTime().toString());
pst.setString(6, xin.getContent());
pst.setString(7,xin.getDateposted().toString());
//executeUpdate(sql)是更新数据,
//返回int类型是返回的更新了多少行,也就是受影响的行数,如果为0,则表示无更新
int rows = pst.executeUpdate();
if(rows>0)
{
flag=true;
}
}catch (Exception e) {
e.printStackTrace();
}finally{
util.close(pst, conn);
}
return flag; //返回flag方便后面的获取
}
//删除
public boolean del(String id) {
boolean flag = false;
Connection conn = null;
PreparedStatement pst = null;
conn = util.getConnection();
try{
String sql = "delete from report where id like?";
pst = (PreparedStatement) conn.prepareStatement(sql);
pst.setString(1, id);
int rows = pst.executeUpdate();
if(rows>0){
flag = true;
}
}catch (Exception e) {
e.printStackTrace();
}finally{
util.close(pst, conn);
}
return flag;
}
//查询
public List<Xinx> getXinxs() {
//用到了类型转换 (方法内定义的 public List<Xinx>getXinxs();)
List<Xinx> list = new ArrayList<Xinx>();
Connection conn = null;
ResultSet rs = null; //!!!!!!!
Statement stmt = null;
try{
conn = util.getConnection();
String sql = "select * from report";
//创建Statement (Sql语句的执行环境)
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
//executeQuery(String sqlString)执行查询数据库的SQL,
//eg:SELECT语句,返回一个结果集(ResultSet)
while( rs.next()){ //!!!!
Xinx xin = new Xinx();
// 查询。类的所有成员信息都set出来
xin.setId(rs.getString("id"));
//解读一下,请求获取 字符串,然后都set出来
xin.setSpeaker(rs.getString("speaker")); xin.setAddress(rs.getString("address"));
xin.setTitle(rs.getString("title"));
xin.setTime(rs.getString("time"));
xin.setContent(rs.getString("content"));
xin.setUnit(rs.getString("unit"));
xin.setDateposted(rs.getString("dateposted"));
list.add(xin); //!!!!!!
}
}catch (Exception e) {
e.printStackTrace();
}finally{
util.close(rs, stmt, conn);
}
return list;
}
//修改
public boolean update(Xinx xin){
boolean flag = false;
Connection conn = null;
java.sql.PreparedStatement pst = null;
conn = util.getConnection();
String sql= "update report set title=?,speaker=?,address=?,unit=?,time=?,content=?,dateposted=? where id = "+xin.getId(); //where id = ?"; (两个是一个意思,自where后的东西,是可以替换的,下面会稍作修改,因为多了一个问号)
try{
pst = conn.prepareStatement(sql);
pst.setString(1, xin.getTitle());
pst.setString(2, xin.getSpeaker());
pst.setString(3, xin.getAddress());
pst.setString(4, xin.getUnit());
pst.setString(5, xin.getTime());
pst.setString(6, xin.getContent());
pst.setString(7, xin.getDateposted());
//如果不加这个会出错(Statement parameter 8 not set.)说为设置,所以如果用问号,那就几个问号,设计几个Statement parameter。
//pst.setString(8, xin.getId());
int rows = pst.executeUpdate();
if(rows>0)
{flag = true;}
}catch (Exception e)
{
e.printStackTrace();
}
finally
{
util.close(pst, conn);
}
return flag;
}
//根据id查询它的所有信息
public Xinx getXinxById(String id) {
Connection conn = null;
ResultSet rs = null;
Statement stmt = null;
Xinx xin = new Xinx();
try{
conn = util.getConnection();
String sql = "select * from report where id ="+id;
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
while(rs.next())
{
//测试一下看看获取id了木有
System.out.println(rs.getString("id")+"通过id查询信息");
if(rs.getString("id").equals(id)) {
//查询 显示出来
xin.setId(rs.getString("id"));
xin.setTitle(rs.getString("title"));
xin.setSpeaker(rs.getString("speaker"));
xin.setAddress(rs.getString("address"));
xin.setTime(rs.getString("time"));
xin.setContent(rs.getString("content"));
xin.setUnit(rs.getString("unit"));
xin.setDateposted(rs.getString("dateposted"));
}
}
}catch (Exception e)
{
e.printStackTrace();
}finally
{
util.close(rs, stmt, conn);
}
System.out.println(xin.getId());
return xin;
}
public boolean select(String name, String password) {
// TODO Auto-generated method stub
return false;
}
}
addServlet.java
package cn.hpu.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.hpu.gu.Xinx;
import cn.hpu.service.XinxManager;
import cn.hpu.service.XinxManagerImp;
public class AddServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//防止中文乱码,这样最保险
response.setContentType("text/html;chartset=utf-8");
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
// request.getParameter()获取jsp页面提交的数据
String id = request.getParameter("id");
String title = request.getParameter("title");
String speaker = request.getParameter("speaker");
String address = request.getParameter("address");
String unit = request.getParameter("unit");
String time = request.getParameter("time");
String content = request.getParameter("content");
String dateposted = request.getParameter("dateposted");
Xinx xin = new Xinx();
//xin.setId(0);
xin.setTitle(title);
xin.setSpeaker(speaker);
xin.setAddress(address);
xin.setUnit(unit);
xin.setTime(time);
xin.setContent(content);
xin.setDateposted(dateposted);
XinxManager xm = new XinxManagerImp();
boolean flag = xm.add(xin);
System.out.println("增加这里的"+flag);
if(flag == true )
//跟上面的意思是一样的if(flag)
{
//作用: 增加成功后会调到一个页面,显示出来
Xinx xin1 = xm.getXinxById(id);
//通过id获的这组信息,用setAttribute传到表单页面
request.setAttribute("xin1", xin);
//在 login1.jsp显示新添加的信息,这样一目了然
request.getRequestDispatcher("login1.jsp").forward(request, response);
/*或者直接跳到主页面
//request.setAttribute("param", "success");
System.out.println("添加成功");
//request.getRequestDispatcher("login.jsp").forward(request, response);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>添加成功</TITLE></HEAD>");
out.println(" <BODY>");
out.println("添加成功!!!");
out.println("<a href = ‘login.jsp‘> 返回主页面</a>");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
*/
}else {
//request.setAttribute("param", "failed");
System.out.println("添加失败");
//如果添加失败转发到原来的页面
request.getRequestDispatcher("add.jsp").forward(request, response);
}
}
}
<%@ page language="java" import="java.util.*,cn.hpu.gu.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
Login1.jsp
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP ‘login1.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>
<!-- 修改成功! <a href="login.jsp">返回主界面</a> -->
<h3>增加或者修改后的信息 | <a href="login.jsp">返回主界面</a> </h3>
<table border="1" cellpadding="0" cellspacing="0" width="80%" align="center">
<tr>
<!-- <th>序号</th> -->
<th>题目</th>
<th>主讲</th>
<th>地址</th>
<th>主讲人单位</th>
<th>时间</th>
<th>内容</th>
<th>发布时间</th>
<th>操作</th>
</tr>
<%
// XinxManager xm = new XinxManagerImp();
// List<Xinx> list = xm.getXinxs();
// if(list!=null)
// {
// for(int i=0; i<list.size(); i++)
// {
// Xinx xin = list.get(i);
Xinx xin =(Xinx)request.getAttribute("xin1");
if(xin!=null)
{
%>
<tr>
<!-- <td><%=xin.getId()%></td> -->
<td><%=xin.getTitle() %></td>
<td><%=xin.getSpeaker() %></td>
<td><%=xin.getAddress()%></td>
<td><%=xin.getUnit() %></td>
<td><%=xin.getTime() %></td>
<td><%=xin.getContent() %></td>
<td><%=xin.getDateposted() %></td>
<td>
<a href="DelServlet?id=<%=xin.getId() %>">删除</a>
<a href="UpdateServlet1?id=<%=xin.getId() %>">修改</a>
<!-- 点击修改,执行UpdateServlet1,通过id获取要修改的信息 ,,,转到-->
</td>
</tr>
<%
// }
}
%>
</table>
</body>
</html>
DelServlet.Java
package cn.hpu.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.hpu.service.XinxManager;
import cn.hpu.service.XinxManagerImp;
public class DelServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
XinxManager xm = new XinxManagerImp();
boolean flag = xm.del(id);
if(flag == true)
{
response.sendRedirect("login.jsp");
}
}
}
Search.java 查询的servlet
package cn.hpu.servlet;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.omg.PortableServer.ForwardRequest;
import cn.hpu.gu.Xinx;
import cn.hpu.service.XinxManager;
import cn.hpu.service.XinxManagerImp;
public class Search extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
XinxManager xm = new XinxManagerImp();
List<Xinx> list = xm.getXinxs();
request.setAttribute("list", list);
//转发
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
Login.jsp
<%@ page language="java" import="java.util.*,cn.hpu.gu.*" pageEncoding="utf-8"%>
<%@page import="cn.hpu.service.XinxManager"%>
<%@page import="cn.hpu.service.XinxManagerImp"%>
<%
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>管理员操作页面</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>
<h2>管理信息</h2>
欢迎${sessionScope.loginuser}登陆
<!--
request.getSession().getAttribute() 与 ${sessionScope} 它们都是取值的,
前面的是java代码,写在java源文件中,或者jsp的<%%>中
后面的属于表达式,直接嵌在HTML代码中取值
-->
<a href="add.jsp">添加学生</a> <a href = "index.jsp">退出</a>
<hr/>
<body>
<table border="1" cellpadding="0" cellspacing="0" width="80%" align="center">
<tr>
<!-- <th>序号</th> -->
<th>题目</th>
<th>主讲</th>
<th>地址</th>
<th>主讲人单位</th>
<th>时间</th>
<th>内容</th>
<th>发布时间</th>
<th>操作</th>
</tr>
<%
XinxManager xm = new XinxManagerImp();
List<Xinx> list = xm.getXinxs();
if(list!=null)
{
for(int i=0; i<list.size(); i++)
{
Xinx xin = list.get(i);
%>
<tr>
<!-- <td><%=xin.getId()%></td> -->
<td><%=xin.getTitle() %></td>
<td><%=xin.getSpeaker() %></td>
<td><%=xin.getAddress()%></td>
<td><%=xin.getUnit() %></td>
<td><%=xin.getTime() %></td>
<td><%=xin.getContent() %></td>
<td><%=xin.getDateposted() %></td>
<td>
<a href="DelServlet?id=<%=xin.getId() %>">删除</a>
<a href="UpdateServlet1?id=<%=xin.getId() %>">修改</a>
<!-- 点击修改,执行UpdateServlet1,通过id获取要修改的信息 ,,,转到-->
</td>
</tr>
<%
}
}
%>
</table>
</body>
</html>
UpdateServlet1.java
package cn.hpu.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.hpu.gu.Xinx;
import cn.hpu.service.XinxManager;
import cn.hpu.service.XinxManagerImp;
public class UpdateServlet1 extends HttpServlet {
//通过login.jsp中的修改跳这,(获取数据库中要更改单的信息)
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//通过id获取要修改的信息
String id = request.getParameter("id");
XinxManager xm = new XinxManagerImp();
System.out.println("获取数据库中要更新id的所有信息"+id);
//调用XinxManagerImp.java里的方法
Xinx xin = xm.getXinxById(id);
if(xin != null)
{
//通过id获得的xin的信息用setAttribute方法穿到表单中
request.setAttribute("xin",xin);
//跳转到更改页面
request.getRequestDispatcher("update.jsp").forward(request, response); }
}
}
update.jsp
<%@ page language="java" import="java.util.*,cn.hpu.gu.*" pageEncoding="utf-8"%>
<%
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>修改页面</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>
<%
//表单中通过getAttribute获取setAttribute 传来的xin的信息
Xinx xin =(Xinx)request.getAttribute("xin");
%>
<body>
<h1>修改信息</h1>
<hr/>
<!-- 然后用 xin.getSpeaker() 等分别获的各自对应位置的数据-->
<form action="UpdateServlet" method="post">
<table>
<!--让id跟着表单一快传过去,id设置了style="display: none;"表单页面中id被隐藏看不到-->
<inputname="id"type="text"value="<%=xin.getId()%>"style="display: none;"/>
<tr align="left"> <th> 题 目</th>
<th><input name="title" type="text" value="<%=xin.getTitle()%> "></th>
</tr>
<tr align="left"><th> 主 讲</th>
<th><input name="speaker" type="text" value="<%=xin.getSpeaker() %>"></th>
</tr>
<tr align="left">
<th> 地 址</th> <th><input name="address" type="text" value="<%=xin.getAddress()%>"> </th>
</tr>
<tr align="left">
<th>主讲人单位</th> <th><input name="unit" type="text" value="<%=xin.getUnit() %> "></th>
</tr>
<tr align="left">
<th> 时 间</th> <th><input name="time" type="date" value="<%=xin.getTime() %> "></th>
</tr>
<tr align="left">
<th> 内 容</th> <th ><input name="content" type="text" value=" <%=xin.getContent() %> "></th>
</tr>
<tr align="left">
<th>发布时间</th> <th><input name="dateposted" type="date" value=" <%=xin.getDateposted() %>"></th>
</tr>
<tr align="left">
<th><input type="submit" value=" 修改" /></th>
</tr>
</table>
</form>
<!-- 在form表单中通过action="UpdateServlet" 将数据传到UpdateServlet中,,,转到-->
</body>
</html>
UpdateServlet.java
package cn.hpu.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.hpu.gu.Xinx;
import cn.hpu.service.XinxManager;
import cn.hpu.service.XinxManagerImp;
public class UpdateServlet extends HttpServlet {
//进行数据库中信息修好,也就是重新获取修改后提交的信息
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;chartset=utf-8");
response.setCharacterEncoding("utf-8");
request.setCharacterEncoding("utf-8");
//request.getParameter()方法是 获取Http(这里是更改表单)提交过来的数据
String id = request.getParameter("id");
String title = request.getParameter("title");
String speaker = request.getParameter("speaker");
String address = request.getParameter("address");
String unit = request.getParameter("unit");
String time = request.getParameter("time");
String content = request.getParameter("content");
String dateposted = request.getParameter("dateposted");
XinxManager xm = new XinxManagerImp();
Xinx xin = new Xinx();
//将新数据set进去。。。
xin.setId(id);
xin.setTitle(title);
xin.setSpeaker(speaker);
xin.setAddress(address);
xin.setUnit(unit);
xin.setTime(time);
xin.setContent(content);
xin.setDateposted(dateposted);
//调用update(Xinx xin)方法{里面将get的新数据信息,再set到数据库中,从而完成修改}
boolean flag = xm.update(xin);
System.out.println("修改后提交的信息"+id);
if(flag == true)
{
//例子
//Student stu1 = sm.getStudentById(id);
//request.setAttribute("stu1",stu1);
Xinx xin1 = xm.getXinxById(id);
request.setAttribute("xin1", xin);
request.getRequestDispatcher("login1.jsp").forward(request, response);
System.out.println(xin.getId()+"9999999999999");
//request.getRequestDispatcher("login.jsp").forward(request, response);
}else
{
}
}
}