后台简单的MVC模式以及前台显示

  • 需要使用jstl的jar包,mysql-connector-java-5.1.39-bin的jar包,MySQL5.5
  • myeclipse2014版在建立web项目时可自动选择添加jstl的jar包,然而,我用的时候在<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>这句就报错了,也许是前面什么地方设置有问题,要是没遇到报错后面的步骤可以忽略。所以又导入了一次jstl的jar包,先点开JSTL 1.2.1Library然后就能看到那两个jar包的位置,把他们复制到WEB-INF下面的lib文件夹下。

再到myeclipse,右击项目,点击属性,Java Build Path->Add External JARs...,添加WEB-INF下lib中那两个jar包。

 

  • 数据库操作:我还是把mysql-connector-java-5.1.39-bin复制到WEB-INF lib下,然后和上面的步骤一样添加jar包(复制到lib文件夹下是想着项目拿到别的电脑上也能运行,但是没试过)。然后Class.forName("com.mysql.jdbc.Driver"); 遇到报错java.lang.ClassNotFoundException: com.mysql.jdbc.Driver,解决办法看http://blog.csdn.net/woaixiaozhe/article/details/7326915

  • 最后

     

  • MVC大概流程目测都差不多,复杂的也只是加了点别的设计模式:
  • 所有的后台代码都放一个packet my里了,因为是个简单的mvc
  •  

  1. index.jsp
    <%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
    <%
    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>
        This is my JSP page. <br>
        <a href="controller?action=display">display</a><br>
        <a href="controller?action=add">add</a>
      </body>
    </html>
    

    index中href="controller?***”对应了后台,相应web.xml里代码

    index页面

     

  2. 点击index页面display后,后台执行相应的程序,代码如下:
    package my;
    
    import java.io.IOException;
    
    import java.io.PrintWriter;
    import java.util.List;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import javax.servlet.RequestDispatcher;//要导入此包!!!
    public class Simplecontroller extends HttpServlet {
    
    	/**
    	 * Constructor of the object.
    	 */
    	public Simplecontroller() {
    		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 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 {
    			String action = request.getParameter("action");
    			String jspPage = "/index.jsp";
    			if("display".equals(action)){
    				DataDao Datadao = new DataDao();
    				List<DataBean> datalist= Datadao.getAll();
    				request.setAttribute("datalist",datalist);
    				jspPage = "/display.jsp";
    			}
    			dispatch(jspPage,request,response);//自定义的转发函数
    	}
    	
    	protected void dispatch(String jspPage,HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
    		if(jspPage!=null){
    			RequestDispatcher rd = request.getRequestDispatcher(jspPage);
    			rd.forward(request, response);
    		}
    	}
    
    	/**
    	 * Initialization of the servlet. <br>
    	 *
    	 * @throws ServletException if an error occurs
    	 */
    	public void init() throws ServletException {
    		// Put your code here
    	}
    
    }
    

      

 里面没写点击add应该执行的代码。

dispatch(jspPage,request,response);将请求转发到display.jsp页面(能转发大概是因为jsp就是个servlet,猜的),点击index.jsp中display后会产生跳转,会跳到display页面,猜是
dispatch(jspPage,request,response);中response是display.jsp页面,没去仔细看dispatch函数功能了。
DataDao Datadao = new DataDao();List<DataBean> datalist= Datadao.getAll();request.setAttribute("datalist",datalist);这部分暂时不用管,返回数据的。

  3.display.jsp代码

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
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 'display.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>
 <h>display pageee</h><br>
    <% /* List<DataBean> data*/// = (List<DataBean>) request.getAttribute("datalist") ;%>
    <c:forEach var="data" items="${requestScope.datalist}">
    	<tr>
    	<td>${data.name}</td>
    	<td>${data.id}</td>
    	</tr>
    </c:forEach>
  </body>
</html>

  这里可以不用jstl,但是没用jstl时候,

<% /* List<DataBean> data*/// = (List<DataBean>) request.getAttribute("datalist") ;%>报错说解析不了List<DataBean>,目测需要把DataBean给import进来(没试),觉得麻烦所以就改用jstl,也
不清楚为什么用jstl时候不用把javaBean导入进来就可以用了javaBean了,是因为var这种变量很强大?还是前面想的都错了?还有<c:>里面不要乱加空格。



  4.SimpleController.java中
DataDao Datadao = new DataDao();List<DataBean> datalist= Datadao.getAll();request.setAttribute("datalist",datalist);对应的程序是

用来产生对象的,

DataBean.java

package my;

public class DataBean {
	
	    private Integer id; 
	    private String name; 
	    
	    public Integer getId() { 
	        return id; 
	    } 
	    public void setId(Integer id) { 
	        this.id = id; 
	    } 
	    public String getname() { 
	        return name; 
	    } 
	    public void setname(String name) { 
	        this.name = name; 
	    } 
	   
	    public DataBean(Integer id, String name) { 
	        super(); 
	        this.id = id; 
	        this.name = name;
	    }
}

  DataDao.java(类名起的也许不太对)

package my;

import java.sql.Connection;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

//import mvctest.DataBean;
import my.DataBean;
public class DataDao {
	 public List<DataBean> getAll(){ 
	        List<DataBean> DataBeans = new ArrayList<DataBean>(); 
	        Connection conn = null; 
	        PreparedStatement ps = null; 
	        ResultSet rs = null; 
	        
	        try { 
	            Class.forName("com.mysql.jdbc.Driver");   
	            String url = "jdbc:mysql://localhost:3306/databean"; 
	            String user = "root"; 
	            String password = "123"; 
	            String sql = "select * from data";
	            
	            conn = DriverManager.getConnection(url, user, password); 
	            if(conn!=null)
	            { ps = conn.prepareStatement(sql); 
	            rs = ps.executeQuery(); 
	            
	            while(rs.next()){ 
	                int id = rs.getInt(1); 
	                String DataBeanName = rs.getString(2); 
	                System.out.print(id);
	                System.out.println(DataBeanName);
	                //int id = 1;
	                //String DataBeanName = "i";
	                System.out.print(id);
	                System.out.println(DataBeanName);
	                DataBean DataBean = new DataBean(id, DataBeanName); 	                
	                DataBeans.add(DataBean); 
	            } }else{System.out.println("数据库连接失败");}
	            
	        }catch (ClassNotFoundException e) { 
	            // TODO Auto-generated catch block 
	            e.printStackTrace(); 
	        } 
	        catch (SQLException e) { 
	            // TODO Auto-generated catch block 
	            e.printStackTrace(); 
	        }finally{ 
	            try { 
	                if(rs != null) 
	                    rs.close(); 
	                if(ps != null) 
	                    ps.close(); 
	                if(conn != null) 
	                    conn.close(); 
	            } catch (SQLException e) { 
	                // TODO Auto-generated catch block 
	                e.printStackTrace(); 
	            } 
	        } 
	        
	        return DataBeans; 
	    }
	 /*public void main(){
		 DataDao A = new DataDao();
		 A.getAll();
	 }*/
}

  

Class.forName("com.mysql.jdbc.Driver");   
	            String url = "jdbc:mysql://localhost:3306/databean"; 
	            String user = "root"; 
	            String password = "123"; 
	            String sql = "select * from data";
	            
	            conn = DriverManager.getConnection(url, user, password); ,databean是用mysql新建的数据库的名字,
Class.forName("com.mysql.jdbc.Driver");是固定的语句,里面不要乱加空格。

最后,整个项目结构;

testmysql.java,JdbcUnits.java是空的,用不着。

数据库

index页面

点击display后

本来是觉得在浏览器中直接输入http://localhost:8080/mvc/controller?action=display时候打不开的,因为找不到他对应哪个后台,后来发现能正常显示,大概是根据controller就找到了对应的后台程序,所以还是要试下才知道的...

posted @ 2016-07-31 11:01  南斗六星  阅读(343)  评论(0编辑  收藏  举报