struts2+spring3.2简单demo
1> jar包。
2>src下的包與類。
3>WebRoot下的文件。
4>這個demo是簡單實現了利用session機制存儲跟拿取用戶輸入的內容,完成驗證。
其中ContextPvd 跟ContextPvdImpl是一個工具類及它的實現。
ContextPvd.java package com.jiesuanoa.common.struts2;import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
public interface ContextPvd {
/**
* 獲得系統絕對路徑 如:F:\webapps\CmsSys
*
* @param path
* 可以傳入空串
* @return
*/
public String getAppRealPath(String path);
/**
* 獲得應用絕對根路徑
*
* @return
*/
public String getAppRoot();
/**
* 獲得系統根路徑 如:/CmsSys
*
* @return
*/
public String getAppCxtPath();
/**
* 獲得應用端口號
*
* @return
*/
public int getServerPort();
/**
* 注銷
*
* @return
*/
public void logout();
/**
* 獲得response
*
* @return
*/
public HttpServletResponse getResponse();
/**
* 從Request的Attribute中獲取值
*
* @param key
* @return
*/
public Object getRequestAttr(String key);
/**
* 給Request的Attribute中賦值
*
* @param key
* @param value
*/
public void setRequestAttr(String key, Object value);
/**
* 從SESSION中獲得值
*
* @param key
* @return
*/
public Object getSessionAttr(String key);
/**
* 給session賦值
*
* @param key
* @param value
*/
public void setSessionAttr(String key, Object value);
/**
* 移除session中的屬性
*
* @param key
*/
public void removeAttribute(String key);
public Object getApplicationAttr(String key);
public void setApplicationAttr(String key, Object value);
/**
* 獲得sessionId
*
* @param isCreate
* 如果session不存在是否創建
* @return
*/
public String getSessionId(boolean isCreate);
/**
* 獲得訪問者IP
*
* @return
*/
public String getRemoteIp();
/**
* 獲得訪問者PORT
*
* @return
*/
public int getRemotePort();
/**
* 獲得訪問者URL
*
* @return
*/
public String getRequestURL();
/**
* 獲得訪問者瀏覽器
*
* @return
*/
public String getRequestBrowser();
/**
* 獲得訪問者操作系統
*
* @return
*/
public String getRequestOs();
/**
* 獲得訪問者的代理全部信息
*
* @return
*/
public String getRequestUserAgent();
/**
* 添加cookie
*
* @param cookie
*/
public void addCookie(Cookie cookie);
/**
* 獲取cookie
*
* @param name
* @return
*/
public Cookie getCookie(String name);
/**
* 是否是post請求
*
* @return
*/
public boolean isMethodPost();
/**
* 直接輸出內容的簡便函數
*
* @param text
* @param contentType
* @return
*/
public String render(String text, String contentType);
public String renderHtmlGBK(String html);
public String renderText(String text);
public String renderXML(String xml);
} ContextPvdImpl.java package com.jiesuanoa.common.struts2;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
public class ContextPvdImpl implements ContextPvd {
public String getAppRealPath(String path) {
return ServletActionContext.getServletContext().getRealPath(path);
}
public String getAppRoot() {
return getAppRealPath("/");
}
public String getAppCxtPath() {
return ServletActionContext.getRequest().getServletPath();
}
public int getServerPort() {
return ServletActionContext.getRequest().getServerPort();
}
public void logout() {
HttpSession session = ServletActionContext.getRequest().getSession(false);
if(session!=null) {
session.invalidate();
}
}
public HttpServletResponse getResponse() {
return ServletActionContext.getResponse();
}
public Object getRequestAttr(String key) {
return ServletActionContext.getRequest().getAttribute(key);
}
public void setRequestAttr(String key, Object value) {
ServletActionContext.getRequest().setAttribute(key, value);
}
public Object getSessionAttr(String key) {
HttpSession session = ServletActionContext.getRequest().getSession(false);
if(session!=null) {
return session.getAttribute(key);
}
return null;
}
public void setSessionAttr(String key, Object value) {
HttpSession session = ServletActionContext.getRequest().getSession();
session.setAttribute(key, value);
}
public void removeAttribute(String key) {
HttpSession session = ServletActionContext.getRequest().getSession();
session.removeAttribute(key);
}
public Object getApplicationAttr(String key) {
return ServletActionContext.getServletContext().getAttribute(key);
}
public void setApplicationAttr(String key, Object value) {
ServletActionContext.getServletContext().setAttribute(key, value);
}
public String getSessionId(boolean isCreate) {
HttpSession session = ServletActionContext.getRequest().getSession(isCreate);
if(session!=null)
return session.getId();
return null;
}
public String getRemoteIp() {
return ServletActionContext.getRequest().getRemoteAddr();
}
public int getRemotePort() {
return ServletActionContext.getRequest().getRemotePort();
}
public String getRequestURL() {
return ServletActionContext.getRequest().getRequestURL().toString();
}
public String getRequestBrowser() {
String userAgent = getRequestUserAgent();
String agents[] = userAgent.split(";");
if(agents.length>1)
return agents[1].trim();
return null;
}
public String getRequestOs() {
String userAgent = getRequestUserAgent();
String [] agents = userAgent.split(";");
if(agents.length>2)
return agents[2].trim();
return null;
}
public String getRequestUserAgent() {
HttpServletRequest req = ServletActionContext.getRequest();
String userAgent = req.getHeader("user-agent");
return userAgent;
}
public void addCookie(Cookie cookie) {
ServletActionContext.getResponse().addCookie(cookie);
}
public Cookie getCookie(String name) {
Cookie [] cookies = ServletActionContext.getRequest().getCookies();
if(cookies!=null) {
for(Cookie c:cookies) {
if(c.getName().equals(name)){
return c;
}
}
}
return null;
}
public boolean isMethodPost() {
String method= ServletActionContext.getRequest().getMethod();
if("post".equalsIgnoreCase(method))
return true;
return false;
}
public String render(String text, String contentType) {
try {
HttpServletResponse response = this.getResponse();
response.setContentType(contentType);
response.getWriter().write(text);
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
public String renderHtmlGBK(String html) {
return render(html, "text/html;charset=GBK");
}
public String renderText(String text) {
return render(text, "text/plain;charset=UTF-8");
}
public String renderXML(String xml) {
return render(xml, "text/xml;charset=UTF-8");
}
}
我們也可以注意到ContextPvdImpl類里并沒有用@Service注解去讓spring掃描,因為這只是一個工具類,在一個項目里并不會出現較多的這種工具類,所以我們會有一個coreContext.xml文件來配置,然后在web.xml的<context-param>里的<param-value>里面添加classpath:/coreContext.xml
applicationContext.xml <?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:jee="http://www.springframework.org/schema/jee" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
default-lazy-init="true">
<!-- 掃描注解類 -->
<context:component-scan base-package="com.jiesuanoa">
</context:component-scan>
</beans> coreContext.xml <?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:jee="http://www.springframework.org/schema/jee" 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-2.5.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
>
<!--系統上下文信息PROVIDER-->
<bean id="contextPvd" class="com.jiesuanoa.common.struts2.ContextPvdImpl" autowire="byName"/>
</beans> 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">
<context-param>
<param-name>contextConfigLocation</param-name>
<!---->
<param-value>
classpath:/applicationContext.xml
classpath:/coreContext.xml
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- struts2 核心過濾器-->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
</web-app>
5>建立User類,并根據分層思想建立UserMng及其實現類UserMngImpl。
User package com.jiesuanoa.core.entity;import java.io.Serializable;
public class User implements Serializable {
public static String SessionKey="sessionUser";
private long id;
private String username;
private String password;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
} UserMng package com.jiesuanoa.core.manager;
import com.jiesuanoa.core.entity.User;
public interface UserMng {
public User validateUser(User user);
} UserMngImpl package com.jiesuanoa.core.manager.impl;
import org.springframework.stereotype.Service;
import com.jiesuanoa.core.entity.User;
import com.jiesuanoa.core.manager.UserMng;
@Service
public class UserMngImpl implements UserMng {
public User validateUser(User user) {
if(!user.getUsername().equals("")&&!user.getPassword().equals("")) {
return user;
}
return null;
}
}
注意User類里有一個SessionKey的屬性,這就是我們以后從頁面上取得的內容所存儲的對象key。另外是不能忘了UserMngImpl中的spring注解@Service。
6>BaseAction 實現Action接口 ,LoginAct繼承與BaseAction?
BaseAction package com.jiesuanoa.front;import com.opensymphony.xwork2.Action;
public class BaseAction implements Action {
public String execute() throws Exception {
return SUCCESS;
}
} LoginAct package com.jiesuanoa.front.web;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import com.jiesuanoa.common.struts2.ContextPvd;
import com.jiesuanoa.core.entity.User;
import com.jiesuanoa.core.manager.UserMng;
import com.jiesuanoa.front.BaseAction;
@Scope("prototype")
@Controller("core.aclAct")
public class LoginAct extends BaseAction {
@Autowired
private UserMng userMng;
@Autowired
private ContextPvd contextPvd;
private User user;
private String username;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String loginInput() {
return "loginInput";
}
public String login() {
if(userMng.validateUser(user)==null) {
return this.loginInput();
}
contextPvd.setSessionAttr(User.SessionKey, user);
return SUCCESS;
}
public String index() {
return SUCCESS;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
可以看出業務邏輯是如果取回的User對象為空就返回原界面重新輸入,如果不為空則跳轉。
7>頁面之間跳轉的配置
struts.xml <?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>
<!--基本配置-->
<include file="struts-default.xml" />
<!--入口登錄相關-->
<include file="com/jiesuanoa/front/web/struts-login.xml" />
</struts> struts-login.xml <?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>
<!--登錄-->
<package name="jiesuan.login" namespace="/login" extends="core-default">
<action name="loginInput" method="loginInput" class="core.aclAct"/>
<action name="login" method="login" class="core.aclAct">
<result type="redirectAction">
<param name="actionName">com_index</param>
<param name="namespace">/manager</param>
</result>
</action>
</package>
<!--后臺首頁-->
<package name="jiesuan.console" namespace="/manager" extends="core-default">
<action name="com_*" method="{1}" class="core.aclAct">
<result>/WEB-INF/core/index.html</result>
</action>
</package>
</struts> struts-default.xml <?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>
<!-- url后綴定義 -->
<constant name="struts.action.extension" value="do,action"/>
<package name="core-default" extends="struts-default">
<result-types>
<result-type name="freemarker" class="org.apache.struts2.views.freemarker.FreemarkerResult" default="true"/>
</result-types>
<!--全局跳轉地址-->
<global-results>
<result name="loginInput">/WEB-INF/login/login.html</result>
</global-results>
</package>
</struts>
我們訪問的地址是http://localhost:8080/jiesuanoa/login/loginInput.do? 則會調用struts-default.xml中的屈居地址跳轉到/WEB-INF/login/login.html頁面。然后此頁面點擊按鈕之后會調用/jiesuanoa/login/login.do 則根據
<result type="redirectAction"><param name="actionName">com_index1</param>
<param name="namespace">/manager</param>
</result>
得出調用namespace="/manager" action名字為com_index1的方法:
<package name="jiesuan.console" namespace="/manager" extends="core-default"><action name="com_*" method="{1}" class="core.aclAct">
<result>/WEB-INF/core/index.html</result>
</action>
</package>
即:LoginAct類中的index1方法,然后會返回success字符串,最后跳到/WEB-INF/core/index.html頁面。
8>
login.xml <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>
<head>
<title>MyHtml.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
hello world!! <br>
<form action="/jiesuanoa/login/login.do" method="post">
<input type="text" name="user.username"/></br>
<input type="password" name="user.password"/></br>
<button type="submit">登陸</button>
</form>
</body>
</html> index.html <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>登陸成功</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
</head>
<body>
${sessionUser.username}歡迎您!
</body>
</html>
需要注意的是(${sessionUser.username}歡迎您!)這句話的取值方式,并不是從User對象里取出的,而是根據session的'key'而渠道的'value'。
轉載于:https://www.cnblogs.com/hubingxu/archive/2011/12/13/2285691.html
總結
以上是生活随笔為你收集整理的struts2+spring3.2简单demo的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 对SqlCommandBuilder类理
- 下一篇: android onclick事件和on