I just learned the springmvc framework recently, and it feels that it is indeed much more convenient and reduces a lot of redundant code. I did a small project to practice. This is a basic springmvc application project. Mybatis is not used. The project functions are quite complete, and the basic functions of addition, deletion, modification and search are realized.
Project environment:
-System: win10
-Development environment: eclipseOxygenReleaseCandidate3 (4.7)
-jdk version: java1.8(121)
-mysql:5.7
-spring:4.0
-tomcat:8.5
Techniques used:
springmvcspringjspjdbcjavaBeanjsjstl
Access address: http://localhost:8080/your project name/all
Statement: I am just a novice who has just started, and there are inevitably any errors in the code I wrote. If you find it, please point it out, thank you everyone.
The detailed process is posted below
1. First create a web project (DynamicWebProject)
I wrote the project name myself, no more detailed
2. This is my completed project structure
I just used the function and did not use the interface. I only used three simple classes, the entity class under the bean package, the dao layer database access class, and the interface control class of the controller layer.
All referenced jar packages are in the /WebContent/WEB-INF/lib folder, which is different from ordinary java projects.
3. Specific java code
1.Student class, entity class first needs to write a javaBean. Mine is Student as javaBean. The detailed code is as follows:
package bean;public class Student { private Integer id;//student id private String name;//student name private Double javaScore;//java score private Double htmlScore;//html score private Double cssScore;//css score private Double totalScore; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getJavaScore() { return javaScore; } public void setJavaScore(Double javaScore) { this.javaScore = javaScore; } public Double getHtmlScore() { return htmlScore; } public void setHtmlScore(Double htmlScore) { this.htmlScore = htmlScore; } public Double getCssScore() { return cssScore; } public void setCssScore(Double cssScore) { this.cssScore = cssScore; } public Double getTotalScore() { return totalScore; } public void setTotalScore(Double totalScore) { this.totalScore = totalScore; }}2. StudentDao, the database access operation class is then the code of the dao layer, that is, the data access layer. Here is a class encapsulated by spring (JdbcTemplate), which contains some methods for operating the database. There are no need to write a lot of repeated code by yourself, just write SQL statements. Here is the specific code:
package dao;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Types;import java.util.List;import org.springframework.jdbc.core.JdbcTemplate;import org.springframework.jdbc.core.RowMapper;import bean.Student;public class StudentDao { /** * @Fields jdbcTemplate : TODO */ private JdbcTemplate jdbcTemplate; /** * Class provided by spring* * @param jdbcTemplate * Return value type: void * @author janinus */ public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } /** * Query all students* * @return Return value type: List<Student> * @author janinus */ public List<Student> queryAll() { String sql = "select id,name,javaScore,htmlScore,cssScore from student"; //Map the query result into the Student class, add it to the list, and return return jdbcTemplate.query(sql, new StudentMapper()); } /** * Query by name* * @param name * @return Return value type: List<Student> * @author janinus */ public List<Student> queryByName(String name) { String sql = "select id,name,javaScore,htmlScore,cssScore from student where name like '%" + name + "%'"; return jdbcTemplate.query(sql, new StudentMapper()); } /** * Add student* * @param student * @return Return value type: boolean * @author janinus */ public boolean addStu(Student student) { String sql = "insert into student(id,name,javaScore,htmlScore,cssScore) values(0,?,?,?,?)"; return jdbcTemplate.update(sql, new Object[] { student.getName(), student.getJavaScore(), student.getHtmlScore(), student.getCssScore() }, new int[] { Types.VARCHAR, Types.DOUBLE, Types.DOUBLE, Types.DOUBLE, Types.DOUBLE }) == 1; } /** * Delete student* * @param id * @return Return value type: boolean * @author janinus */ public boolean deleteStu(Integer id) { String sql = "delete from student where id = ?"; return jdbcTemplate.update(sql, id) == 1; } /** * Update student information* * @param student * @return Return value type: boolean * @author janinus */ public boolean updateStu(Student student) { String sql = "update student set name=? ,javaScore=?,htmlScore = ? ,cssScore = ? where id = ?"; Object stuObj[] = new Object[] { student.getName(), student.getJavaScore(), student.getHtmlScore(), student.getCssScore(), student.getId() }; return jdbcTemplate.update(sql, stuObj) == 1; } /** * Return the total score of the top n students* * @param num * @return Return value type: List<Student> * @author janinus */ public List<Student> topNum(int num) { String sql = "select id,name,javaScore+htmlScore+cssScore from student order by javaScore+htmlScore+cssScore desc ,name asc limit ?"; return jdbcTemplate.query(sql, new RowMapper<Student>() { @Override public Student mapRow(ResultSet rs, int rowNum) throws SQLException { // TODO Auto-generated method stub Student student = new Student(); student.setId(rs.getInt(1)); student.setName(rs.getString(2)); student.setTotalScore(rs.getDouble(3)); return student; } }, num); } /** * * StudentMapper database mapping* * @ClassName StudentMapper * @author janinus * @date June 27, 2017* @Version V1.0 */ class StudentMapper implements RowMapper<Student> { @Override public Student mapRow(ResultSet rs, int rowNum) throws SQLException { // TODO Auto-generated method stub Student student = new Student(); student.setId(rs.getInt(1)); student.setName(rs.getString(2)); student.setJavaScore(rs.getDouble(3)); student.setHtmlScore(rs.getDouble(4)); student.setCssScore(rs.getDouble(5)); return student; } }}3. StudentController , the front-end interaction class is finally the control layer StudentController class related to user interaction. This class is mainly used to combine the front-end and back-end to achieve complete interaction. Here is the specific code:
package controller;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import bean.Student;import dao.StudentDao;@Controllerpublic class StudentController { /** * * Get all student information from the database and return the data to the home page index,jsp * * @param model * @return Return value type: String * @author janinus */ @RequestMapping(value = "/all") public String queryAll(Model model) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //Get dao StudentDao dao = (StudentDao) context.getBean("dao"); model.addAttribute("students", dao.queryAll()); model.addAttribute("tops", dao.topNum(3)); return "index.jsp"; } /** * Find students by name, use fuzzy search, and return the result to index.jsp * * @param name * @param model * @return Return value type: String * @author janinus */ @RequestMapping(value = "/queryByName") public String queryByName(String name, Model model) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); //Get dao from the ioc container StudentDao dao = (StudentDao) context.getBean("dao"); model.addAttribute("students", dao.queryByName(name)); model.addAttribute("tops", dao.topNum(3)); return "index.jsp"; } /** * Add new student and return the result to the all page, forwarded from all to the home page* @param name * @param javaScore * @param htmlScore * @param cssScore * @param model * @return Return value type: String * @author janinus */ @RequestMapping(value = "/add") public String addStu(String name, String javaScore, String htmlScore, String cssScore, Model model) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDao dao = (StudentDao) context.getBean("dao"); Student student = new Student(); student.setName(name); student.setJavaScore(Double.parseDouble(javaScore)); student.setHtmlScore(Double.parseDouble(htmlScore)); student.setCssScore(Double.parseDouble(cssScore)); boolean result = dao.addStu(student); if (result) model.addAttribute("msg", "<script>alert('Added Successfully!')</script>"); else model.addAttribute("msg", "<script>alert('Added successfully!')</script>"); return "all"; } /** * Delete student by id* @param id * @param model * @return Return value type: String * @author janinus */ @RequestMapping(value = "/deleteById") public String deleteById(String id, Model model) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDao dao = (StudentDao) context.getBean("dao"); boolean result = dao.deleteStu(Integer.parseInt(id)); if (result) model.addAttribute("msg", "<script>alert('Delete Successfully!')</script>"); else model.addAttribute("msg", "<script>alert('Delete Successfully!')</script>"); return "all"; } /** * * @param id * @param name * @param javaScore * @param htmlScore * @param cssScore * @param model * @return Return value type: String * @author janinus */ @RequestMapping(value = "/update") public String updateStu(String id, String name, String javaScore, String htmlScore, String cssScore, Model model) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); StudentDao dao = (StudentDao) context.getBean("dao"); Student student = new Student(); student.setId(Integer.parseInt(id)); student.setName(name); student.setJavaScore(Double.parseDouble(javaScore)); student.setHtmlScore(Double.parseDouble(htmlScore)); student.setCssScore(Double.parseDouble(cssScore)); boolean result = dao.updateStu(student); if (result) model.addAttribute("msg", msg("modified successfully")); else model.addAttribute("msg", msg("Modification failed")); return "all"; } /** * Page message to pop up* @param msg * @return Return value type: String * @author janinus */ public String msg(String msg) { return "<script>alert('" + msg + "')</script>"; }}All the java code has been completed, and only the specific XML configuration and front-end page are left below.
4. Front-end page
Since it is a simple small project, my js and css are all on the same page, not separated, only two pages,
1.index.jsp
Home page, screenshot
edit
Detailed code:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Student Management</title></head><style type="text/css"> body{ text-align: center; } .all{ width:40%; margin: 20px 100px; text-align: center; height: 300px; float: left; } table{ width: 80%; margin: 20px auto; font-size: 14px; overflow: auto; } #tab02{ width: 80%; margin: 20px auto; font-size: 14px; } table th,table td{ border-bottom: 1px #000 solid; line-height: 23px; } #edit_comm{ width: 500px; margin: 20px auto; border-left: 3px solid #000; display: none; } #add_comm{ width: 500px; margin: 20px auto; border-left: 3px solid #000; } #all_comm{ height:600px; } .edit_stu{ width:200px; height: 30px; background: #fff; font-family: "Microsoft Ya Black Light", "Arial Black"; font-size: 18px; border: none; border-bottom: 1px solid #000; margin: 20px 10px; }</style><script src="http://code.jquery.com/jquery-latest.js"></script><script type="text/javascript"> $(function(){ $("#cancel").click(function(){ $("#add_comm").fadeIn(); $("#edit_comm").fadeOut(); }) $("input").addClass("edit_stu"); }) function refush(){ window.location.href="all" rel="external nofollow" rel="external nofollow" ; } function add_reg(){ var name = $("#add_edit_name").val(); var javaScore = $("#add_edit_java").val(); var htmlScore = $("#add_edit_html").val(); var cssScore=$("#add_edit_css").val(); var nameNot = name!=null&&name!=''; var javaScoreNot = javaScore!=null && javaScore != ''; var htmlScoreNot = htmlScore!=null && htmlScore !=''; var cssScoreNot = cssScore !=null && cssScore != ''; if(nameNot&javaScoreNot&&htmlScoreNot&&cssScoreNot) return true; else return false; } function delete_stu(id){ var result = confirm("Did it be deleted?"); if(result) window.location.href="deleteById?id="rel="external nofollow" +id; } function edit_stu(id){ var name = $("#name"+id).text(); var java = $("#java"+id).text(); var html = $("#html"+id).text(); var css = $("#css"+id).text(); $("#edit_id").val(id); $("#edit_name").val(name); $("#edit_java").val(java); $("#edit_html").val(html); $("#edit_css").val(css); $("#add_comm").fadeOut(); $("#edit_comm").fadeIn(); }</script><body>${msg }<h1 align="center">Student Management</h1><div id="all_comm" > <h2>All Student</h2> <table id="items" > <tr> <td>id</td> <td>name</td> <td>java score</td> <td>html score</td> <td>css score</td> <td>operation</td> </td> </tr> <c:forEach items="${students }" var="student" > <tr> <td id="id${student.id }">${student.id }</td> <td id="name${student.id }">${student.name }</td> <td id="java${student.id}">${student.javaScore }</td> <td id="html${student.id }">${student.htmlScore }</td> <td id="css${student.id}">${student.cssScore }</td> <td ><a onclick="delete_stu(${student.id})">Delete</a>|<a onclick="edit_stu(${student.id})">Edit</a></td> </tr> </c:forEach> </table> <table id="tab02"> <h2>Top three</h2> <tr> <td>Ranking</td> <td>id</td> <td>Name</td> <td>Total Score</td> </tr> <c:forEach items="${tops }" var="student" varStatus="i"> <tr> <td>${i.index+1 }name</td> <td id="id${student.id }t">${student.id }</td> <td>${student.name }</td> <td id="name${student.id }t">${student.totalScore }</td> </tr> </c:forEach> </table> If not displayed: <a onclick="refush()" >Click here to refresh</a></div><div id="add_comm"> <h2>Find student</h2> <form action="queryByName" method="post" > <input type="text" placeholder="Student name" name="name" > <input type="submit" value="Find student" > </form> <h2 id="edit_title">Add student</h2> <form action="add" method="post" > <input type="text" placeholder="Student name" name="name" /> <input type="text" placeholder="java score" name="javaScore" /> <input type="text" placeholder="html score" name="htmlScore" /> <input type="text" placeholder="css score" name="cssScore" /> <input type="submit" value="Confirm to add" /> </form></div><div id="edit_comm"> <h2 id="edit_title">Edit student</h2> <form action="update" method="post"> <input type="text" placeholder="id to be modified is" id="edit_id" name="id" value="The id to be modified is" readonly="readonly"/><br> <input type="text" placeholder="student name" id="edit_name" name="name" /> <input type="text" placeholder="java score" id="edit_java" name="javaScore" > <input type="text" placeholder="html score" id="edit_html" name="htmlScore" /> <input type="text" placeholder="css score" id="edit_css" name="cssScore" /> <input type="submit" value="Confirm Modification" /> <input type="button" value="Cancel Modification" id="cancel"/> </form></div></body></html>2. login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><h1 align="center"><a href="all" rel="external nofollow" rel="external nofollow" >Enter homepage</a></h1></body></html>
5. Detailed file configuration
1. applicationContext.xml
This is the configuration file of spring's IOC container, used to implement dependency injection. The following is the specific code:
<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd" default-autowire="byName" default-lazy-init="true" > <!--Database Data Source Configuration --> <bean id="dataSource"> <!--Loading driver class --> <property name="driverClassName" value="com.mysql.jdbc.Driver"></property> <!--Database Access Address--> <property name="url" value="jdbc:mysql://localhost:3306/test"></property> <!--Database Access User Name--> <property name="username" value="root"></property> <!--Database access password--> <property name="password" value="123123"></property> </bean> <!-- Database transaction management provided by spring--> <bean id="txManager"> <property name="dataSource" ref="dataSource"></property> </bean> <tx:annotation-driven transaction-manager="txManager"/> <!--Configure javaBean entity class--> <bean id="studentBean"> <!--Attribute automatic configuration--> </bean> <!-- Database access operation class provided by spring--> <bean id="jdbcTemplate"></bean> <!-- dao layer class--> <bean id="dao"></bean> <!-- Control layer class, this configuration is invalid--> <bean id="controller"> <property name="dao" ref="dao"></property> </bean> </beans>
2. springMVC-servlet.xml, spring mvc configuration class,
We have implemented most of the code of servlet for us, and we only need to write a business implementation. Below is the specific code
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <!-- Automatically scan the class under the specified package --> <context:component-scan base-package="controller" /></beans>
3. web.xml
This is the configuration file of the web project, and the following is the main code:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><!--Configure character encoding filters, provided by spring--><filter> <filter-name>encodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>utf-8</param-value> </init-param></filter><!-- Configure welcome interface--><welcome-file-list> <welcome-file>/all</welcome-file> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file></welcome-file-list><!-- Configure springmvc servlet --><servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup></servlet><servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>/</url-pattern></servlet-mapping></web-app>
6. Project summary and appendix
This project is my daily practice program. In order to be more proficient, I reviewed the complete process again and became familiar with it a lot.
Appendix to the jar package used for the project:
In addition to the spring package, there are also mysql-jbdc jar package and jstl jar package
Download address:
Spring framework jar package (optional version): spring official website
mysql-jdbc.jar (optional version): MySQL official website
jstl.jar (optional version): maven official address
The above is the entire content of this article about the complete example of Spring MVC implementing the addition, deletion, modification and search of mysql database. I hope it will be helpful to everyone. Interested friends can continue to refer to this site:
Detailed explanation of the configuration of WEB module in Spring
Springmvc Rest style introduction and implementation code example
SpringMVC interceptor implements single sign-on
If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!