MVC是三个单词的缩写:M,Model(模型);V,View( 视图 ),C,Control(控制)。
MVC模式的目的就是实现Web系统的职能分工Model层:实现系统的业务逻辑(javaBean)
View层:负责与用户交互,即在界面上展示数据对象给用户(html,jsp)Control层:Model与View之间沟通的桥梁,它可以分派用户的请求并选择恰当的视图以用于显示,同时它也可以解释用户的输入并将它们映射为模型层可执行的操作(Servlet)
下面通过一个登录的实例体现MVC:
项目结构如下:
其中,login.jsp为登录页面;succes.jsp为登陆成功页面;unsuccessful.jsp为登录失败页面
login.jsp:
<body> <center> <form action="UserServlet" method="post"> <h4>登录</h4> <hr/> 姓名:<input type="text" name="username"/><br/> 密码:<input type="password" name="password"/><br/> <input type="submit" value="提交"/> </form> </center> </body>success.jsp:
<body> <center> <h3>登陆成功</h3> <a href="<%=path %>/login.jsp">后退</a> </center> </body>unsuccessful.jsp:
<body> <center> <h3>登陆失败</h3> <a href="<%=path %>/login.jsp">后退</a> </center> </body>
UserServlet.java(获取视图层传过来的参数,并传给模型层,待模型层判断后调转到相应的页面)
package com.mvc.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 com.mvc.javaBean.User; public class UserServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub this.doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub String userName = request.getParameter("username"); String password = request.getParameter("password"); User user = new User(); if(user.validatorUser(userName, password)){ response.sendRedirect("success.jsp"); } else{ response.sendRedirect("unsuccessful.jsp"); } } }
User.java(实现业务逻辑,即验证用户名与密码是否正确,在这里仅仅是验证字符串是否相等,姓名与密码都为“admin”时,登陆成功,也可以加上数据库连接代码)
package com.mvc.javaBean; public class User { public boolean validatorUser(String username, String password){ if(username.equals("admin") && password.equals("admin")){ return true; } else{ return false; } } }
下面是web.xml的配置
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>MVC</display-name> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>UserServlet</servlet-name> <servlet-class>com.mvc.servlet.UserServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UserServlet</servlet-name> <url-pattern>/UserServlet</url-pattern> </servlet-mapping> </web-app>
在该实例中
Model层:User.java
View层:ogin.jsp;succes.jsp;unsuccessful.jspControl层:UserServlet.java
具体代码下载猛点下方
http://download.csdn.net/detail/yezis/6937651