# 3.5 getBean & getModel series

The getModel method is used to receive a model object passed from the page form field. The form field name is named in the "modelName.attrName" format. The attrName used by getModel must match the database table field name exactly.

The getBean method supports traditional Java Beans, including Models with generated getter and setter methods by jfinal. When passing parameters from a page form, it uses the attrName consistent with the setter method, rather than the database table field name.

The difference between getModel and getBean is that the former uses the database table field names for data injection, while the latter uses property names consistent with the setter method. It is recommended to prioritize using the getBean method.

Here's a simple example:

// Define a Model, in this case, Blog
public class Blog extends Model<Blog> {
    
}
1
2
3
4

In the form on the webpage, use the "modelName.attrName" format as the form field's name:

<form action="/blog/save" method="post">
  <input name="blog.title" type="text">
  <input name="blog.content" type="text">
  <input value="提交" type="submit">
</form>
1
2
3
4
5
public class BlogController extends Controller {
  public void save() {
    // The modelName from the page matches the class name "Blog" with the first letter in lowercase
    Blog blog = getModel(Blog.class);
 
    // If the form field's name is "otherName.title", you can add a parameter to retrieve it
    blog = getModel(Blog.class, "otherName");
  }
}
1
2
3
4
5
6
7
8
9

In the above code, the form fields use "blog.title" and "blog.content" as their name attributes. "blog" is the lowercase first letter of the class name "Blog", and "title" is the title field of the blog database table. If you want the form field to use any modelName, just add a parameter to specify it when calling getModel, like getModel(Blog.class, "otherName").

If you want to avoid using the modelName prefix when passing parameters, you can use an empty string as the modelName: getModel(Blog.class, ""). This is very useful for pure API projects (getBean works similarly).

If you want to skip data conversion or property name error exceptions during reception, you can pass in a true parameter: getBean(…, true).

Last Updated: 9/17/2023, 5:50:29 AM