var xxx = <%=variable%>;
此時瀏覽器直器當機,看來是語法的錯誤,可是當時居然找不到,靜下心來後,發現原來要這樣子用
var xxx = '<%=variable%>'; 或是 var xxx = "<%=variable%>";
因為javascript原本就可以用單或雙引號,在此做個筆記,以免忘記
var xxx = <%=variable%>;
var xxx = '<%=variable%>'; 或是 var xxx = "<%=variable%>";
public static void main(String[] args) {
new Test().<String>xxx("");
new Test().xxx("");
}
private <T> void xxx(T t) {}
private <T extends Xxx, U extends String, V extends Animal &Ooo & Oooo> void xxx(T t, U u, V v) {}
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
new Test().<Integer>xxx(list);
new Test().xxx(list);
}
private <T> void xxx(List<T> t) {
for(T tt:t) {
System.out.println(tt);
}
}
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("Samsung", new Double(27.8));
dataset.setValue("Others", new Double(55.3));
dataset.setValue("Nokia", new Double(16.8));
dataset.setValue("Apple", new Double(17.1));
JFreeChart jfc = ChartFactory.createPieChart("Phone Person", dataset);
try {
ChartUtilities.saveChartAsJPEG(new File("D:/test.jpg"), jfc, 800, 600);
System.out.println("成功!");
} catch (IOException e) {
e.printStackTrace();
System.err.println("失敗!");
}
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("象棋", 12);
dataset.setValue("跳棋", 25);
dataset.setValue("五子棋", 30);
dataset.setValue("孔明棋", 5);
// 中文標題
JFreeChart jfc = ChartFactory.createPieChart("棋類使用率圖", dataset);
jfc.getTitle().setFont(new Font("標楷體", Font.BOLD, 28));
// 圖裡的中文
PiePlot plot = (PiePlot) jfc.getPlot();
plot.setLabelFont(new Font("微軟正黑體", Font.PLAIN, 16));
// 圖底的中文
jfc.getLegend().setItemFont(new Font("新細明體", Font.ITALIC, 20));
try {
ChartUtilities.saveChartAsJPEG(new File("D:/test.jpg"), jfc, 800, 600);
System.out.println("成功!");
} catch (IOException e) {
e.printStackTrace();
System.err.println("失敗!");
}
<constant name="struts.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.devMode" value="true" /> <package name="basicstruts2" extends="struts-default" namespace="/"> <result-types> <result-type name="chart" class="org.apache.struts2.dispatcher.ChartResult"> <param name="height">200</param> <param name="width">200</param> </result-type> </result-types> </package>
@ParentPackage("basicstruts2")
@Namespace("/struts2")
@Action("picture")
@Results({ @Result(name = "success", type = "chart") })
public class JFreeChartAction extends ActionSupport {
private JFreeChart chart;
public JFreeChart getChart() {
return chart;
}
public String productPic() {
DefaultPieDataset dataset = new DefaultPieDataset();
dataset.setValue("象棋", 12);
dataset.setValue("跳棋", 25);
dataset.setValue("五子棋", 30);
dataset.setValue("孔明棋", 5);
// 中文標題
chart = ChartFactory.createPieChart("棋類使用率圖", dataset);
chart.getTitle().setFont(new Font("標楷體", Font.BOLD, 28));
// 圖裡的中文
PiePlot plot = (PiePlot) chart.getPlot();
plot.setLabelFont(new Font("微軟正黑體", Font.PLAIN, 16));
// 圖底的中文
chart.getLegend().setItemFont(new Font("新細明體", Font.ITALIC, 20));
try {
ChartUtilities.saveChartAsJPEG(new File("D:/test.jpg"), chart, 200,
200);
System.out.println("成功!");
} catch (IOException e) {
e.printStackTrace();
System.err.println("失敗!");
}
return SUCCESS;
}
}
Random random = new Random();
for (int i = 0; i <= 100; i++) {
dataSeries.add(i, random.nextInt());
}
@Namespaces(value = {
@Namespace("/"),
@Namespace("/struts2")
})
@Actions(value = {
@Action(value = "crud1"),
@Action(value = "crud2")
})
@Results(value = {
@Result(name = "success", location = "/struts2/success.jsp"),
@Result(name = "input", location = "/struts2/fail.jsp")
})
public class CRUDAction extends ActionSupport {
@Action(value = "crudI")
public String insert() {
System.out.println("增");
return null;
}
@Action(value = "crudD")
public void delete() {
System.out.println("刪");
}
@Action(value = "crudU")
public void update() {
System.out.println("改");
}
@Action(value = "crudQ")
public List<String> query() {
System.out.println("查");
return null;
}
}
@Action(
value = "crudI",
exceptionMappings =
@ExceptionMapping(
exception = "java.lang.NullPointerException",
result = "success",
params = {
"key", "value"
}
))
public String insert() {
System.out.println("增");
return null;
}
<html lang="en">
<head>
<meta charset="utf-8">
<title>get demo</title>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
var aaa = $('[name="aaa"]');
alert(aaa.get(0).value);
alert(aaa[0].value);
alert(aaa.eq(0)[0].value);
aaa.each(function(i){
alert($(aaa.get(i)).val());
alert($(aaa[i]).val());
alert($(aaa.eq(i)[0]).val());
});
$('[name="aaa"]').each(function(){
alert($(this).val());
alert(this.value);
});
});
</script>
</head>
<body>
<input type="text" value="1" name="aaa" />
<input type="text" value="2" name="aaa" />
<input type="text" value="3" name="aaa" />
</body>
</html>
<form action="upload!upload.action" method="post" enctype="multipart/form-data"> <input type="file" name="uploadFile" /><br /> <input type="submit" /> </form>
<constant name="struts.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.custom.i18n.resources" value="Message" /> <constant name="struts.devMode" value="true" /> <package name="basicstruts2" extends="struts-default" namespace="/struts2"> <action name="upload" class="action.UploadAction"></action> </package>
public class UploadAction extends ActionSupport {
private File uploadFile;
//setter即可
public String upload() {
System.out.println("uploadFile=" + uploadFile);
return null;
}
}
public class UploadAction extends ActionSupport {
private File uploadFile;
private String uploadFileContentType;
private String uploadFileFileName;
//三個屬性都給setter即可
public String upload() {
System.out.println("uploadFile=" + uploadFile);
System.out.println("uploadFileContentType=" + uploadFileContentType);
System.out.println("uploadFileFileName=" + uploadFileFileName);
return null;
}
}
<%@ page isELIgnored="false"%>
${uploadMsg}
<form action="upload!upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" /><br />
<input type="submit" />
</form>
<constant name="struts.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.custom.i18n.resources" value="Message" /> <constant name="struts.devMode" value="true" /> <constant name="struts.multipart.saveDir" value="D:\testStruts2" /> <constant name="struts.multipart.maxSize" value="2097152" /> <package name="basicstruts2" extends="struts-default" namespace="/struts2"> <action name="upload" class="action.UploadAction"> <result name="success">/struts2/upload.jsp</result> </action> </package>struts2-core-2.x.x.jar\org.apache.strtus2\default.properties可以找到constant的所有資訊
private File uploadFile;
private String uploadFileContentType;
private String uploadFileFileName;
//三個屬性都給setter即可
public String upload() {
HttpServletRequest request = ServletActionContext.getRequest();
//可以到「tomcat目錄\conf\web.xml」可看到很多xxx/xxx
List<String> list = Arrays.asList(new String[] { "image/jpeg",
"image/bmp", "image/tiff" });
if (list.contains(this.uploadFileContentType)) {
ServletContext context = ServletActionContext.getServletContext();
StringBuffer path = new StringBuffer();
// 取個資料夾名稱放上傳的檔案
path.append(context.getRealPath("/uploadPlace"));
// 用唯一值命名主檔名
path.append(File.separator + UUID.randomUUID() + ".");
// 取原本的副檔名
path.append(this.uploadFileFileName
.substring(this.uploadFileFileName.lastIndexOf(".") + 1));
FileControl.saveFile(this.uploadFile, path.toString());
request.setAttribute("uploadMsg", "上傳成功!");
} else {
request.setAttribute("uploadMsg", "上傳非圖片格式!");
}
return SUCCESS;
}
public static boolean saveFile(File file, String path) {
File outFile = new File(path);
if (!outFile.getParentFile().exists()) {
outFile.getParentFile().mkdirs();
}
InputStream input = null;
OutputStream output = null;
try {
input = new FileInputStream(file);
output = new FileOutputStream(outFile);
byte[] data = new byte[1024];
int temp = 0;
while ((temp = input.read(data)) != -1) {
output.write(data, 0, temp);
}
input.close();
output.close();
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean deleteFile(String path) {
File file = new File(path);
if (file.exists()) {
file.delete();
return true;
}
return false;
}
這個class就隨個人發揮了
${fieldErrors},<br />
${fieldErrors['uploadFile']},<br />
${fieldErrors['uploadFile'][0]}<br />
<form action="upload!upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" /><br />
<input type="submit" />
</form>
<constant name="struts.enable.DynamicMethodInvocation" value="true" /> <constant name="struts.custom.i18n.resources" value="Message" /> <constant name="struts.devMode" value="false" /> <constant name="struts.multipart.saveDir" value="D:/testStruts2" /> <package name="basicstruts2" extends="struts-default" namespace="/struts2"> <action name="upload" class="action.UploadAction"> <interceptor-ref name="fileUpload"> <param name="allowedTypes"> image/jpeg,image/bmp,image/tiff,image/png,image/gif </param> <param name="maximumSize">1048576</param> </interceptor-ref> <interceptor-ref name="basicStack"/> <result name="success">/struts2/upload.jsp</result> </action> </package>
private File uploadFile;
private String uploadFileContentType;
private String uploadFileFileName;
//都給setter即可
public String upload() {
ServletContext context = ServletActionContext.getServletContext();
StringBuffer path = new StringBuffer();
path.append(context.getRealPath("/uploadPlace"));
path.append(File.separator + this.uploadFileFileName);
System.out.println("path=" + path);
FileControl.saveFile(this.uploadFile, path.toString());
return SUCCESS;
}
struts.messages.error.uploading=aaa struts.messages.error.file.too.large=bbb struts.messages.error.content.type.not.allowed=ccc struts.messages.error.file.extension.not.allowed=ddd
<form action="upload!upload.action" method="post" enctype="multipart/form-data">
<input type="file" name="uploadFile" />${fieldErrors['uploadFile'][0]}<br />
<input type="file" name="uploadFile" />${fieldErrors['uploadFile'][1]}<br />
<input type="file" name="uploadFile" />${fieldErrors['uploadFile'][2]}<br />
<input type="submit" />
</form>
private File[] uploadFile;
private String[] uploadFileContentType;
private String[] uploadFileFileName;
//都給setter即可
public String upload() {
ServletContext context = ServletActionContext.getServletContext();
for (int i = 0; i < uploadFile.length; i++) {
StringBuffer path = new StringBuffer();
path.append(context.getRealPath("/uploadPlace"));
path.append(File.separator + this.uploadFileFileName[i]);
System.out.println("path=" + path);
FileControl.saveFile(this.uploadFile[i], path.toString());
}
return SUCCESS;
}
public class HelloInterceptor extends ActionSupport{
public void Hello(){
System.out.println("Hello Interceptor!");
}
}
和一般action一樣
<action name="hello" class="action.HelloInterceptor"> <interceptor-ref name="timer" /> </action>因為package有extends="struts-default",這個檔案在struts2-core-2.x.x.jar裡, 所以name可以是timer,還有很多,可以參考這裡
public class TestInterceptor extends AbstractInterceptor {
@Override
public String intercept(ActionInvocation invocation) throws Exception {
System.out.println("攔截成功!");
return invocation.invoke();
}
}
繼承一個叫AbstractInterceptor的抽象類別,並覆寫方法,invocation.invoke()表示繼續執行
<interceptors> <interceptor name="testICR" class="interceptor.TestInterceptor" /> </interceptors> <action name="hello" class="action.HelloInterceptor"> <interceptor-ref name="timer" /> <interceptor-ref name="testICR" /> </action>可以有很多攔截器,這個例子有兩個,要注意interceptors要寫在action上面,錯誤會有提示
<interceptors> <!-- interceptor可以很多 --> <interceptor name="testICR" class="interceptor.TestInterceptor" /> <interceptor-stack name="xxx"> <interceptor-ref name="timer" /> <interceptor-ref name="testICR" /> </interceptor-stack> </interceptors> <action name="hello" class="action.HelloInterceptor"> <interceptor-ref name="xxx" /> </action>把interceptor-ref搬上去後,用interceptor-stack包起來,然後取個名字,下面就使用新的名字即可
<interceptors>
<interceptor name="testICR" class="interceptor.TestInterceptor" />
<interceptor-stack name="xxx">
<interceptor-ref name="timer" />
<interceptor-ref name="testICR" />
</interceptor-stack>
<default-interceptor-ref name="xxx" />
</interceptors>
<action name="hello1" class="action.HelloInterceptor1" />
<action name="hello2" class="action.HelloInterceptor2" />
<action name="hello3" class="action.HelloInterceptor3" />
default-interceptor-ref設定完,所有的actin在執行之前都會攔截<interceptor-ref name="defaultStack" />不加時,會執行setContainer()-->execute()
<form action="login.action" method="post"> <input type="text" name="user.userName" /><br /> <input type="password" name="user.userPassword" /><br /> <input type="reset" /> <input type="submit" /> </form>
<interceptors> <interceptor name="login" class="interceptor.LoginInterceptor" /> <interceptor-stack name="stack"> <interceptor-ref name="login" /> </interceptor-stack> </interceptors> <action name="login" class="login.LoginAction" method="execute"> <interceptor-ref name="stack" /> <result name="login">/struts2/login.jsp</result> <!-- 方法一 --> <result name="success">/struts2/success.jsp</result> <!-- 方法二,只是測試redirectAction --> <result name="success" type="redirectAction">xxx.action</result> </action> <!-- 此action方法二才需要 --> <action name="xxx" class="login.LoginAction" method="success"> <result name="success">/struts2/success.jsp</result> </action>
HttpServletRequest req = ServletActionContext.getRequest();
User user = new User();
user.setUserName(req.getParameter("user.userName"));
user.setUserPassword(req.getParameter("user.userPassword"));
// 方法一
Map<String, Object> map = invocation.getInvocationContext()
.getSession();
// 方法二
// Map<String, Object> map = ActionContext.getContext().getSession();
if (user.getUserName().isEmpty() || user.getUserPassword().isEmpty()) {
//方法一
HttpServletResponse res = ServletActionContext.getResponse();
res.sendRedirect("/Struts2Demo/struts2/login.jsp");
return null;
//方法二
// return ActionSupport.LOGIN;
} else {
map.put("user", user);
return invocation.invoke();
}
private User user;
//setter/getter
@Override
public String execute() throws Exception {
return SUCCESS;
}
//此方法為struts.xml的方法二才需要
public String success() {
return SUCCESS;
}
private String userName; private String userPassword; //setter/getter
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ page isELIgnored="false"%>
OGNL:
<ul>
<li>帳號:<s:property value="#session.user.userName"/>
<li>密碼:<s:property value="#session.user.userPassword"/>
</ul>
EL:
<ul>
<li>帳號:${user.userName}
<li>密碼:${user.userPassword}
</ul>
<constant name="struts.custom.i18n.resources" value="Message" /> <interceptors> <interceptor name="login" class="interceptor.LoginInterceptor" /> <interceptor-stack name="stack"> <interceptor-ref name="login" /> <interceptor-ref name="basicStack" /> <interceptor-ref name="token" /> </interceptor-stack> </interceptors> <action name="login" class="login.LoginAction" method="execute"> <interceptor-ref name="stack" /> <result name="login">/struts2/login.jsp</result> <result name="success">/struts2/success.jsp</result> <result name="invalid.token">/struts2/login.jsp</result> </action>注意invalid.token要設定
<form action="login.action" method="post"> <s:token name="ooo" /> <s:actionerror /> <input type="text" name="user.userName" /><br /> <input type="password" name="user.userPassword" /><br /> <input type="reset" /> <input type="submit" /> </form>s:token的name可以隨便打,網頁原始碼可看出會變成兩行hidden
struts.messages.invalid.token=\u8868\u55AE\u91CD\u8986\u63D0\u4EA4\uFF01