参考书籍:《J2EE开源编程精要15讲》

MVC(Model View Controller),Model(模型)表示业务逻辑层,View(视图)代表表述层,Controller(控制)表示控制层。

在Java Web应用程序中,

  View部分一般用JSP和HTML构建。客户在View部分提交请求,在业务逻辑层处理后,把结果返回给View部分显示

  Controller部分一般用Servlet组成,把用户的请求发给适当的业务逻辑组件处理;处理后又返回Controller,把结果转发给适当的View组件

  Model部分包括业务逻辑层和数据库访问层,一般由JavaBean或EJB(Enterprise JavaBean,企业级JavaBean)构建。数据访问层也叫数据持久层,与数据库打交道,常用JDBC API或Hibernate构建。

示例:

View部分:

  index.jsp

 <%@ page language="java" import="java.util.*" 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> <body>
<form method="post" action="LoginServlet">
用户名:<input type="text" name="username" size="15"><br><br>
密&nbsp&nbsp码:<input type="password" name="password" size="15"><br><br>
<input type="submit" name="submit" value="登陆"><br>
</form>
</body>
</html>

  main.jsp

 <%@ page language="java" import="java.util.*" 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> <body>
<h1>
<%=session.getAttribute("username") %>,你成功登陆,现已进入主界面!
</h1>
</body>
</html>

  register.jsp

 <%@ page language="java" import="java.util.*" 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> <body>
<h1>
<%=session.getAttribute("username") %>,你未能成功登陆。
<br>现已进入注册页面,请注册你的信息!
</h1>
</body>
</html>

Controller部分:

  LoginServlet.java

 /**
* 控制组件,在web.xml中将<servlet-mapping>标签内的<url-pattern>设置为"/LoginServlet",
* 所以能接受来自index.jsp中action="LoginServlet"的表单的HTTP POST请求
*/
package login; 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 javax.servlet.http.HttpSession; public class LoginServlet extends HttpServlet { /**
* Constructor of the object.
*/
public LoginServlet() {
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 username=request.getParameter("username");
String password=request.getParameter("password"); //生成一个Session对象,在main.jsp和register.jsp中可以根据Session对象获取用户名
HttpSession session=request.getSession(true);
session.removeAttribute("username");
session.setAttribute("username", username); //调用业务逻辑组件,检查该用户是否已注册
LoginHandler login=new LoginHandler();
boolean mark=login.checkLogin(username,password); //根据查询结果跳转
if(mark)
response.sendRedirect("main.jsp");
else
response.sendRedirect("register.jsp");
} /**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
} }

Model部分

  业务逻辑组件,LoginHandler.java

 /**
* 业务逻辑组件,从数据访问组件DBPool中获得数据库链接,检查用户记录是否存在
*/
package login; import java.sql.*; public class LoginHandler {
public LoginHandler(){} Connection conn;
PreparedStatement ps;
ResultSet rs; public boolean checkLogin(String username,String password){
DBPool con=new DBPool();
try{
conn=con.getConnection();
String sql="select * from UserInfo where username=? and password=?";
ps=conn.prepareStatement(sql);
ps.setString(1, username);
ps.setString(2, password);
rs=ps.executeQuery();
if(rs.next()){
conn.close();
return true;
}
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
return false;
}
}

  数据库访问组件,DBPool.java (MySQL数据库)

 /**
* 数据访问组件,数据库类型为MySQL,
* 登陆数据库用户名:"root",
* 密码:"root",
* 数据库:"user",
* 表:"UserInfo"
*/
package login; import java.sql.*; public class DBPool {
public Connection getConnection() throws SQLException{
Connection con=null; try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/user?useUnicode=true&characterEncoding=UTF-8", "root", "root");
}catch(ClassNotFoundException e){
e.printStackTrace();
}
return con;
}
}

配置文件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" 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>Login_Proj</display-name>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>login.LoginServlet</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

应用实例 简单登陆系统:http://pan.baidu.com/s/1eQdAGqI

PS:使用环境Win7 64bit+MyEclipse Professional 2014+phpMyAdmin-2.10.3

Java Web编程的主要组件技术——MVC设计模式的更多相关文章

  1. Java Web编程的主要组件技术——Struts入门

    参考书籍:<J2EE开源编程精要15讲> Struts是一个开源的Java Web框架,很好地实现了MVC设计模式.通过一个配置文件,把各个层面的应用组件联系起来,使组件在程序层面联系较少 ...

  2. Java Web编程的主要组件技术——JDBC

    参考书籍:<J2EE开源编程精要15讲> JDBC(Java DataBase Connectivity)是Java Web应用程序开发的最主要API之一.当向数据库查询数据时,Java应 ...

  3. Java Web编程的主要组件技术——Hibernate核心组件

    参考书籍:<J2EE开源编程精要15讲> Hibernate配置文件 1) hibernate.cfg.xml <?xml version='1.0' encoding='UTF-8 ...

  4. Java Web编程的主要组件技术——Struts核心组件

    参考书籍:<J2EE开源编程精要15讲> Struts配置文件struts-config.xml Struts核心文件,可配置各种组件,包括Form Beans.Actions.Actio ...

  5. Java Web编程的主要组件技术——Servlet

    参考书籍:<J2EE开源编程精要15讲> Servlet是可以处理客户端传来的HTTP请求,并返回响应,由服务器端调用执行,有一定编写规范的Java类. 例如: package test; ...

  6. Java Web编程的主要组件技术——Hibernate入门

    参考书籍:<J2EE开源编程精要15讲> Hibernate是对象/关系映射(ORM,Object/Relational Mapping)的解决方案,就是将Java对象与对象关系映射到关系 ...

  7. Java Web编程的主要组件技术——Struts的高级功能

    参考书籍:<J2EE开源编程精要15讲> Struts对国际化的支持 "国际化"(I18N)指一个应用程序在运行时能根据客户端请求所来的国家/地区.语言的不同显示不同的 ...

  8. Java Web编程的主要组件技术——JSP

    参考书籍:<J2EE开源编程精要15讲> JSP(Java Server Page)页面由HTML代码和嵌入其中的Java代码组成. 简单的JSP页面如: <html> < ...

  9. [原创]java WEB学习笔记19:初识MVC 设计模式:查询,删除 练习(理解思想),小结 ,问题

    本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当 ...

随机推荐

  1. HDU 5486 Difference of Clustering 图论

    题目链接: http://acm.hdu.edu.cn/showproblem.php?pid=5486 题意: 给你每个元素一开始所属的集合和最后所属的集合,问有多少次集合的分离操作,并操作和不变操 ...

  2. C++文件操作之get/getline

    问题描述:                C++ 读取写入文件,其中读取文件使用get和getline方式 参考资料: http://simpleease.blog.163.com/blog/stat ...

  3. 【POJ】【1739】Tony's Tour

    插头DP 楼教主男人八题之一! 要求从左下角走到右下角的哈密顿路径数量. 啊嘞,我只会求哈密顿回路啊……这可怎么搞…… 容易想到:要是把起点和重点直接连上就变成一条回路了……那么我们就连一下~ 我们可 ...

  4. sampler state

    昨天遇到一个非常诡异的错误 samplerstate 无法加大括弧定义 编译器非要一个: 而不要{ 去掉吧'''之后的编译似乎又会报某些ss没method 现在想想 也许是 samplerstate要 ...

  5. 关于make: *** No rule to make target `clean'. Stop.的解决

    在重新编译makefile工程文件时需要用到 #make clean 命令, 但是最近工程使用make clean的时候总是提示: make: *** No rule to make target ` ...

  6. mysqlbinlog工具基于日志恢复详细解释

    如果每天都会生成大量的二进制日志,这些日志长时间不清理的话,将会对磁盘空间带来很大的浪费,所以定期清理日志是DBA维护mysql的一个重要工作 1)RESET MASTER在上面查看日志存放的文件夹中 ...

  7. NET Framework 4 中的新 C# 功能

    http://msdn.microsoft.com/zh-cn/magazine/ff796223.aspx C# 编程语言自 2002 年初次发布以来已经有了极大的改善,可以帮助程序员编写更清晰易懂 ...

  8. 配置sql server2012属性 ms-help://MS.SQLCC.v10/MS.SQLSVR.v10.zh-CHS/s10de_5techref/html/6df812ad-4d80-4503-8a23-47719ce85624.htm

    服务与服务器是两个不同的概念,服务器是提供服务的计算机,配置服务器主要是对内存.处理器.安全性等几个方面配置.由于SQL Server 2005服务器的设置参数比较多,这里选一些比较常用的介绍. 配置 ...

  9. SQL 中的游标实例

    --声明变量 declare @IMType varchar(10),@IMResourceID varchar(10) --定义游标 declare information_cursor curso ...

  10. JsRender系列demo(3)-自定义容器

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...