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'。

posted on 2011-12-13 10:32  你妹啊。  阅读(1589)  评论(0)    收藏  举报