数据转换
- jsp页面传送到后台带的数据默认都是字符串,但是如果要把数据封装到对象中,就要转换为对象对应的属性类型
字符转list
- user类
package com.model;
public class User {
//name属性
private String name;
//age属性
private int age;
//tel属性
private String tel;
//各属性的getter和setter()方法
}
- action
package com.action;
import java.util.List;
import com.model.User;
import com.opensymphony.xwork2.ActionSupport;
public class ListAction extends ActionSupport{
private static final long serialVersionUID = 1L;
//users属性,为List类型
private List<User> users;
//getter方法
public List<User> getUsers() {
return users;
}
//setter方法
public void setUsers(List<User> users) {
this.users = users;
}
//重载execute()方法
public String execute() throws Exception {
for (User user : users) {
System.out.println("Name:"+user.getName()+" Age:"+user.getAge()+" Tel:"+user.getTel());
}
return SUCCESS;
}
}
- struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<!-- default包-->
<package name="default" namespace="/" extends="struts-default">
<!-- list Action返回success.jsp页面 -->
<action name="list" class="com.action.ListAction">
<result>/success.jsp</result>
</action>
</package>
</struts>
- index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<!-- 表单 -->
<s:form action="list">
<!-- 表格 -->
<table >
<tr>
<td></td>
<td>first:</td>
<td>second:</td>
</tr>
<tr>
<td>Name:</td>
<!-- 设置list元素-->
<td><s:textfield name="users[0].name" theme="simple"/></td>
<td><s:textfield name="users[1].name" theme="simple"/></td>
</tr>
<tr>
<td>Age:</td>
<td><s:textfield name="users[0].age" theme="simple"/></td>
<td><s:textfield name="users[1].age" theme="simple"/></td>
</tr>
<tr>
<td>Tel:</td>
<td><s:textfield name="users[0].tel" theme="simple"/></td>
<td><s:textfield name="users[1].tel" theme="simple"/></td>
</tr>
<tr>
<td colspan="3">
<s:submit></s:submit>
</td>
</tr>
</table>
</s:form>
</center>
</body>
</html>
- success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
Name:<s:property value="users[0].name"/>
Age:<s:property value="users[0].age"/>
Tel:<s:property value="users[0].tel"/><br/>
Name:<s:property value="users[1].name"/>
Age:<s:property value="users[1].age"/>
Tel:<s:property value="users[1].tel"/>
</center>
</body>
</html>
字符串转map
- action
package com.action;
import java.util.Map;
import com.model.User;
import com.opensymphony.xwork2.ActionSupport;
public class ListAction extends ActionSupport{
private static final long serialVersionUID = 1L;
//Map类型 users属性
private Map<String, User> users;
//getter方法
public Map<String, User> getUsers() {
return users;
}
//setter方法
public void setUsers(Map<String, User> users) {
this.users = users;
}
//重载execute方法
public String execute() throws Exception {
return SUCCESS;
}
}
- index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<s:form action="list">
<table >
<tr>
<td></td>
<td>first:</td>
<td>second:</td>
</tr>
<tr>
<td>Name:</td>
<td><s:textfield name="users['first'].name" theme="simple"/></td>
<td><s:textfield name="users['second'].name" theme="simple"/></td>
</tr>
<tr>
<td>Age:</td>
<td><s:textfield name="users['first'].age" theme="simple"/></td>
<td><s:textfield name="users['second'].age" theme="simple"/></td>
</tr>
<tr>
<td>Tel:</td>
<td><s:textfield name="users['first'].tel" theme="simple"/></td>
<td><s:textfield name="users['second'].tel" theme="simple"/></td>
</tr>
<tr>
<td colspan="3">
<s:submit></s:submit>
</td>
</tr>
</table>
</s:form>
</center>
</body>
</html>
- success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
Name:<s:property value="users['first'].name"/>
Age:<s:property value="users['first'].age"/>
Tel:<s:property value="users['first'].tel"/><br/>
Name:<s:property value="users['second'].name"/>
Age:<s:property value="users['second'].age"/>
Tel:<s:property value="users['second'].tel"/>
</center>
</body>
</html>
自定义转换器
- action
package com.action;
import com.convertor.Line;
import com.opensymphony.xwork2.ActionSupport;
public class LineAction extends ActionSupport{
private static final long serialVersionUID = 1L;
//生面Line实例
private Line line;
//getter方法
public Line getLine() {
return line;
}
//setter方法
public void setLine(Line line) {
this.line = line;
}
//重载execute方法
public String execute() throws Exception {
// TODO Auto-generated method stub
return SUCCESS;
}
}
- LineAction-conversion.properties
line=com.convertor.LineConvertor
- Line类
package com.convertor;
public class Line {
//线段类的端点坐标(x1,y1,x2,y2)
private int x1;
private int y1;
private int x2;
private int y2;
public Line(){
}
//构造方法
public Line(int x1, int y1, int x2, int y2)
{
this.x1=x1;
this.y1=y1;
this.x2=x2;
this.y2=y2;
}
//属性的getter和setter方法
}
- LineConvertor转换器类
package com.convertor;
import java.util.Map;
import org.apache.struts2.util.StrutsTypeConverter;
public class LineConvertor extends StrutsTypeConverter{
//字符串转向指定类型
public Object convertFromString(Map contenxt, String[] values, Class totype) {
//请求参数为字符串数组
String[] params=(String[])values;
String param=params[0];
//创建Line实例
Line line=new Line();
StringBuilder temp=new StringBuilder();
char ch;
int j=0;
//字符串正确形式为(x1,y1,x2,y2)
for(int index=0;index<param.length();index++)
{
ch=param.charAt(index);
if(ch!=','&&ch!='('&&ch!=')')
{
temp.append(ch);
}else if(ch==','||ch==')')
{
switch (j) {
case 0:
{
line.setX1(Integer.parseInt(temp.toString()));
temp.delete(0,temp.length());
break;
}
case 1:
{
line.setY1(Integer.parseInt(temp.toString()));
temp.delete(0,temp.length());
break;
}
case 2:
{
line.setX2(Integer.parseInt(temp.toString()));
temp.delete(0,temp.length());
break;
}
case 3:
{
line.setY2(Integer.parseInt(temp.toString()));
temp.delete(0,temp.length());
break;
}
default:
break;
}
j++;
}
}
return (Object)line;
}
//将对象转换为字符串
public String convertToString(Map context, Object o) {
//强制转换为Line类型
Line line=(Line)o;
return "("+line.getX1()+","+line.getY1()+","+line.getX2()+","+line.getY2()+")";
}
}
- struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="line" class="com.action.LineAction">
<result>/success.jsp</result>
</action>
</package>
</struts>
- index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<s:form action="line">
<s:textfield name="line" label="Line input,please input (x1,y1,x2,y2)!"/>
<s:submit></s:submit>
</s:form>
</center>
</body>
</html>
- success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<s:property value="line"/>
</center>
</body>
</html>
案例
-
要求:输入x坐标和y坐标按照【x=?,y=?】格式显示
-
web.xml
<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>
- input.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="out" method="post">
<s:textfield name="point" label="X point"/>
<s:textfield name="point" label="Y point"/>
<s:submit></s:submit>
</s:form>
</body>
</html>
- 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.i18n.encoding" value="UTF-8"></constant>
<package name="demo" extends="struts-default" namespace="/">
<action name="out" class="com.test.action.PointAction">
<result name="out">/out.jsp</result>
</action>
</package>
</struts>
- PointAction
package com.test.action;
import com.opensymphony.xwork2.ActionSupport;
import com.test.bean.Point;
public class PointAction extends ActionSupport {
private Point point;
public Point getPoint() {
return point;
}
public void setPoint(Point point) {
this.point = point;
}
@Override
public String execute() throws Exception {
// TODO Auto-generated method stub
return "out";
}
}
- Point.java
package com.test.bean;
public class Point {
private int x;
private int y;
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
@Override
public String toString() {
return "Point [x=" + x + ", y=" + y + "]";
}
}
- PointConverter
package com.test.action;
import java.util.Map;
import org.apache.struts2.util.StrutsTypeConverter;
import com.test.bean.Point;
public class PointConverter extends StrutsTypeConverter{
////字符串转向指定类型
@Override
public Object convertFromString(Map contenxt, String[] values, Class totype) {
//请求参数为字符串数组
String xString=values[0];
String yString=values[1];
Point point=new Point();
point.setX(Integer.parseInt(xString));
point.setY(Integer.parseInt(yString));
System.out.println("s to o"+point);
return point;
}
////将对象转换为字符串
@Override
public String convertToString(Map map, Object object) {
Point point=(Point) object;
System.out.println(point);
return "[x="+point.getX()+",y="+point.getY()+"]";
}
}
- PointAction-conversion.properties
point=com.test.action.PointConverter
- out.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<%@ taglib uri="/struts-tags" prefix="s"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:property value="point"/>
</body>
</html>
数据校验
普通校验
- bean
package com.test.bean;
import java.util.Date;
public class Book {
private String name;
private Double price;
private Date date;
private Integer count;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}
- action
package com.test.action;
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
import com.test.bean.Book;
public class BookAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private Book book;
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public String execute() throws Exception {
return "hello";
}
//login业务方法
public String log() throws Exception{
return "hello";
}
//校验方法
@Override
public void validate() {
// TODO Auto-generated method stub
super.validate();
}
//log方法的校验方法
public void validateLog(){
Date date=new Date();
if(null==book.getName() || book.getName().equals("")) {
addFieldError("name", "name must not null");
}
if(null==book.getPrice() || book.getPrice()<=0){
addFieldError("price", "price must >0");
}
if(null==book.getDate() || book.getDate().getTime()>=date.getTime()) {
addFieldError("date", "date is error");
}
if(null==book.getCount() || book.getCount()<=0) {
addFieldError("count", "count must >0");
}
}
}
- 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.i18n.encoding" value="UTF-8"></constant>
<package name="demo" extends="struts-default" namespace="/">
<action name="addBook" class="com.test.action.BookAction" method="log">
<result name="hello">/hello.jsp</result>
<result name="input">/addBook.jsp</result>
</action>
</package>
</struts>
- web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_9" version="2.4">
<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>
<welcome-file-list>
<welcome-file>addBook.jsp</welcome-file>
</welcome-file-list>
</web-app>
- addBook.jsp
<body>
<!-- 显示所有数据校验错误信息 -->
<s:fielderror/>
<s:form action="addBook.action" validate="true">
<s:textfield name="book.name" label="name"></s:textfield>
<s:textfield name="book.price" label="price"></s:textfield>
<s:textfield name="book.date" label="date"></s:textfield>
<s:textfield name="book.count" label="count"></s:textfield>
<s:submit method="log"></s:submit>
</s:form>
</body>
- hello.jsp
<body>
name:<s:property value="book.name"/><br>
price:<s:property value="book.price"/><br>
date:<s:property value="book.date"/><br>
count:<s:property value="book.count"/><br>
</body>
XWORK案例
- action
package com.action;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
private static final long serialVersionUID = 1L;
//name属性
private String name;
//age属性
private int age;
//tel属性
private String tel;
//name属性getter方法
public String getName() {
return name;
}
//name属性setter方法
public void setName(String name) {
this.name = name;
}
//age属性getter方法
public int getAge() {
return age;
}
//age属性setter方法
public void setAge(int age) {
this.age = age;
}
//tel属性getter方法
public String getTel() {
return tel;
}
//tel属性setter方法
public void setTel(String tel) {
this.tel = tel;
}
//重载execute方法
public String execute() throws Exception {
return "hello";
}
//log方法,Action调用的method方法
public String log()throws Exception{
System.out.println("log");
return "hello";
}
}
- LoginAction-validation.xml
- 字段校验方式:针对字段或者属性,使用这种方式在校验时对任意一个字段都能返回一个明确消息
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<!-- age域 -->
<field name="age">
<!--域类型为int-->
<field-validator type="int">
<param name="min">10</param>
<param name="max">40</param>
<message>the age must be from 10 to 40!</message>
</field-validator>
</field>
<!-- name域 -->
<field name="name">
<!-- 域类型为requiredstring类型 -->
<field-validator type="requiredstring">
<message>the age must be from 10 to 40!</message>
</field-validator>
</field>
</validators>
- struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<action name="login" class="com.action.LoginAction">
<!-- 返回hello.jsp -->
<result name="hello">/hello.jsp</result>
<!-- 校验出现问题,返回validation.jsp -->
<result name="input">/validateLogin.jsp</result>
</action>
</package>
</struts>
- index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<s:form action="login">
<s:textfield name="name" label="Name"></s:textfield>
<s:textfield name="age" label="Age"></s:textfield>
<s:textfield name="tel" label="Telephone"></s:textfield>
<s:submit method="log"></s:submit>
</s:form>
</center>
</body>
</html>
- hello.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
Name:<s:property value="name"/><br/>
Age:<s:property value="age"/><br/>
Telephone:<s:property value="tel"/><br/>
</center>
</body>
</html>
- validateLogin.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
the your input
<s:property value="age"/> that is wrong!<br/>
</center>
</body>
</html>
校验器
- required
- 要求必须非空
<field name="name">
<!--域类型为required-->
<field-validator type="required">
<message>the name must not be null</message>
</field-validator>
</field>
- requiredstring
- 要求必须非空并且长度必须大于0
<field name="name">
<!--域类型为requiredstring-->
<field-validator type="requiredstring">
<message>the name is required</message>
</field-validator>
</field>
- int
- 整数校验,必须在指定范围内,另外,long,short,float,double同理
<field name="age">
<!--域类型为int-->
<field-validator type="int">
<param name="min">10</param>
<param name="max">40</param>
<message>the age must be from 10 to 40!</message>
</field-validator>
</field>
- data
- 要求日期在指定范围内
<field name="birth">
<!--域类型为data-->
<field-validator type="data">
<param name="min">1990-01-01</param>
<param name="max">2018-3-2</param>
<!--错误输出,${min} 和 ${max}是上面的要求日期-->
<message>the data must between ${min} and ${max}</message>
</field-validator>
</field>
- 校验邮件地址是否合法
<field name="mail">
<!--域类型为email-->
<field-validator type="email">
<message>the address must not be avliable</message>
</field-validator>
</field>
- stringlength
- 长度必须在范围内
<field name="user">
<!--域类型为stringlength-->
<field-validator type="stringlength">
<param name="minLength">4</param>
<param name="maxLength">40</param>
<message>the user must be between 4 and 40!</message>
</field-validator>
</field>
案例
- Book.java
package com.test.bean;
import java.util.Date;
public class Book {
private String name;
private Double price;
private Date date;
private Integer count;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
}
- addBook.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'addBook.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>
<!-- 显示所有数据校验错误信息 -->
<s:fielderror/>
<s:form action="addBook.action" validate="true">
<s:textfield name="book.name" label="name"></s:textfield>
<s:textfield name="book.price" label="price"></s:textfield>
<s:textfield name="book.date" label="date"></s:textfield>
<s:textfield name="book.count" label="count"></s:textfield>
<s:submit method="log"></s:submit>
</s:form>
</body>
</html>
- 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.i18n.encoding" value="UTF-8"></constant>
<package name="demo" extends="struts-default" namespace="/">
<action name="addBook" class="com.test.action.BookAction" method="log">
<!--如果全部通过验证,跳转到hello页面显示,如果验证不通过,返回addbook页面显示错误信息 -->
<result name="hello">/hello.jsp</result>
<result name="input">/addBook.jsp</result>
</action>
</package>
</struts>
- BookAction
package com.test.action;
import java.util.Date;
import com.opensymphony.xwork2.ActionSupport;
import com.test.bean.Book;
public class BookAction extends ActionSupport{
/**
*
*/
private static final long serialVersionUID = 1L;
private Book book;
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public String execute() throws Exception {
return "hello";
}
//login业务方法
public String log() throws Exception{
return "hello";
}
//校验方法
@Override
public void validate() {
// TODO Auto-generated method stub
super.validate();
}
//log方法的校验方法
public void validateLog(){
Date date=new Date();
if(null==book.getName() || book.getName().equals("")) {
addFieldError("name", "name must not null");
}
if(null==book.getPrice() || book.getPrice()<=0){
addFieldError("price", "price must >0");
}
if(null==book.getDate() || book.getDate().getTime()>=date.getTime()) {
addFieldError("date", "date is error");
}
if(null==book.getCount() || book.getCount()<=0) {
addFieldError("count", "count must >0");
}
}
}
- hello.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'hello.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>
name:<s:property value="book.name"/><br>
price:<s:property value="book.price"/><br>
date:<s:property value="book.date"/><br>
count:<s:property value="book.count"/><br>
</body>
</html>
国际化
- action
package com.action;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
private static final long serialVersionUID = 1L;
//name属性
private String name;
//age属性
private int age;
//tel属性
private String tel;
//name属性getter方法
public String getName() {
return name;
}
//name属性setter方法
public void setName(String name) {
this.name = name;
}
//age属性getter方法
public int getAge() {
return age;
}
//age属性setter方法
public void setAge(int age) {
this.age = age;
}
//tel属性getter方法
public String getTel() {
return tel;
}
//tel属性setter方法
public void setTel(String tel) {
this.tel = tel;
}
//重载execute方法
public String execute() throws Exception {
return "hello";
}
//log方法,Action调用的method方法
public String log()throws Exception{
System.out.println("log");
return "hello";
}
}
- struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.custom.i18n.resources" value="login"></constant>
<package name="default" namespace="/" extends="struts-default">
<action name="login" class="com.action.LoginAction">
<result name="hello">/hello.jsp</result>
</action>
</package>
</struts>
- 在src目录下创建全局国际化文件
- login_zh_CN.properties
### 设置error常量为错误
error=\u9519\u8BEF
### 设置success常量为成功
success=\u6210\u529F
### 设置name常量为姓名
name=\u59D3\u540D
### 设置tel常量为电话号码
tel=\u7535\u8BDD\u53F7\u7801
### 设置age常量为年龄
age=\u5E74\u9F84
### 设置welcome常量为欢迎注册
welcome=\u6B22\u8FCE\u6CE8\u518C\uFF01
- login_en_US.properties
error=Error
success=Success
name=Name
tel=Tel
age=Age
welcome=Welcome to Login!
- index.jsp
- 用
<s:text name="welcome"/>
取出国际化资源中的内容
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<h3>
<s:text name="welcome"/>
</h3>
<s:form action="login">
<s:textfield name="name" key="name"/>
<s:textfield name="age" key="age"/>
<s:textfield name="tel" key="tel"/>
<s:submit method="log"></s:submit>
</s:form>
</center>
</body>
</html>
- hello.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
Name:<s:property value="name"/><br/>
Age:<s:property value="age"/><br/>
Telephone:<s:property value="tel"/><br/>
</center>
</body>
</html>