概述
1.在struts-config.xml中配置mysql数据源:
value="com.mysql.jdbc.Driver" />
value="jdbc:mysql://localhost:3306/struts?characterEncoding=UTF-8" />
2.在struts-config.xml中配置PersonForm与PersonAction:
attribute="personForm"
input="/form/addPerson.jsp"
name="personForm"
path="/person"
scope="request"
type="com.li.struts.action.PersonAction">
3.Person类代码,Person类封装了人员信息:
public class Person {
private Integer id;
private String account;
private String name;
private Date birthday;
private Timestamp createDate=new Timestamp(System.currentTimeMillis());
private boolean secret;
private List hobby=new ArrayList();
}
4.Action代码:保存用户信息
主方法execute()是一个分发器,根据action参数分发到不同的执行方法。
public class PersonAction extends Action {
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception{
PersonForm personForm = (PersonForm) form;// TODO Auto-generated method stub
if("add".equals(personForm.getAction())){
return add(mapping,form,request,response);
}else if("list".equals(personForm.getAction())){
return List(mapping,form,request,response);
}
return mapping.getInputForward();
}
private ActionForward add(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
PersonForm personForm=(PersonForm) form;
// 转化日期
Date birthday = new Date(new SimpleDateFormat("yyyy-MM-dd").parse(
personForm.getBirthday()).getTime());
Person person=new Person();
person.setAccount(personForm.getAccount());
person.setName(personForm.getName());
person.setSecret(personForm.isSecret());
person.setCreateDate(new Timestamp(System.currentTimeMillis()));//记录用户创建或注册时间;
person.setBirthday(birthday);
person.setHobby(Arrays.asList(personForm.getHobby()));//由于Person类里hobby是List类型
//,所以用List hobby=Arrays.asList(personForm.getHobby());传递数组值。详见com.li.filter.lll.java
PersonDAO personDAO=new PersonDAO();
Connection conn=getDataSource(request).getConnection();
personDAO.addPerson(conn,person);//调用DAO层的方法存储person注册的数据
request.setAttribute("person", person);
return mapping.findForward("success");
}
}
其中,Person类里的hobby是List类型,form里是String[ ]数组类型,所以用List hobby=Arrays.asList(personForm.getHobby());传递数组值。
最后
以上就是温柔烧鹅为你收集整理的class action extends mysql{_struts学习笔记—Action实例:保存用户信息到数据库(1)的全部内容,希望文章能够帮你解决class action extends mysql{_struts学习笔记—Action实例:保存用户信息到数据库(1)所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复