框架學習之自己動手實現Struts框架
阿新 • • 發佈:2019-02-10
前言:
MVC模式回顧:Model(模型) View(檢視) Controller(控制器)
框架無非目的是為了簡化程式碼,快捷開發,萬變不離其宗。Structs就是對其中的Controller層進行優化,在JavaWeb中也就是Servlet。
現在回想下之前不用框架之前的麻煩點:
1. 跳轉程式碼寫死,不靈活;
2. 每次都去寫Servlet,然後web.xml中配置Servlet。(配置目的: 請求, Servlet處理類)於是想到能不能進行優化呢,如果有幾十個甚至上百個Servlet那web.xml是不是會非常臃腫呢?現在先自己動手實現優化,實現第一個自己的MyStruct。
需求:
一個簡單的登入註冊
- 設計User實體類、DAO與Service
ppackage entity;
/**
* 實體類 User
* Created by Administrator on 2017/1/6.
*/
public class User {
private String name;
private String pwd;
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package dao;
import entity.User;
/**
* Created by Administrator on 2017/1/6.
*/
public class UserDao {
//模擬登陸
public User login(User user){
if("admin".equals(user.getName()) &&
"admin" .equals(user.getPwd())){
return user;
}
return null;
}
//模擬註冊
public void regist(User user){
System.out.println("註冊成功,歡迎您 " + user.getName());
}
}
package service;
import dao.UserDao;
import entity.User;
/**
* Created by Administrator on 2017/1/6.
*/
public class UserService {
private UserDao dao = new UserDao();
// 模擬登陸
public User login(User user){
return dao.login(user);
}
// 模擬註冊
public void regist(User user) {
dao.regist(user);
}
}
- 核心,模擬Structs中的設計,自己寫一個ActionServlet,來管理專案中所有的Servlet,首先在src目錄下新建一個mystructs.xml檔案,配置專案中的Servlet。先設計配置檔案:
<?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="framework.action.LoginAction" method="login">
<result name="loginSuccess" type="redirect">/index.jsp</result>
<result name="loginFaild">/login.jsp</result>
</action>
<action name="register" class="framework.action.RegistAction" method="register">
<result name="registerSuccess">/login</result>
</action>
</package>
</mystruts>
然後寫兩個Action類
package framework.action;
import entity.User;
import service.UserService;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Action表示動作類
* 1. 一個servlet對應一個action 2. action中負責處理具體的請求
* Created by Administrator on 2017/1/6.
*/
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 = "loginFailed";
}else {
//登陸成功
request.getSession().setAttribute("userInfo",userInfo);
uri = "loginSuccess";
}
return uri;
}
}
package framework.action;
import entity.User;
import service.UserService;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* RegistAction
* Created by Administrator on 2017/1/6.
*/
public class RegistAction {
public Object regist(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();
userService.regist(user);
//3.跳轉
uri = "registSuccess";
return uri;
}
}
接著寫一個ActionMapping來封裝配置檔案中的action節點
package framework.bean;
import java.util.Map;
/**
* 封裝action節點
* Created by Administrator on 2017/1/6.
*/
public class ActionMapping {
//請求路徑名稱
private String name;
//處理action類的全名
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;
}
}
還有一個封裝結果檢視的Result
package framework.bean;
/**
* 封裝結果檢視
* <result name="success" type="redirect">/index.jsp</result>
* Created by Administrator on 2017/1/6.
*/
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;
}
}
再寫一個ActionMappingManager類:
package framework.bean;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* 載入配置檔案, 封裝所有的整個 mystruts.xml
* Created by Administrator on 2017/1/6.
*/
public class ActionMappingManager {
//儲存action的集合
private Map<String, ActionMapping> allActions;
public ActionMappingManager() {
allActions = new HashMap<String, ActionMapping>();
this.init();
}
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;
}
//初始化allCollection集合
private void init() {
//DOM4J讀取配置檔案
try {
//1.得到解析器
SAXReader reader = new SAXReader();
//得到mystruct.xml檔案流
InputStream in = this.getClass().getResourceAsStream("/mystructs.xml");
//2.載入檔案
Document doc = reader.read(in);
//3,獲取根節點
Element root = doc.getRootElement();
//4.得到packet節點
Element ele_package = root.element("package");
//5.得到根結點下所有的action節點
List<Element> listAction = ele_package.elements("action");
//6.遍歷,封裝
for (Element e : listAction) {
// 6.1 封裝一個ActionMapping物件
ActionMapping actionMapping = new ActionMapping();
actionMapping.setName(e.attributeValue("name"));
actionMapping.setClassName(e.attributeValue("class"));
actionMapping.setMethod(e.attributeValue("method"));
// 6.2 封裝當前aciton節點下所有的結果檢視
Map<String,Result> results = new HashMap<String,Result>();
//得到action節點下的所有result節點
Iterator<Element> it = e.elementIterator("result");
while(it.hasNext()){
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);
//actionMapping新增到map集合
allActions.put(actionMapping.getName(),actionMapping);
}
} catch (Exception e) {
throw new RuntimeException("啟動初始化出錯",e);
}
}
}
然後記得在web.xml中配置ActionServlet
<servlet>
<servlet-name>ActionServlet</servlet-name>
<servlet-class>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>
最後完成三個jsp頁面,login.jsp,regist.jsp,index.jsp
//index.jsp
<body>
歡迎你,${sessionScope.userInfo.name}
</body>
//login.jsp
<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>
//regist.jsp
<body>
<form action="${pageContext.request.contextPath }/regist.action" name="frmRegister" method="post">
使用者名稱: <input type="text" name="name"> <br/>
密碼: <input type="text" name="pwd"> <br/>
<input type="submit" value="註冊"> <br/>
</form>
</body>
第一個自己動手的Structs框架專案完成!