struts2学习笔记(1)
1、struts2中的路径问题
struts2中的路径是根据action的路径而不是jsp路径来确定,所以尽量不用使用相对路径。
解决办法:
(1)使用用绝对路径
(2)使用myeclipse中常用的指定basepath(使用Myeclipse的高级JSP模板就能自动生成)
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <head> <base href="<%=basePath%>"> </head>
2 减少action
(1)Action执行时并不一定执行execute方法,可以用method来指定其他方法(若不指定,则默认是execute方法)。用method指定同一个action中的不同方法,可以减少action(class)的个数,但在struts.xml文件中定义的action个数并没有少。使用通配符匹配可以减少struts.xml文件中定义的action个数。
(2)action中的通配符匹配
在structs.xml中配置:
当在浏览器中输入http://localhost:8080/struts2Demo/Studentadd时, 上述配置中action立的*相当于add,所以method={1}相当于method=“add”,所以会调用StudentAction中的add()方法,然后跳转到Studentadd_success.jsp页面
public class StudentAction extends ActionSupport () { public String add() { return SUCCESS; } public String del() { return SUCCESS; } }
开发中一个重要原则:约定优于配置。 良好的约定可以使配置达到很简单。如下所示:
通配符匹配中,若存在多个匹配,则优先匹配最精确的,而不是按最早匹配原则。