The first time to use the SSM framework to write list additions, deletions, modifications, and pagination

Tip: After the article is written, the table of contents can be automatically generated. How to generate it can refer to the help document on the right


foreword

This is a hands-on project for learning how to use SSM before doing the course design project. It includes framework construction, addition, deletion, modification, and paging of the list, and the realization of paging functions. Most of the content below is personal learning perception. Correct communication.


1. Framework construction

My SSM framework construction is learned at station b. The framework construction does not need to be written by myself. It is enough to copy the framework from other places and learn it. It is enough to know the role of each position in the framework. 

ssm project construction_哔哩哔哩_bilibili

Attached here is a video of the framework study, UP's lecture is very clear, and there are corresponding documents.

There are three sections in the SSM framework, Dao layer, Service layer and Controller layer.

The Dao layer is the bottom layer, responsible for calling and modifying the data in the database; the Service layer is the middle layer, responsible for data transmission and connection between the Dao layer and the Controller layer, and the Controller layer is the top layer, responsible for processing relevant data from the web page and returning data to web pages.

For example, restaurants.

When a customer (webpage) comes to eat, he first orders food (data request) from the waiter (Controller layer), and the waiter writes the food ordered by the customer (data request) to the back kitchen window (Service layer), and the back kitchen (Dao layer) according to the window requirements Process the ingredients (database data) and put them in the window, and the waiter will take the dishes to the customers.

Would it be easier to understand the general role of SSM in this way?

Next, let’s talk about the specific project, a list of student information. It is recommended to learn to integrate after learning the three major sections of Spring, SpringMVC and MyBatis.

 In the end my file with frame was created as shown in the image below.

The jsp page file is shown in the figure below, and the subsequent configuration files will set the prefix and suffix of the jsp file

The role of web.xml is to configure DispatcherServlet, which is used to intercept web page url requests and distribute them.

The following filter is used to solve the problem of garbled encoding.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" id="WebApp_ID" version="4.0">
  <display-name>springLearn</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
	 <servlet>
	    <servlet-name>DispatcherServlet</servlet-name>
	    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
	    <init-param> 
	    	
	         <param-name>contextConfigLocation</param-name>
	         <!--一定要注意:我们这里加载的是总的配置文件,之前被这里坑了!-->
	         <param-value>classpath:applicationContext.xml</param-value>
	    </init-param>
	    <load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
	    <servlet-name>DispatcherServlet</servlet-name>
	    <!--注意这里不能配置成/*-->
	    <url-pattern>/</url-pattern>
	</servlet-mapping>
	
	<!--encodingFilter-->
	<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>
	<filter-mapping>
	    <filter-name>encodingFilter</filter-name>
	    <url-pattern>/*</url-pattern>
	</filter-mapping>
  
</web-app>

This framework is written by dividing the content in applicationContext.xml into three parts, and this file is to integrate the three sub-files.

applicationContext.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:tx="http://www.springframework.org/schema/tx"
       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
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd">
        
        <import resource="classpath:spring-dao.xml"/>
        <import resource="classpath:spring-service.xml"/>
        <import resource="classpath:spring-mvc.xml"/>
        
</beans>

 The Mybatis-config.xml file is used to configure aliases and scan dao layer interface files

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
	<!-- 配置别名 -->
    <typeAliases>
    	<package name="com.pojo"/>
	</typeAliases>
	<!-- 配置扫描dao层接口 -->
	<mappers>
	    <package name="com.dao"/>
	</mappers>
</configuration>

 spring-dao.xml is used for the configuration of related files at the bottom of the SSM framework, that is, the layer connected to the database.

<?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: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
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd">
        
        <!-- 数据库连接池 -->
		<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
		    <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
            <!-- cj是mysql8.0的一个特性 -->
		    <property name="url" value="jdbc:mysql://localhost:3306/student?serverTimezone=UTC"/>
		    <property name="username" value="root"/>
		    <property name="password" value="123456"/>
		</bean>
		
		<!-- 配置SqlSessionFactory对象 -->
		<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		    <property name="dataSource" ref="dataSource" />
		    <!-- mybatis配置文件的位置 -->
		    <property name="configLocation" value="classpath:mybatis-config.xml"/>
		</bean>
		
		
		<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        	<property name="basePackage" value="com.dao"/>
    	</bean>

		
		
</beans>

spring-mvc.xml is the configuration of the view parser and annotations, that is, the configuration of the prefix and suffix of the jsp file and the alias scanning of the method of the pojo layer entity class, which is more convenient for writing methods

<?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: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
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd">

   		<!-- 1.开启SpringMVC注解驱动 -->
		<mvc:annotation-driven/>
		
		<!-- 2.静态资源默认servlet配置-->
		<mvc:default-servlet-handler/>
		
		<!-- 3.配置jsp 显示ViewResolver视图解析器 -->
		<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		    <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
		    <!-- /WEB-INF/jsp/+视图名+.jsp -->
		    <!-- 前缀 -->
		    <property name="prefix" value="/WEB-INF/jsp/" />
		    <!-- 后缀 -->
		    <property name="suffix" value=".jsp" />
		</bean>
		
		<context:component-scan base-package="com.controller"></context:component-scan>
		

</beans>

spring-service is the scan of the service method

<?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: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
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd">
        
        <context:component-scan base-package="com.service"></context:component-scan>
        
</beans>

Second, the specific method of writing steps

1. Controller layer method

@RequestMapping fills in the url of the webpage, that is, enter http://localhost:8080/StudentSSM/pagelistStudent in the browser , where StudentSSM is the project name, and the pagelistStudent behind it is the content of @

The page to be redirected is the content in setViewName, which should be the name of the jsp page (since the prefix and suffix have been set in the configuration file, just fill in the name of the jsp page here)

package com.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.pojo.Page;
import com.pojo.Student;
import com.service.StudentService;

@Controller
public class Studentcontroller {
	@Autowired
	StudentService studentservice;
	@RequestMapping("/listStudent")
	public ModelAndView listStudent() {
		ModelAndView mav = new ModelAndView();
		List<Student> stduents=studentservice.list();
		mav.addObject("students",stduents);
		mav.setViewName("listStudent");
		return mav;
	}
	@RequestMapping("/pagelistStudent")
	public ModelAndView pagelistStudent(Page page) {
		
		ModelAndView mav = new ModelAndView();
		int total = studentservice.total();
        //设置页码防溢出
		if(page.getstart()<0)
			page.setstart(0);
		if(page.getstart()>total)
			page.setstart(total-1);
		page.calculatelast(total);
		List<Student> pagestudents=studentservice.pagelist(page);
		mav.addObject("pagestudents",pagestudents);
		mav.setViewName("listStudent");
		return mav;
	}
	@RequestMapping("/getStudent")
	public ModelAndView getStudent(int sno) {
		ModelAndView mav = new ModelAndView();
		Student student = studentservice.get(sno);
		List<Student> get = new ArrayList<Student>();
		get.add(student);
		mav.addObject("get",get);
		mav.setViewName("getStudent");
		return mav;
	}
	@RequestMapping("/deleteStudent")
	public ModelAndView deleteStudent(int sno,Page page) {
		ModelAndView mav = new ModelAndView();
		studentservice.delete(sno);
		int total = studentservice.total();
		if(page.getstart()<0)
			page.setstart(0);
		if(page.getstart()>total)
			page.setstart(total-1);
		page.calculatelast(total);
		List<Student> delete=studentservice.pagelist(page);
		mav.addObject("delete",delete);
		mav.setViewName("listStudent");
		return mav;
	}
	@RequestMapping("/beforeinsertStudent")
	public ModelAndView beforeinsertStudent() {
		ModelAndView mav = new ModelAndView();
		mav.setViewName("insertStudent");
		return mav;
	}

	@RequestMapping("/insertStudent")
	public ModelAndView insertStudent(int sno,String sname,Page page) {
		ModelAndView mav = new ModelAndView();
		studentservice.insert(sno,sname);
		int total = studentservice.total();
		if(page.getstart()<0)
			page.setstart(0);
		if(page.getstart()>total)
			page.setstart(total-1);
		page.calculatelast(total);
		List<Student> insert=studentservice.pagelist(page);
		mav.addObject("insert",insert);
		mav.setViewName("listStudent");
		return mav;
	}
	@RequestMapping("/beforeupdateStudent")
	public ModelAndView beforeupdateStudent(int id,int sno,String sname) {
		ModelAndView mav = new ModelAndView();
		mav.addObject("id",id);
		mav.addObject("sno",sno);
		mav.addObject("sname",sname);
		mav.setViewName("updateStudent");
		return mav;
	}
	@RequestMapping("/updateStudent")
	public ModelAndView updateStudent(int id,int sno,String sname) {
		ModelAndView mav = new ModelAndView();
		studentservice.update(id,sno,sname);
		List<Student> update = studentservice.list();
		mav.addObject("update",update);
		mav.setViewName("listStudent");
		return mav;
	}
}

2. Service layer method

 Through the interface to realize the method of calling the method of the Controller layer and the method of calling the Dao layer

package com.service;

import java.util.List;

import com.pojo.Page;
import com.pojo.Student;

public interface StudentService {
	
	List<Student> list();
	
	List<Student> pagelist(Page page);
	int total();
	
	void delete(int sno);
	
	Student get(int sno);
	
	void insert(int sno,String sname);
	
	void update(int id,int sno,String sname);

}
package com.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.dao.StudentMapper;
import com.pojo.Page;
import com.pojo.Student;
import com.service.StudentService;

@Service
public class StudentServiceImpl implements StudentService{
	
	@Autowired
	StudentMapper studentmapper;
	
	@Override
	public List<Student> list(){
		return studentmapper.list();
	}
	
	@Override
	public Student get(int sno) {
		return studentmapper.get(sno);
	}
	
	@Override
	public void delete(int sno) {
		studentmapper.delete(sno);
	}
	
	@Override
	public void insert(int sno,String sname) {
		studentmapper.insert(sno,sname);
	}
	
	@Override
	public void update(int id,int sno,String sname) {
		studentmapper.update(id,sno,sname);
	}

	@Override
	public List<Student> pagelist(Page page) {
		// TODO Auto-generated method stub
		return studentmapper.pagelist(page);
	}

	@Override
	public int total() {
		// TODO Auto-generated method stub
		return studentmapper.total();
	}
}

3. Dao layer method

 The Dao layer calls the underlying method

package com.dao;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.pojo.Page;
import com.pojo.Student;

public interface StudentMapper {
	
	public List<Student> list();
	
	public List<Student> pagelist(Page page);
	
	public int total();
	
	public void delete(int sno);
	
	public Student get(int sno);
	
	public void insert(@Param("sno")int sno,@Param("sname")String sname);
	
	public void update(@Param("id")int id,@Param("sno")int sno,@Param("sname")String sname);
	
	
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  <!-- namespace:命名空间,填写对应接口的全限定类名 -->      
<mapper namespace="com.dao.StudentMapper">
	<!-- id:list 对应接口的方法-->
	<select id="list" resultType="Student">
		select * from student
	</select>
	<select id="pagelist" resultType="Student">
		select * from student
		<if test="start!=null and count!=null">
			limit #{start},#{count}
		</if>
	</select>
	<select id="total" resultType="int">
		select count(*) from student
	</select>
	<select id="get" resultType="Student" parameterType="int">
		select * from student where Sno = #{sno}
	</select>
	
	<delete id="delete" parameterType="Student">
		delete from student where Sno = #{sno}
	</delete>
	<insert id="insert" parameterType="Student">
		insert into student(Sno,Sname) value(#{sno},"${sname}")
	</insert>
	<update id="update" parameterType="Student">
		update student set Sno=#{sno},Sname=#{sname} where id=#{id}
	</update>
</mapper>

Three, the specific web page display

Finally, such a form will be displayed, in which the names and student numbers have nothing to do with the actual situation, and are only used as data in the form.


Summarize

In general, after building the framework and understanding the writing of related methods, the work will become extremely simple, just spend time to understand it.

Guess you like

Origin blog.csdn.net/laodaye_xiaolizi/article/details/125673126