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 = "/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 = "/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="/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文件,增加重定向

<%--
  Created by IntelliJ IDEA.
  User: 15435
  Date: 2019/1/14
  Time: 11:09
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    通过post传递参数


名字:${name}

年龄:${age}

<% response.sendRedirect("users"); %>

修改user.jsp,增加超链接功能,href里的“addUser2”对应的是UserController里的addUser2方法

<%@ page import="SpringmvcDemo.DB.entity.UsersEntity" %>
<%@ page import="java.util.List" %>
<%@ page pageEncoding="utf-8" %>


    用户列表


    <%for (UsersEntity entity:(List)request.getAttribute("users")){%>
  1. 姓名:<%out.print(entity.getName());%> 年龄:<%out.print(entity.getAge());%>
  2. <%}%>
添加用户

你可能感兴趣的:(SpringMVC数据库操作(向数据库写入))