jsp+servlet实现mvc结构示例

//接口 IMsgBox.java

package msg;
import java.util.*;
public interface IMsgBox { 
 public void add(Msg msg);
 public void add(int pos,Msg msg);
 public int remove(int id);
 public void save(Msg msg);
 public List getAll();
 public Msg getById(int id);
}

//M层javaBean, Msg.java文件

package msg;

public class Msg {
 private int id;
 private String title;
 private String content;
 private String note;
 public Msg(){
  
 }
 public Msg(int id,String title,String content,String note){
  this.id=id;
  this.title=title;
  this.content=content;
  this.note=note;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 public String getTitle() {
  return title;
 }
 public void setTitle(String title) {
  this.title = title;
 }
 public String getContent() {
  return content;
 }
 public void setContent(String content) {
  this.content = content;
 }
 public String getNote() {
  return note;
 }
 public void setNote(String note) {
  this.note = note;
 }
 public String toString(){
  return "[id:"+id+",title:"+title+"]";
 }
}

//简单实现SimpleMsgBox .java

package msg.impl;
import java.util.*;
import msg.*;
public class SimpleMsgBox implements IMsgBox{
 private List msgs=new ArrayList();
 public void add(Msg msg){
  msgs.add(msg);
 }
 public void add(int pos,Msg msg){
  msgs.add(pos, msg);
 }
 
 public int remove(int id){
  for(int i=0;i<msgs.size();i++){
   Msg msg=(Msg)msgs.get(i);
   if(msg.getId()==id){
   msgs.remove(i);
   return i;
   }  
  }
  return -1;
 }
 public void save(Msg msg){
  int index=remove(msg.getId());
  if(index!=-1){
   add(index,msg);
  }
  else
  {
   add(msg);
  }
 }
 public List getAll(){
  return msgs;
 }
 public Msg getById(int id){
  for(int i=0;i<msgs.size();i++){
   Msg msg=(Msg)msgs.get(i);
   if(msg.getId()==id){
    return msg;
   } 
  }
  return null;
 } 
}

//数据库实现DbMsgBox.java

package msg.impl;
import java.util.ArrayList;
import java.util.List;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.sun.corba.se.spi.orbutil.fsm.Guard.Result;


import msg.*;
public class DbMsgBox implements IMsgBox{

    String databaseName="dbweb";
    String userName="root";
    String userPassWord="root";
    DbOperation myobj=new DbOperation();
 private List msgs=new ArrayList();
 public void add(Msg msg) {
  // TODO Auto-generated method stub
  return;
 }

 public void add(int pos, Msg msg) {
  // TODO Auto-generated method stub
  msgs.add(pos, msg);
 }

 public List getAll() {
  List<msg.Msg> al=new ArrayList();
  Msg msg=new Msg();
      myobj.init(databaseName, userName, userPassWord);
      ResultSet rs=myobj.executeQuery("select id,title,content,note from tbmsg");
      try{
          while(rs.next())
          {
              int id=rs.getInt("id");
        String title=rs.getString("title").toString();
        String content=rs.getString("content").toString();
        String note=rs.getString("note");
        System.out.println(id);
        System.out.println("id="+id+"  ,title="+title+" ,content="+content+" ,note="+note);
        al.add(new Msg(id,title,content,note));
          }
          }catch(Exception e){
           System.out.println(e);
           }
       return al;
          }
           

 public Msg getById(int id) {
  // TODO Auto-generated method stub
   Msg msg=new Msg();
      myobj.init(databaseName, userName, userPassWord);
      ResultSet rs=myobj.executeQuery("select id,title,content,note from tbmsg where id="+id);
      try{
      if (rs.next())
      {
    String title=rs.getString("title").toString();
    String content=rs.getString("content").toString();
    String note=rs.getString("note");
    msg.setId(id);
    msg.setTitle(title);
    msg.setContent(content);
    msg.setNote(note);
      }
      }catch(Exception e){
       System.out.println(e);
      }
  return msg;
 }

 public int remove(int id) {
  // TODO Auto-generated method stub
  myobj.init(databaseName, userName, userPassWord);
  myobj.executeUpdate("delete from tbmsg where id="+id);
  return id;
 }

 public void save(Msg msg) {
  // TODO Auto-generated method stub
  int id=msg.getId();
  String title=msg.getTitle();
  String content=msg.getContent();
  String note=msg.getNote();
  myobj.init(databaseName, userName, userPassWord);
  myobj.executeUpdate("update dbweb.tbmsg set title='"+title+"',content='"+content+"',note='"+note+"'where id="+id);
 }

}

//MsgContext.java选择用那个类实现接口

package msg;
import msg.impl.*;
public class MsgContext {
 private static IMsgBox mbox;
 public static IMsgBox getMsgBox(){
  if(mbox==null){
   mbox=new SimpleMsgBox();
  }
  return mbox;
 }
 
 public static IMsgBox getMsgboxDB(){
  if (mbox==null){
   mbox=new DbMsgBox();
  }
  return mbox;
 }
}

//C层servlet  ,Control.java

package web;

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 msg.*;
import msg.impl.*;
public class Control extends HttpServlet {

 /**
  * Constructor of the object.
  */
 IMsgBox mbox;
 public Control() {
  super();
 }

 /**
  * 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 myForward1(HttpServletRequest request,HttpServletResponse response,String page){
    try {
     request.getRequestDispatcher("/WEB-INF/page/"+page+".jsp").forward(request,response);
    } catch (ServletException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    } 
   }
    public void myForward(HttpServletRequest request,HttpServletResponse response,String page) throws ServletException{
     try{
      request.getRequestDispatcher(page+".jsp").forward(request,response);
     }
     catch(IOException e){
      e.printStackTrace();
     }
    }
 public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  
            String action=request.getParameter("action");
            if (action==null){
             return;
            }
            String _id=request.getParameter("id");
            int id=-1;
            if(_id!=null)
             id=Integer.parseInt(_id);
            String title=request.getParameter("title");
            String content=request.getParameter("content");
            String note=request.getParameter("note");
            if ("view".equals(action)){
             request.setAttribute("msgs", mbox.getAll());
             myForward(request,response,"view");
             return;
            } 
            if ("_view".equals(action)){
              request.setAttribute("msgs", mbox.getAll());
                myForward(request,response,"manager");
                return;

            }
            if ("detail".equals(action)){
             DbMsgBox obj=new DbMsgBox();
               Msg msg=obj.getById(id);
               request.setAttribute("msg",msg);
               myForward(request,response,"detail");
               return;
            }
            if("edit".equals(action)){
                Msg msg=mbox.getById(id);
                request.setAttribute("msg",msg);
                myForward(request,response,"edit");
                return;
               }
            if("confirm".equals(action)){
                Msg msg=new Msg(id,title,content,note);
                request.setAttribute("msg",msg);
                request.setAttribute("action","save");
                request.setAttribute("button","保存");
                myForward(request,response,"confirm");
                return;
               }
            if("save".equals(action)){
                Msg msg=new Msg(id,title,content,note);
                mbox.save(msg);
                request.setAttribute("msgs", mbox.getAll());
                myForward(request,response,"manager");
                return;
               }

            if("delconfirm".equals(action)){
                request.setAttribute("button","删除");
                Msg msg=mbox.getById(id);
                request.setAttribute("action","delete");//将action设值为delete,并传到client端的confirm.jsp中,等待动作.
                request.setAttribute("msg",msg);
                myForward(request,response,"confirm");
                return;
               }
           if("delete".equals(action)){//先到确认页面,接收action 为delconfirm,后到本页面删除
              mbox.remove(id);//删除消息
           request.setAttribute("msgs", mbox.getAll());//返回当前全部消息,并保存到request对象中
           myForward(request,response,"manager");//前页面重新定位于管理页面
           return;
               }
 }

 /**
  * 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 {
  doGet(request,response);
 }

 /**
  * Initialization of the servlet. <br>
  *
  * @throws ServletException if an error occurs
  */
 public void init() throws ServletException {
  // Put your code here
     mbox=MsgContext.getMsgboxDB();
//    mbox.add(new Msg(1,"hello1","HELLO WORLD1","1wuyan is writer"));
//    mbox.add(new Msg(2,"hello2","HELLO WORLD2","2wuyan is writer"));
//    mbox.add(new Msg(3,"hello3","HELLO WORLD3","3wuyan is writer"));
//    mbox.add(new Msg(4,"hello4","HELLO WORLD4","4wuyan is writer"));
//    mbox.add(new Msg(5,"hello5","HELLO WORLD5","5wuyan is writer"));
 }

}

 

/*****************/

/edit.jsp*/

<%@ page language="java" contentType="text/html; charset=gb2312"
    pageEncoding="gb2312"%>
<!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=gb2312">
<title>Insert title here</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="Control">
  <label>title
  <input type="text" name="title" value="${msg.title}"/>
  </label>
  <p>
    <label>content
    <textarea name="content" rows="5" value="${msg.content}">
    ${msg.content }
    </textarea>
    </label>
  </p>
  <p>
    <label>note
    <input type="text" name="note" value="${msg.note }"/>
    </label>
  </p>
  <p>
    <input name="id" type="hidden" id="id" value="${msg.id}"/>
    <input name="action" type="hidden" value="confirm"/>
  </p>
  <p>
    <label>
    <input type="submit" name="Submit" value="修改" />
    </label>
  </p>
</form>
</body>
</html>

/*detail.jsp*/

<%@ page language="java" contentType="text/html; charset=gb2312"
    pageEncoding="gb2312"%>
<%@page import="java.util.*,msg.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
id:${msg.id}<br/>
title:${msg.title }<br/>
content:${msg.content }<br/>
note:${msg.note }
</body>
</html>

/*view.jsp*/


<%
List aL=(List)request.getAttribute("msgs");
for(int i=0;i<aL.size();i++){
 Msg msg=(Msg)aL.get(i);

 out.println("id:"+msg.getId()+",title:"+msg.getTitle());
 out.println("<a href='?action=detail&id="+msg.getId()+"'>详细信息</a>");
 out.println("<br/>");

}

%>

/*manger.jsp*/

<%
List aL=(List)request.getAttribute("msgs");
for(int i=0;i<aL.size();i++){
 Msg msg=(Msg)aL.get(i);

 out.println("id:"+msg.getId()+",title:"+msg.getTitle());
 out.println("<a href='?action=edit&id="+msg.getId()+"'>修改</a>");
 out.println("<a href='?action=delconfirm&id="+msg.getId()+"'>删除</a>"); 
 out.println("<br/>");

}

%>

/*confirm.java*/

<%@ page language="java" contentType="text/html; charset=gb2312"
    pageEncoding="gb2312"%>
<!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=gb2312">
<title>Confirm</title>
</head>
<body>
<form id="form1" name="form1" method="post" action="Control">
  <label>title
  <input type="text" name="title" value="${msg.title}" readonly="true"/>
  </label>
  <p>
    <label>content
    <textarea name="content" rows="5" value="${msg.content}" readonly="true">
    ${msg.content }
    </textarea>
    </label>
  </p>
  <p>
    <label>note
    <input type="text" name="note" value="${msg.note }" readonly="true"/>
    </label>
  </p>
  <p>
    <input name="id" type="hidden" id="id" value="${msg.id}"/>
    <input name="action" type="hidden" value="${action}"/>
  </p>
  <p>
    <label>
    <input type="submit" name="Submit" value="${button}" />
    </label>
  </p>
</form>


</body>
</html>

你可能感兴趣的:(jsp+servlet实现mvc结构示例)