Spring MVC CRUD示例
spring mvc crud示例
crud(创建,读取,更新和删除)应用程序是用于创建任何项目的最重要的应用程序。它提供了开发大型项目的想法。在springmvc中,我们可以开发一个简单的crud应用程序。
在这里,我们使用 jdbctemplate 进行数据库交互。
创建一个表
在这里,我们使用的是mysql数据库中存在的emp99表。它具有4个字段: id,名称,薪水和名称。
spring mvc crud示例
1、将依赖项添加到pom.xml文件。
pom.xml
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-webmvc</artifactid> <version>5.1.1.release</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.tomcat/tomcat-jasper --> <dependency> <groupid>org.apache.tomcat</groupid> <artifactid>tomcat-jasper</artifactid> <version>9.0.12</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api --> <dependency> <groupid>javax.servlet</groupid> <artifactid>servlet-api</artifactid> <version>3.0-alpha-1</version> </dependency> <!-- https://mvnrepository.com/artifact/javax.servlet/jstl --> <dependency> <groupid>javax.servlet</groupid> <artifactid>jstl</artifactid> <version>1.2</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>8.0.11</version> </dependency> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupid>org.springframework</groupid> <artifactid>spring-jdbc</artifactid> <version>5.1.1.release</version> </dependency>
2、创建bean类
在这里,bean类包含对应于数据库中存在的字段的变量(以及setter和getter方法)。
emp.java
package com.yapf.beans; public class emp { private int id; private string name; private float salary; private string designation; public int getid() { return id; } public void setid(int id) { this.id = id; } public string getname() { return name; } public void setname(string name) { this.name = name; } public float getsalary() { return salary; } public void setsalary(float salary) { this.salary = salary; } public string getdesignation() { return designation; } public void setdesignation(string designation) { this.designation = designation; } }
3、创建控制器类
empcontroller.java
package com.yapf.controllers; import java.util.list; import org.springframework.beans.factory.annotation.autowired; import org.springframework.stereotype.controller; import org.springframework.ui.model; import org.springframework.web.bind.annotation.modelattribute; import org.springframework.web.bind.annotation.pathvariable; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestmethod; import com.yapf.beans.emp; import com.yapf.dao.empdao; @controller public class empcontroller { @autowired empdao dao;//will inject dao from xml file /*it displays a form to input data, here "command" is a reserved request attribute *which is used to display object data into form */ @requestmapping("/empform") public string showform(model m){ m.addattribute("command", new emp()); return "empform"; } /*it saves object into database. the @modelattribute puts request data * into model object. you need to mention requestmethod.post method * because default request is get*/ @requestmapping(value="/save",method = requestmethod.post) public string save(@modelattribute("emp") emp emp){ dao.save(emp); return "redirect:/viewemp";//will redirect to viewemp request mapping } /* it provides list of employees in model object */ @requestmapping("/viewemp") public string viewemp(model m){ list<emp> list=dao.getemployees(); m.addattribute("list",list); return "viewemp"; } /* it displays object data into form for the given id. * the @pathvariable puts url data into variable.*/ @requestmapping(value="/editemp/{id}") public string edit(@pathvariable int id, model m){ emp emp=dao.getempbyid(id); m.addattribute("command",emp); return "empeditform"; } /* it updates model object. */ @requestmapping(value="/editsave",method = requestmethod.post) public string editsave(@modelattribute("emp") emp emp){ dao.update(emp); return "redirect:/viewemp"; } /* it deletes record for the given id in url and redirects to /viewemp */ @requestmapping(value="/deleteemp/{id}",method = requestmethod.get) public string delete(@pathvariable int id){ dao.delete(id); return "redirect:/viewemp"; } }
4、创建dao类
让我们创建一个dao类以访问数据库中所需的数据。
empdao.java
package com.yapf.dao; import java.sql.resultset; import java.sql.sqlexception; import java.util.list; import org.springframework.jdbc.core.beanpropertyrowmapper; import org.springframework.jdbc.core.jdbctemplate; import org.springframework.jdbc.core.rowmapper; import com.yapf.beans.emp; public class empdao { jdbctemplate template; public void settemplate(jdbctemplate template) { this.template = template; } public int save(emp p){ string sql="insert into emp99(name,salary,designation) values('"+p.getname()+"',"+p.getsalary()+",'"+p.getdesignation()+"')"; return template.update(sql); } public int update(emp p){ string sql="update emp99 set name='"+p.getname()+"', salary="+p.getsalary()+",designation='"+p.getdesignation()+"' where id="+p.getid()+""; return template.update(sql); } public int delete(int id){ string sql="delete from emp99 where id="+id+""; return template.update(sql); } public emp getempbyid(int id){ string sql="select * from emp99 where id=?"; return template.queryforobject(sql, new object[]{id},new beanpropertyrowmapper<emp>(emp.class)); } public list<emp> getemployees(){ return template.query("select * from emp99",new rowmapper<emp>(){ public emp maprow(resultset rs, int row) throws sqlexception { emp e=new emp(); e.setid(rs.getint(1)); e.setname(rs.getstring(2)); e.setsalary(rs.getfloat(3)); e.setdesignation(rs.getstring(4)); return e; } }); } }
5、在web.xml文件中提供控制器的条目
web.xml
<?xml version="1.0" encoding="utf-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="webapp_id" version="3.0"> <display-name>springmvc</display-name> <servlet> <servlet-name>spring</servlet-name> <servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
6、在xml文件中定义bean
spring-servlet.xml
<?xml version="1.0" encoding="utf-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemalocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <context:component-scan base-package="com.yapf.controllers"></context:component-scan> <bean class="org.springframework.web.servlet.view.internalresourceviewresolver"> <property name="prefix" value="/web-inf/jsp/"></property> <property name="suffix" value=".jsp"></property> </bean> <bean id="ds" class="org.springframework.jdbc.datasource.drivermanagerdatasource"> <property name="driverclassname" value="com.mysql.jdbc.driver"></property> <property name="url" value="jdbc:mysql://localhost:3306/test"></property> <property name="username" value=""></property> <property name="password" value=""></property> </bean> <bean id="jt" class="org.springframework.jdbc.core.jdbctemplate"> <property name="datasource" ref="ds"></property> </bean> <bean id="dao" class="com.yapf.dao.empdao"> <property name="template" ref="jt"></property> </bean> </beans>
7、创建请求的页面
index.jsp
<a href="empform">add employee</a> <a href="viewemp">view employees</a>
8、创建其他视图组件
empform.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <h1>add new employee</h1> <form:form method="post" action="save"> <table > <tr> <td>name : </td> <td><form:input path="name" /></td> </tr> <tr> <td>salary :</td> <td><form:input path="salary" /></td> </tr> <tr> <td>designation :</td> <td><form:input path="designation" /></td> </tr> <tr> <td> </td> <td><input type="submit" value="save" /></td> </tr> </table> </form:form>
empeditform.jsp
此处"/springmvccrudsimple"是项目名称,如果您使用其他项目名称,请更改此名称。对于实时应用程序,您可以提供完整的url。
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <h1>edit employee</h1> <form:form method="post" action="/springmvccrudsimple/editsave"> <table > <tr> <td></td> <td><form:hidden path="id" /></td> </tr> <tr> <td>name : </td> <td><form:input path="name" /></td> </tr> <tr> <td>salary :</td> <td><form:input path="salary" /></td> </tr> <tr> <td>designation :</td> <td><form:input path="designation" /></td> </tr> <tr> <td> </td> <td><input type="submit" value="edit save" /></td> </tr> </table> </form:form>
viewemp.jsp
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <h1>employees list</h1> <table border="2" width="70%" cellpadding="2"> <tr><th>id</th><th>name</th><th>salary</th><th>designation</th><th>edit</th><th>delete</th></tr> <c:foreach var="emp" items="${list}"> <tr> <td>${emp.id}</td> <td>${emp.name}</td> <td>${emp.salary}</td> <td>${emp.designation}</td> <td><a href="editemp/${emp.id}">edit</a></td> <td><a href="deleteemp/${emp.id}">delete</a></td> </tr> </c:foreach> </table> <br/> <a href="empform">add new employee</a>
输出:
点击 添加员工时,您将看到以下表格。
填写表格,然后 单击保存以将条目添加到数据库中。
现在,点击 编辑以对提供的内容进行一些更改数据。
现在,单击 编辑保存,将具有更改的条目添加到数据库中。
现在,单击 删除从数据库中删除条目。