MVC模式实例

MVC是一种架构型模式,它本身不引入新的功能,只是指导我们把web应用结构做的更加合理,实现逻辑与页面相分离。

在MVC模式中,应用程序被划分成了模型(Model)、视图(View)和控制器(Controller)三个部分。

1:模型部分包含了应用程序的业务逻辑和业务数据;

2:视图部分封装了应用程序的输出形式,也就是通常所说的页面或者是界面;

3:控制器部分负责协调模型和视图,根据用户请求来选择要调用哪个模型来处理业务,以及最终由哪个视图为用户做出应答。

为何需要MVC

Servlet  === Java + “html”  问题:拼字符串太麻烦  è

Jsp       === Html + Java脚本  问题:页面和逻辑太过于混杂 è

MVC

MVC包含三个部分,功能分别如下:

uModel

封装应用状态                  ------数据封装(vo)

响应状态查询                  ------获取数据(vo)

暴露应用的功能                ------逻辑层API

uController

接收并验证HTTP请求的数据      ------收集数据,封装数据

将用户数据与模型的更新相映射  ------调用逻辑层API

选择用于响应的视图            ------根据返回值选择下一个页面

uView

产生HTML响应                  ------展示数据 

请求模型的更新                ------触发事件

提供HTML form用于用户请求     ------人机交互

 

MVC中的模型和视图是分离的、解耦的,同一个模型可以对应多种不同的视图

MVC的组件关系图描述了模型、视图、控制器这三个部分的交互关系,下面按照交互顺序来详细描述一下它们的交互关系:

(1)首先是展示视图给用户,用户在这个视图上进行操作,并填写一些业务数据

(2)然后用户会点击提交按钮,来发出请求

(3)视图发出的用户请求会到达控制器,在请求中包含了想要完成什么样的业务功能以及相关的数据。

(4)控制器会来处理用户请求,会把请求中的数据进行封装,然后选择并调用合适的模型,请求模型进行状态更新,然后选择接下来要展示给用户的视图。

(5)模型会去处理用户请求的业务功能,同时进行模型状态的维护和更新

(6)当模型状态发生改变的时候,模型会通知相应的视图,告诉视图它的状态发生了改变。

(7)视图接到模型的通知后,会向模型进行状态查询,获取需要展示的数据,然后按照视图本身的展示方式,把这些数据展示出来。

接下来就是等待用户下一次操作,再次从头轮回了

 

 

域模型:域对象封装应用域中的实体

MVC的标准实现方式是:

View用Jsp来实现,Controller用Servlet来实现,Model用JavaBean来实现.而在该实例中,jsp为View,控制器用Struts来实现,模型用hibernate来封装.

 

从控制器如何传递值到Jsp页面?

如果把Jsp页面看作是acting,那么就是从一个action向另外一个action传递参数,方法就是使用request、session或者servletContext之一。

项目文件结构:

 

 

 

配置spring和hibernate

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans 
http://www.springframework.org/schema/beans/spring-beans.xsd 
http://www.springframework.org/schema/tx 
http://www.springframework.org/schema/tx/spring-tx.xsd 
http://www.springframework.org/schema/aop 
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context 
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="src" />
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.microsoft.sqlserver.jdbc.SQLServerDriver">
</property>
<property name="url"
value="jdbc:sqlserver://localhost:1433; DatabaseName=HBZJK">
</property>
<property name="username" value="sa"></property>
<property name="password" value="123456"></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.SQLServerDialect
</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>entity/Info.hbm.xml</value>
<value>entity/BasisInformation.hbm.xml</value>
<value>entity/NonBasis.hbm.xml</value>
<value>entity/Qx.hbm.xml</value></list>
</property>
</bean>
<!-- 事务管理: -->
<!-- 事务管理器 -->

<bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>

<tx:annotation-driven transaction-manager="transactionManager"/> 
<!-- Dao的配置 ===========================-->
<bean id="userDao" class="dao.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<bean id="qestDao" class="dao.QestDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!-- Service的配置 ===========================-->
<bean id="userService" class="service.UserServiceImpl">
<property name="userDao" ref="userDao"/>
</bean>
<bean id="questService" class="service.QuestServiceImpl">
<property name="qestDao" ref="qestDao"/>
</bean>

<!-- Action的配置 ===========================-->
<!-- 用户模块的Action -->
<bean id="loginAction" class="action.LoginAction" scope="prototype">
<property name="userServiceImpl" ref="userService"></property>
</bean>
<bean id="QestAction" class="action.QestAction" scope="prototype">
<property name="questService" ref="questService"></property>
</bean>

<!-- <bean class="dao.SpringContextHolder" lazy-init="false" /> -->



</beans>

配置Struts

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.devMode" value="true"/>
<package name="userjson" namespace="/" extends="json-default"> 
<action name="userJSONAction_*" method="{1}" class="action.LoginAction"> 
<result type="json"> 
<param name="root">result</param> 
</result> 
</action> 
</package> 
<package name="ljson" namespace="/leftPages" extends="json-default"> 
<action name="questJSONAction_*" method="{1}" class="action.QestAction"> 
<result type="json"> 
<param name="root">result</param> 
</result> 
</action> 
</package> 
<package name="action" extends="struts-default" namespace="/">
<action name="LoginAction" class="action.LoginAction" method="login">
<result name="loginSuccess">main.jsp</result> 
<result name="login">login.jsp</result> 
</action>
<action name="regist" class="action.LoginAction" method="add"> 
<result name="input">/register.html</result> 
<result name="success">/zhuce.jsp</result> 
</action> 
<action name="add" class="action.QestAction" method="add"> 
<result name="input">/ask.jsp</result> 
<result name="success">/ask.jsp</result> 
</action> 
</package>
<package name="PassAction" extends="struts-default" namespace="/xgmm">
<action name="passChange" class="action.LoginAction" method="passChange"> 
<result name="input">/xgmm/xgmm.jsp</result> 
<result name="success">/xgmm/xgmm.jsp</result> 
</action> 
</package>
<package name="QestAction" extends="struts-default" namespace="/tjcx">
<action name="QestAction" class="action.QestAction" method="passChange"> 
<result name="success">/tjcx/tjcx_shouye.jsp</result> 
</action> 
</package>
</struts>

登录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>
<title>登陆</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
<!--
body {
margin-left: 0px;
margin-top: 0px;
margin-right: 0px;
margin-bottom: 0px;
background-image: url(../login/loginbg.jpg);
background-repeat: repeat-x;
}
-->
</style>
<script type="text/javascript" src="js/jquery-1.4.js"></script>
<script type="text/javascript" src="login/refresh.js"></script>
<!-- 回车换行 -->
<script language="javascript" for="document" event="onkeydown">

if(event.keyCode==13 && event.srcElement.type!='button' && event.srcElement.type!='submit' && event.srcElement.type!='reset' && event.srcElement.type!='textarea' && event.srcElement.type!='')

event.keyCode=9; //Tab的键值为9 Enter的键值为13

</script>
<script type="text/javascript" >
var msg="${requestScope.tipMessage}"; 
if(msg!=""){
alert(msg);
}

</script>
<script type="text/javascript">

function test()
{
alert("如果丢失密码,请与0311-85813216电话联系!");
}
</script>
<script type="text/javascript">
function MM_swapImgRestore() { //v3.0
var i, x, a = document.MM_sr;
for (i = 0; a && i < a.length && (x = a[i]) && x.oSrc; i++)
x.src = x.oSrc;
}
function MM_preloadImages() { //v3.0


var d = document;
if (d.images) {
if (!d.MM_p)
d.MM_p = new Array();
var i, j = d.MM_p.length, a = MM_preloadImages.arguments;
for (i = 0; i < a.length; i++)
if (a[i].indexOf("#") != 0) {
d.MM_p[j] = new Image;
d.MM_p[j++].src = a[i];
}
}
}

function MM_findObj(n, d) { //v4.01
var p, i, x;
if (!d)
d = document;
if ((p = n.indexOf("?")) > 0 && parent.frames.length) {
d = parent.frames[n.substring(p + 1)].document;
n = n.substring(0, p);
}
if (!(x = d[n]) && d.all)
x = d.all[n];
for (i = 0; !x && i < d.forms.length; i++)
x = d.forms[i][n];
for (i = 0; !x && d.layers && i < d.layers.length; i++)
x = MM_findObj(n, d.layers[i].document);
if (!x && d.getElementById)
x = d.getElementById(n);
return x;
}

function MM_swapImage() { //v3.0
var i, j = 0, x, a = MM_swapImage.arguments;
document.MM_sr = new Array;
for (i = 0; i < (a.length - 2); i += 3)
if ((x = MM_findObj(a[i])) != null) {
document.MM_sr[j++] = x;
if (!x.oSrc)
x.oSrc = x.src;
x.src = a[i + 2];
}
}
function realodpage(){
//alert(document.getElementById("shuaxin").src);
$("#shuaxin").attr("src","login/randCode.jsp");
}
function re(){
setTimeout("realodpage()",10);
}
re();
</script>
</head>
<body bgcolor="#FFFFFF"
onLoad="MM_preloadImages('login/login000_06.jpg','login/loging000_07.jpg')">
<!-- Save for Web Slices (待切.psd) -->
<table width="795" height="475" border="0" align="center"
cellpadding="0" cellspacing="0" id="__01">
<tr>
<td colspan="5"><img src="login/login_01.jpg" width="795"
height="159" alt=""></td>
</tr>
<tr>
<td rowspan="2"><img src="login/login_02.jpg" width="269"
height="174" alt=""></td>
<td bgcolor="#CFE5F2"><img src="login/login_03.jpg" width="66"
height="115" alt=""></td>
<td colspan="2" bgcolor="#D0E6F3"><table width="100%"
height="116" border="0" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2" align="left" valign="bottom"><INPUT
NAME="LoginName" TYPE="text" class="STYLE1"
STYLE="width: 180px; height: 17px; border: #336699 1px solid"
tabindex="1" MAXLENGTH="26" id="username"></td>
</tr>
<tr>
<td height="32" colspan="2" align="left" valign="bottom"><INPUT
NAME="LoginName" TYPE="password" class="STYLE1"
STYLE="width: 180px; height: 17px; border: #336699 1px solid"
tabindex="1" MAXLENGTH="26" id="userpassword"></td>
</tr>
<tr>
<td width="50%" height="29" align="left" valign="bottom"><INPUT
NAME="LoginName" TYPE="text" class="STYLE1"
STYLE="width: 100px; height: 17px; border: #336699 1px solid"
tabindex="1" MAXLENGTH="26" id="randcode"></td>
<td width="50%" align="left" valign="bottom"><img
src="login/randCode.jsp" id='shuaxin' width="50" height="25">
</td>
</tr>
<tr>
<td height="30" colspan="1" align="left" valign="bottom">&nbsp;</td>
</tr>
</table></td>
<td rowspan="2"><img src="login/login_05.jpg" width="262"
height="174" alt=""></td>
</tr>
<tr>
<td colspan="2"><a href="#" onMouseOut="MM_swapImgRestore()"
onMouseOver="MM_swapImage('Image12','','login/loging000_06.jpg',1)"><img
src="login/login_06.jpg" name="Image12" width="135" height="59"
border="0" onClick="IMG1_onclick2()"></a></td>
<td><a href="#" onMouseOut="MM_swapImgRestore()"
onMouseOver="MM_swapImage('Image13','','login/loging000_08.png',1)"><img
src="login/login_09.png" name="Image13" width="129" height="59"
border="0" onClick="window.location='register.html'"></a></td>
</tr>
<tr>
<td colspan="5"><img src="login/login_08.jpg" alt="" width="795"
height="141" border="0" usemap="#Map"></td>
</tr>
<tr>
<td><img src="login/&#x5206;&#x9694;&#x7b26;.gif" width="269"
height="1" alt=""></td>
<td><img src="login/&#x5206;&#x9694;&#x7b26;.gif" width="66"
height="1" alt=""></td>
<td><img src="login/&#x5206;&#x9694;&#x7b26;.gif" width="69"
height="1" alt=""></td>
<td><img src="login/&#x5206;&#x9694;&#x7b26;.gif" width="129"
height="1" alt=""></td>
<td><img src="login/&#x5206;&#x9694;&#x7b26;.gif" width="262"
height="1" alt=""></td>
</tr>
<tr>
<td colspan="5" align="center">
<a href="download/Browser.zip">浏览器兼容问题说明</a>
</td>
</tr>
</table>
<!-- End Save for Web Slices -->

<map name="Map"><area shape="rect" coords="484,16,558,34" href="#" onclick="test()" target="_self">
</map></body>
<script type="text/javascript">

function IMG1_onclick2() {
var user = document.getElementById("username");
var pwd = document.getElementById("userpassword");
var randcode = document.getElementById("randcode");
var url = "LoginAction?no=" + escape(user.value) + "&pwd="
+ escape(pwd.value) + "&randcode=" + escape(randcode.value);
if (user.value == "") {
alert("用户名不能为空");

} else if (pwd.value == "") {
alert("密码不能为空");

}
else if (randcode.value == "") {
alert("验证码不能为空");

} else if (user.value.length > 20 || user.value.length < 2) {
alert("用户名小于6位或大于20位");

} else if (pwd.value.length > 20 || pwd.value.length < 2) {
alert("密码小于6位或大于20位");

} else if (!isNum(randcode.value)) {
alert("验证码只能由数字组成!");
randcode.value = "";
} else if (CheckCode(user.value) && CheckCode(pwd.value)
&& CheckCode(randcode.value)) {
alert("有特殊字符请重新填写!");
user.value = "";
pwd.value = "";
randcode.value = "";
}else {
window.location.href = url;
}
}
function CheckCode(s) //有特殊字符为true 
{
var containSpecial = RegExp(/[(\ )(\~)(\!)(\#)(\$)(\%)(\^)(\&)(\*)(\()(\))(\-)(\_)(\+)(\=)(\[)(\])(\{)(\})(\|)(\\)(\;)(\:)(\')(\")(\,)(\.)(\/)(\<)(\>)(\?)(\)]+/);
return (containSpecial.test(s));
}
function isNum(str){
for (ilen = 0; ilen < str.length; ilen++) {
if (str.charAt(ilen) < '0' || str.charAt(ilen) > '9') {
return false;
}
}
return true;
}
</script>
</html>

登录action

package action;

import java.util.List;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import service.UserServiceImpl;

import javax.mail.Session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import entity.Info;
import entity.Qx;

@SuppressWarnings("serial")
public class LoginAction extends ActionSupport implements ModelDriven<Info> {
//模型驱动使用的对象
private String result;
private String code;
public String getResult()
{
return result;
}

public void setResult(String result)
{
this.result = result;
}
private Info user=new Info();
public Info getModel(){
return user;


}
// 注入UserService
private UserServiceImpl userService ;
/**
* @param userService the userService to set 00
*/
@Resource
public void setUserServiceImpl(UserServiceImpl userService) {
this.userService = userService;
System.out.println("****");
}

/**
* 登陆
*/
public String login(){
List<Info> all = userService.findAll();
System.out.println("LLL");
if (!all.isEmpty()) {
ServletActionContext.getRequest().getSession().setAttribute("listA", all);
}
Info existUser=userService.login(user);
if(existUser==null){
//登陆失败
HttpServletRequest request = ServletActionContext.getRequest(); 
request.setAttribute("tipMessage","登陆失败:用户名或密码错误用户未激活!");
return LOGIN;
}else {
//登陆成功
//将用户的信息存入session中
System.out.println(existUser.getShenfen());
Qx qx=userService.findBySF(existUser.getShenfen());
ServletActionContext.getRequest().getSession().setAttribute("existUser", existUser);

ServletActionContext.getRequest().getSession().setAttribute("qx", qx);
//页面跳转
return "loginSuccess";
}

}
public String checkUserName() { 
String warnMsg = ""; 
Info a = userService.getByNo(this.user.getNo()); 
if (a == null) 
warnMsg = "该用户可用"; 
else 
warnMsg = "该用户已经存在"; 

result = warnMsg;//向jsp页面传递一个result值 

return SUCCESS; 

public String add()
{
System.out.println(user.getNo());
try
{
userService.add(user);
return "success";
}
catch (Exception e)
{
return "input";
}

}
public String passChange()
{
Info a = userService.getByNo(this.user.getNo());
try
{
a.setPwd(user.getPwd());
userService.saveOrUpdate(a);
HttpServletRequest request = ServletActionContext.getRequest(); 
request.setAttribute("tipMessage","修改成功!");
return "success";
}
catch (Exception e)
{
HttpServletRequest request = ServletActionContext.getRequest(); 
request.setAttribute("tipMessage","修改失败!");
return "input";
}
}

public String getCode()
{
return code;
}

public void setCode(String code)
{
this.code = code;
}

 

}

posted @ 2017-05-04 16:17  q白月倚寒楼  阅读(1319)  评论(0编辑  收藏  举报