struts2学习

1.jar包


2.struts.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>

<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="true" />


<!-- namespace 用来对访问路径分层 -->
<package name="default" namespace="/" extends="struts-default">
<!-- name 给其他包去继承 -->
<action name="index">
<result>index.jsp</result>
</action>


<action name="testSession" class="com.cl.struts2.action.TestAction">
<result>index.jsp</result>
</action>
<!-- 不写methods 默认访问execute方法 -->
<action name="test" class="com.cl.struts2.action.TestAction" method="add">
<result>index.jsp</result>
</action>
<!-- 通配符   eg:  Test_index 
http://localhost:8080/struts2_01/Test_index
-->
<action name="*_*" class="com.cl.struts2.action.{1}Action" method="{2}">
<result>{1}.jsp</result>
</action>

</package>
<package name="user" namespace="/" extends="default">
<action name="checklogin" class="com.cl.struts2.action.UserAction" method="check">
<result>index.jsp</result>
<result name="login">login.jsp</result>
</action>

</package>
<!-- <include file="example.xml"/> -->


<!-- Add packages here -->


</struts>


3.修改web,xml文件

<!-- 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>
</filter-mapping>



目录结构


 action 需要 extends ActionSupport implements ModelDriven<Book>,涉及页面取值传值问题,参数需要有get/set方法

主要是获取session:

public class TestAction extends ActionSupport implements ModelDriven<Book> {


private static final long serialVersionUID = 1L;
private Book book;

private Map session;
private Map request;
private HttpServletRequest req;

public TestAction() {
session = ActionContext.getContext().getSession();
request = (Map) ActionContext.getContext().get("request");
req = ServletActionContext.getRequest();
req.getSession();
ActionContext.getContext().getApplication();
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}

public Book getModel() {
if(book == null){
book = new Book();
}
return book;
}

@Override
public String execute() throws Exception{
//获取session
System.out.println("execute.....");
session.put("name", "chenling");
request.put("name", "chenling");
req.setAttribute("name1", "chenling");
return super.execute();
}
public String add(){
System.out.println("add.....");
System.out.println(book);
return "success";
}
public String index(){
System.out.println("index.....");
return null;
}
}


验证用户登陆并提示错误信息:

public class UserAction extends ActionSupport implements ModelDriven<User> {
private User user;

public User getUser() {
return user;
}


public void setUser(User user) {
this.user = user;
}
public String check(){
//用户名为空
if(user.getUsername()==null || user.getUsername().equals("")){
//页面提示错误:session
this.addFieldError("username", "name is null");
return "login";
}

if(user.getUsername().equals("admin")&& user.getPassword().equals("1234")){


return SUCCESS;

}
addFieldError("username", "username or password is error");
return "login";
}


public User getModel() {
if(user==null){
user = new User();
}
return user;
}


}


login.jsp

<form action="checklogin">
    
    用户:<input name="username"/>
    <%-- <s:fielderror value="username"></s:fielderror> --%>
    <span style="color:red;"><s:property value="errors.username[0]"/></span><br>
    密码:<input name="password"/><br>
    <input type="submit"value="Submit"/><br>
    </form>


addBook.jap:

<form action="test">
    图书号:<input name="id"/><br>
    图书名:<input name="name"/><br>
    图书价:<input name="price"/><br>
    <input type="submit"value="Submit"/><br>
    </form>


struts2:文件上传

public class UploadAction {


//struts2通过set方法得到数据、要求name 相同
private File pic;
//Struts 提供的得到文件名的方式,  属性名+FileName
private String picFileName;
private  HttpServletRequest request;
public UploadAction() {
request = ServletActionContext.getRequest();
}




public File getPic() {
return pic;
}


public void setPic(File pic) {
this.pic = pic;
}


public String getPicFileName() {
return picFileName;
}


public void setPicFileName(String picFileName) {
this.picFileName = picFileName;
}


public String upload(){
String path = request.getRealPath("/")+"upload";
//F:\ChenLing\Java\MyEclipse\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\struts2_02\
//System.out.println(path);
// String path = ServletActionContext.getServletContext().getRealPath("/upload");
try {
InputStream is = new FileInputStream(pic);
File descFile = new File(path,getPicFileName());
OutputStream os = new FileOutputStream(descFile);
byte[] buf = new byte[1024];
while(is.read(buf) > 0){
os.write(buf);
}
os.close();
is.close();
return "success";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//使用struts2提供的工具上传
// String path = ServletActionContext.getServletContext().getRealPath("/upload");
// if(pic != null){
// File savefile = new File(path,picFileName);
// try {
// FileUtils.copyFile(pic, savefile);
// return "success";
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// }
return "login";
}
}


页面代码:

<%@ taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.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>
  <!--
  action ="upload" 会报错   跟方法名写的一样  不可以
  There is no Action mapped for namespace [/] and action name [upload/] associated with context path [/struts2_02].   -->
  <form action="uploadFile" method="post" enctype="multipart/form-data">
    
    文件:<input type="file" name="pic"/><br>
    <input type="submit"value="Submit"/><br>
    </form>
  </body>
</html>


练习源码:http://download.csdn.net/detail/i_do_can/9372107

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值