1、如何获取session等API
在servlet中,获取session需要从request对象中获取,struts2与servlet解耦后,提供个了ActionContext类,通过这个类可以获取session、request、application这三个对象
Map<String,Object> session=ActionContext.getContext().getSession()
想要在session里放入登录的用户,直接session.put(“loginUser”,user),就可以实现了
request=ActionContext.getContext().get(“request”)
application=ActionContext.getContext().getApplication()
另外,也可以通过实现ServletRequestAware, ServletResponseAware的方式得到request和response
另外,struts2也提供了耦合的方法获取servlet的API。通过 ServletActionContext.getRequest();ServletActionContext.getResponse()能获取到request和response等但需要导入javax.servlet.api依赖。
2、数据校验
action继承于AtionSupport类,该类不仅对Ation接口进行简单实现,同时增加了验证,本地化等支持。重写其validate方法,在方法内部编写自定义的数据校验逻辑。
3、前后端传值
struts2不仅可以将基本数据类型在控制器和前端页面之间传递,其中模型驱动封装还可以传递类类型,首先控制器要实现ModelDriven的getModle方法,并且将类类型作为控制器的私有属性,private Item item = new Item(),在前端往后端传递时,标签的name属性的值与类类型属性的的值保持一致,struts2就会自动封装在类类型中,但是如果属性和模型驱动封装同时使用,属性封装无法获得值,例如:
Item类
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Item implements Serializable {
/**
* 产品编号
*/
private String code;
/**
* 产品名称
*/
private String name;
/**
* 产品描述
*/
private String description;
/**
* 风险等级
*/
private String risk;
控制器
//实现ModelDriven<Item>的getModel,前端传过来的数据自动封装成对象
public class ItemAction extends ActionSupport implements ModelDriven<Item> {
@Autowired
private ItemService itemService;
//申明要封装的对象
private Item item = new Item();
private Result result;
//获取前端传过来的Item对象,属于ModelDriven<Item>的抽象方法,不能删除
@Override
public Item getModel() {
return item;
}
}
前端form表单,为了减少篇幅,上两个文件的属性没有写全,对应相应的属性即可。
<form action="http://localhost:8088/putaway" method="post">
<div class="row">
<div class="col-sm-6 col-md-5 col-lg-5