一.需求
1.MVC模式
Model 模型
View 视图
Control 控制器
2.Control 控制器
Servlet起到控制器作用!
----> 获取请求数据封装 【BeanUtils可以优化,(调用方法?)】
----> 调用Service处理业务逻辑
----> 跳转(转发/重定向)【跳转代码写死】
3.传统mvc开发总结:
1. 跳转代码写死,不灵活
2. 每次都去写servlet,web.xml中配置servlet!
(配置目的: 请求, Servlet处理类)
4.需求:
登陆、注册
登陆成功---首页
注册成功
---登陆
---首页
二、基于MVC模式封装一个自己的Structs案例
1.逻辑图
2.代码实现
1).核心控制器代码
package com.chinano1edu.framework;
import java.io.IOException;
import java.lang.reflect.Method;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.itcast.framework.bean.ActionMapping;
import cn.itcast.framework.bean.ActionMappingManager;
import cn.itcast.framework.bean.Result;
/*
* 核心控制器,此项目只有这一个servlet
* 1. 拦截所有的*.action为后缀的请求
* 2. 请求:http://localhost:8080/mystruts/login.action
* http://localhost:8080/mystruts/register.action
*/
public class ActionServlet extends HttpServlet{
private ActionMappingManager actionMappingManager;
// 只执行一次(希望启动时候执行)
@Override
public void init() throws ServletException {
System.out.println("ActionServlet.init()");
actionMappingManager = new ActionMappingManager();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String uri = request.getRequestURI();
String actionName=uri.substring(uri.lastIndexOf("/")+1, uri.indexOf(".action"));
// 2. 根据路径名称,读取配置文件,得到类的全名
ActionMapping actionMapping = actionMappingManager.getActionMapping(actionName);
String className = actionMapping.getClassName();
// 当前请求的处理方法
String method = actionMapping.getMethod();
// 3. 反射: 创建对象,调用方法; 获取方法返回的标记
Class<?> clazz = Class.forName(className);
Object obj = clazz.newInstance(); //LoginAction loginAction = new LoginAction();
Method m = clazz.getDeclaredMethod(method, HttpServletRequest.class,HttpServletResponse.class );
// 调用方法返回的标记
String returnFlag = (String) m.invoke(obj, request, response);
// 4. 拿到标记,读取配置文件得到标记对应的页面 、 跳转类型
Result result = actionMapping.getResults().get(returnFlag);
// 类型
String type = result.getType();
// 页面
String page = result.getPage();
// 跳转
if ("redirect".equals(type)) {
response.sendRedirect(request.getContextPath() + page);
} else {
request.getRequestDispatcher(page).forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
2.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<mystruts>
<package>
<!-- 配置请求路径,与处理action类的关系 -->
<!--
1. 请求路径与处理Action的关系
/login = LoginAction login
success = /index.jsp 登陆成功(重定向)
loginFaild = /login.jsp 登陆失败-->
<action name="login" class="com.chinano1edu.com.framework.action.LoginAction" method="login">
<result name="loginSuccess" type="redirect">/index.jsp</result>
<result name="loginFaild">/login.jsp</result>
</action>
<action name="register" class="com.chinano1edu.com.framework.action.RegisterAction" method="register">
<result name="registerSuccess">/login</result>
</action>
</package>
</mystruts>
3).配置文件内容读取代码
package com.chinano1edu.com.framework.bean;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
* 加载配置文件, 封装所有的真个mystruts.xml
*/
public class ActionMappingManager {
// 保存action的集合
private Map<String,ActionMapping> allActions ;
public ActionMappingManager(){
allActions = new HashMap<String,ActionMapping>();
// 初始化
this.init();
}
/**
* 根据请求路径名称,返回Action的映射对象
* @param actionName 当前请求路径
* @return 返回配置文件中代表action节点的AcitonMapping对象
*/
public ActionMapping getActionMapping(String actionName) {
if (actionName == null) {
throw new RuntimeException("传入参数有误,请查看struts.xml配置的路径。");
}
ActionMapping actionMapping = allActions.get(actionName);
if (actionMapping == null) {
throw new RuntimeException("路径在struts.xml中找不到,请检查");
}
return actionMapping;
}
// 初始化allActions集合
private void init() {
try {
// 1. 得到解析器
SAXReader reader = new SAXReader();
// 得到src/mystruts.xml 文件流
InputStream inStream = this.getClass().getResourceAsStream("/mystruts.xml");
// 2. 加载文件
Document doc = reader.read(inStream);
// 3. 获取根
Element root = doc.getRootElement();
// 4. 得到package节点
Element ele_package = root.element("package");
// 5. 得到package节点下, 所有的action子节点
List<Element> listAction = ele_package.elements("action");
// 6.遍历 ,封装
for (Element ele_action : listAction) {
// 6.1 封装一个ActionMapping对象
ActionMapping actionMapping = new ActionMapping();
actionMapping.setName(ele_action.attributeValue("name"));
actionMapping.setClassName(ele_action.attributeValue("class"));
actionMapping.setMethod(ele_action.attributeValue("method"));
// 6.2 封装当前aciton节点下所有的结果视图
Map<String,Result> results = new HashMap<String, Result>();
// 得到当前action节点下所有的result子节点
Iterator<Element> it = ele_action.elementIterator("result");
while (it.hasNext()) {
// 当前迭代的每一个元素都是 <result...>
Element ele_result = it.next();
// 封装对象
Result res = new Result();
res.setName(ele_result.attributeValue("name"));
res.setType(ele_result.attributeValue("type"));
res.setPage(ele_result.getTextTrim());
// 添加到集合
results.put(res.getName(), res);
}
// 设置到actionMapping中
actionMapping.setResults(results);
// 6.x actionMapping添加到map集合
allActions.put(actionMapping.getName(), actionMapping);
}
} catch (Exception e) {
throw new RuntimeException("启动时候初始化错误",e);
}
}
}
package com.chinano1edu.com.framework.bean;
import java.util.Map;
/**
* 封装action节点
*/
public class ActionMapping {
// 请求路径名称
private String name;
// 处理aciton类的全名
private String className;
// 处理方法
private String method;
// 结果视图集合
private Map<String,Result> results;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getMethod() {
return method;
}
public void setMethod(String method) {
this.method = method;
}
public Map<String, Result> getResults() {
return results;
}
public void setResults(Map<String, Result> results) {
this.results = results;
}
}
package com.chinano1edu.com.framework.bean;
/**
* 封装结果视图
*/
public class Result {
// 跳转的结果标记
private String name;
// 跳转类型,默认为转发; "redirect"为重定向
private String type;
// 跳转的页面
private String page;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
}
4).Action代码
package com.chinano1edu.framework.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.chinano1edu.entity.User;
import com.chinano1edu.service.UserService;
/**
* Action表示动作类 1. 一个servlet对应一个action 2. action中负责处理具体的请求
*/
public class LoginAction {
public Object execute(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
return null;
}
/**
* 处理登陆请求
*/
public Object login(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Object uri = null;
// 1. 获取请求数据,封装
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
User user = new User();
user.setName(name);
user.setPwd(pwd);
// 2. 调用Service
UserService userService = new UserService();
User userInfo = userService.login(user);
// 3. 跳转
if (userInfo == null) {
// 登陆失败
uri = "loginFaild"; // loginFaild = /login.jsp
} else {
// 登陆成功
request.getSession().setAttribute("userInfo", userInfo);
// 首页
uri = "loginSuccess";
}
return uri;
}
}
package com.chinano1edu.framework.action;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.chinano1edu.entity.User;
import com.chinano1edu.service.UserService;
public class RegisterAction {
public Object register(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Object uri;
// 1. 获取请求数据,封装
String name = request.getParameter("name");
String pwd = request.getParameter("pwd");
User user = new User();
user.setName(name);
user.setPwd(pwd);
// 2. 调用Service
UserService userService = new UserService();
userService.register(user);
// 3. 跳转
return "registerSuccess";
}
}
5).Service层代码
public class UserService {
private UserDao ud = new UserDao();
// 模拟登陆
public User login(User user){
return ud.login(user);
}
// 模拟注册
public void register(User user) {
ud.register(user);
}
}
6).userBean层代码
public class User {
private String name;
private String pwd;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
7).Dao层代码
public class UserDao {
// 模拟登陆
public User login(User user){
if ("tom".equals(user.getName()) && "888".equals(user.getPwd()) ){
return user;
}
return null;
}
public void register(User user) {
System.out.println("注册成功:用户," + user.getName());
}
}
8).web.xml文件代码
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 核心控制器 -->
<servlet>
<servlet-name>ActionServlet</servlet-name>
<servlet-class>com.chinano1edu.framework.ActionServlet</servlet-class>
<!-- 启动时候执行servlet初始化方法 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>ActionServlet</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
9).jsp文件代码
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>index</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>
欢迎你,${sessionScope.userInfo.name }
</body>
</html>
2.login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>login</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 action="${pageContext.request.contextPath }/login.action" name="frmLogin" method="post">
用户名: <input type="text" name="name"> <br/>
密码: <input type="text" name="pwd"> <br/>
<input type="submit" value="登陆"> <br/>
</form>
</body>
</html>
3.register.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>login</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 action="${pageContext.request.contextPath }/register.action" name="frmRegister" method="post">
用户名: <input type="text" name="name"> <br/>
密码: <input type="text" name="pwd"> <br/>
<input type="submit" value="注册"> <br/>
</form>
</body>
</html>