表单中有一种textarea的控件,可以提交长一点的内容,比如要写一篇很长的文章,是不能用type=text的文本框的,因为这种文本框只显示一行。在表单里定义一个textarea标记就可以来输入长文本数据,并且可以换行显示。
这个jsp存为/WebContent/form2.jsp。在from2.jsp里面使用了textarea标记,并且把它的属性rows行数设为10,列数cols设为100,名称为"information"。同时,在form标记里,加了一个method="post",也就是提交表单时使用post方法提交。
表单中action的值也改成了postPerson。那么,PersonController.java中需要新增一个postPerson方法。
@RequestMapping(value = "/postPerson", method = RequestMethod.POST) public Object postPerson(HttpServletRequest request, HttpServletResponse response, String id, String nation, String information) { try { // String id = (String) request.getAttribute("id"); // String nation = (String) request.getAttribute("nation"); // String information = (String) // request.getAttribute("information"); Person person = new Person(); person.setId(Integer.parseInt(id)); person.setNation(nation); person.setInformation(information); personService.addPerson(person); Person personAdd = personService.findPerson(id); request.setAttribute("person", personAdd); } catch (Exception e) { e.printStackTrace(); } return "jsp/person.jsp"; }这个postPerson方法,请求路径为/postPerson,并且method改为了method = RequestMethod.POST,即是使用POST方法来接收参数。需要说明的是,使用POST方法接收参数,就不能用request.getParameter的方式了,这种request.getParameter只能接收到地址里有?id=的这种参数。如果要接收POST表单数据,可以在postPerson方法参数里加入三个参数, String id, String nation, String information。
public Object postPerson(HttpServletRequest request, HttpServletResponse response, String id, String nation, String information)
这里新增的参数person.setInformation(information);也需要给person对象存起来,所以在Person.java中新加一个属性information,还要生成getter和setter方法。
private String information;
public String getInformation() {
return information;
}
public void setInformation(String information) {
this.information = information;
}
不仅如此,数据表也要增加字段information,这里给出sql为:
ALTER TABLE `newdb`.`new_table` ADD COLUMN `information` TEXT NULL AFTER `nation`;
执行这条sql语句,数据表new_table会新增一个字段information。
另外,还需要改两个地方,就是PersonJdbcTemplateDaoImpl中的addPerson和findPersonById方法的实现。
public int add(Person person) throws Exception { int updatedRow = this.getJdbcTemplate().update("insert into new_table (id, nation, information) values (?,?,?)", person.getId(), person.getNation(), person.getInformation()); return updatedRow; }
public Person getPersonById(String id) throws Exception { Map personrMap = this.getJdbcTemplate().queryForMap("select * from new_table where id=? limit 1", id); Person person = new Person(); person.setId((Integer) personrMap.get("id")); person.setNation((String) personrMap.get("nation")); person.setInformation((String) personrMap.get("information")); return person; }
新增了一个information属性,就需要牵动这么多地方,以后开发的时候就习惯这种变动了,其实这里只是很简单的改动而已。
重新启动Tomcat来访问下form2.jsp,输入一些内容并提交,就可以得到保存的数据。
提交后的地址为http://localhost/calculateWeb/postPerson,就不再有?id=这种参数了,所以也相对安全了些。显示结果为:
person: Person [id=4, nation=JP, information=This is a person. He is from JP. He is Japanese.]
Java视频教程