action
action是SSH里Struts2的方法。
框架先实例化 Action 对象,在第二次提交时,Action 会重新实例化,每一个 Action 对象都服务一个请求,这和 Servlet 的原理是不一样的——servlet是只在服务器启动时加载一次,所有用户共享。
提交表格内容到action
关于HTML语言中的form表单提交的方式
(1)所有的表单元素如果要进行页面提交需要使用form标签包裹。
(2)关于form标签上的属性作用
action 提交的地址 :
发送当前页面的数据到另外的页面去。
method 请求的方式
get请求 特点:参数会暴露在地址栏上,数据大小有限制,不安全,做一些查询的工作
post请求 特点:与get请求正好相反
提交过程:以< input type=“image”>为例
head里定义basePath:
basePath可以让java项目获取根路径,通过绝对路径引入这些图片文件。然后我们需要在jsp文件的开头写下面的代码。
<head>
<base href="<%=request.getScheme()+"://"+request.getServerName()+":"
+request.getServerPort()+request.getContextPath()+"/page/" %>">
<title><s:text name="login"/></title>
<link rel="stylesheet" type="text/css" href="css/login.css">
<script type="text/javascript" src="js/js.js"></script>
</head>
body里写明提交目的地和提交方法:
< body>
< s:actionerror/>
< s:fielderror key="dataErr"></s:fielderror>
< s:form action="dologin" method="post" validate="true"> //post方式提交到xml里的dologin里处理
< input type=“image”> 使图片按钮具有提交功能:
input本来就是表单form的元素,< input type=“image”>说明:
创建一个图像控件,该控件单击后将导致表单(from)立即被提交。
如果此标签放置在标签内就直接具有提交功能,如果不在标签内,则可以使用< input type=“image” onClick = “formName.submit()”>方式提交。
struts.xml里配置这些方法:
<struts>
<include file="org/dreamtang/struts-aptat_default.xml" />
<!-- 所有与用户相关的Action -->
<package name="user" namespace="/user" extends="aptat_default">
<!-- 登录页面 -->
<action name="login">
<result>/page/login.jsp</result>
</action>
<!-- 处理登录的Action -->
<action name="dologin" class="org.dreamtang.action.UserAction" method="LoginAction">
//将表格的数据传给org.dreamtang.action.UserAction里的LoginAction函数处理
<result name="success" type="redirectAction">welcome</result>
<result name="input" type="chain">login</result>
//若返回success,进入welcome的action里再处理
//若返回input,进入login的action里再处理
</action>
</package>
</struts>
参数:
method:
对应处理函数。
result:
对应处理函数的返回值。
type:
1.dispatcher: 默认值,服务器内部跳转(跳转到jsp等web组件)
2.redirect: 作客户端重定向(重定向到web组件);
3.chain: 作服务器内部跳转(跳转到其他Action);
4.redirectAction: 作客户端重定向(重定向到其他Action)
.java里写对应处理函数:
public User LoginService(User user) throws Exception{
System.out.println(user.getLogin());
check=userDAO.search(user.getLogin());
if(check==null)
throw new Exception("not");//该登录名不存在
if(check.getPassword().equals(user.getPassword())&&check.getIdentify()<4)
return check;//登录成功
throw new Exception("error");//密码错误
}
public String LoginAction() {
try {
user = userService.LoginService(user);
} catch (Exception e) {// 登录失败
e.printStackTrace();
errorMessage = "帐号或密码错误";
return INPUT;
}
// 登录成功,记录用户信息到session
request.getSession().setAttribute("user", user);
File f = new File(basePath + ("file") + "/photo/" + user.getLogin()
+ "/" + user.getLogin() + ".jpg");
if (f.exists()) {
user.setPhoto("../../file/photo/" + user.getLogin() + "/"
+ user.getLogin() + ".jpg");
} else {
user.setPhoto("../images/ico02.gif");
}
return SUCCESS;
}