SpringMVC数据库操作(向数据库写入)

将HelloWorld里的addUser2方法和resultpost方法剪贴到UserController
在resultpost方法里增加数据库写入代码
package SpringmvcDemo.Controllers; import SpringmvcDemo.DB.DbConnector; import SpringmvcDemo.DB.entity.UsersEntity; import SpringmvcDemo.User; import org.hibernate.Session; import org.hibernate.Transaction; import org.hibernate.criterion.Order; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.List; @Controller public class UserController {@RequestMapping(value = "https://www.it610.com/users",method = RequestMethod.GET) public String allUsers(ModelMap modelMap){ Session session = DbConnector.getSession(); //创建数据库连接List list =session.createCriteria(UsersEntity.class).addOrder(Order.desc("id")).list(); modelMap.addAttribute("users",list); session.close(); //关闭数据库连接return "users"; }@RequestMapping(value = "https://www.it610.com/resultpost",method=RequestMethod.POST) //参数里增加HttpServletRequest request public String resultpost(ModelMap modelMap, @RequestParam String name, @RequestParam int age, HttpServletRequest request){ modelMap.addAttribute("name",name); modelMap.addAttribute("age",age); //连接数据库 Session session = DbConnector.getSession(); //开始事务 Transaction transaction = session.beginTransaction(); //创建一个实体对象,设置name,age UsersEntity usersEntity = new UsersEntity(); usersEntity.setName(name); usersEntity.setAge((byte) age); //保存 session.save(usersEntity); //提交 transaction.commit(); //关闭数据库连接 session.close(); return "resultpost"; }@RequestMapping(value="https://www.it610.com/addUser2",method = RequestMethod.GET) public String addUser2(ModelMap modelMap){ User u = new User(); u.setName("hi"); modelMap.addAttribute("user",u); return "adduser_springmvc"; }}

修改resultpost.jsp文件,增加重定向
通过post传递参数 - 锐客网 名字:${name} 年龄:${age}

【SpringMVC数据库操作(向数据库写入)】修改user.jsp,增加超链接功能,href里的“addUser2”对应的是UserController里的addUser2方法
用户列表 - 锐客网
  1. 姓名: 年龄:
添加用户

    推荐阅读