一 需求
在登录成功的页面,显示登录成功的人名
二 方案
1 实现方法
通过Request对象实现
2 实现代码
2.1
LoginAction
package com.cakin.actions;
//这是一个action(表示小队长,需要继承Action)
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.cakin.forms.UserForm;
public class LoginAction extends Action {
//我们需要重新编写一个方法:execute会被自动调用,有点类似servlet的service方法。
@Override
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
//把form转成对应的UserForm对象
UserForm userForm=(UserForm)form;
//简单验证
if("123".equals(userForm.getPassword())){
//把名字存放到request对象域
request.setAttribute("username", userForm.getUsername());
return mapping.findForward("ok");
}
else{
return mapping.findForward("err");
}
}
}
2.2
wel.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
>
<
base
href
=
"
<%=
basePath
%>
"
>
<
title
>
My JSP 'wel.jsp' starting page
</
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
>
welcome
<%=
request.getAttribute(
"username"
).toString()
%>
<
br
>
<
a
href
=
"/strutslogin/"
>
返回重新登录
</
a
>
</
body
>
</
html
>
三 测试结果