Sorting out Java Web Framework -- configuring SSM framework

Article directory


From how2j
github project portal

Set up SSM project

POJO

package com.how2java.pojo;
 
public class Category {
    private int id;
    private String name;
    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;
    }
    @Override
    public String toString() {
        return "Category [id=" + id + ", name=" + name + "]";
    }
     
}

CategoryMapper

package com.how2java.mapper;
  
import java.util.List;
 
import com.how2java.pojo.Category;
  
public interface CategoryMapper {
  
    public int add(Category category); 
        
    public void delete(int id); 
        
    public Category get(int id); 
      
    public int update(Category category);  
        
    public List<Category> list();
     
    public int count(); 
     
}

Configure Category.xml

  • Category.xml needs to be placed under the same package as the CategoryMapper, and the namespace must write the full class name of the CategoryMapper
  • Code:
<?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">
 
    <mapper namespace="com.how2java.mapper.CategoryMapper">
        <insert id="add" parameterType="Category" >
            insert into category_ ( name ) values (#{name})   
        </insert>
         
        <delete id="delete" parameterType="Category" >
            delete from category_ where id= #{id}  
        </delete>
         
        <select id="get" parameterType="_int" resultType="Category">
            select * from   category_  where id= #{id}   
        </select>
 
        <update id="update" parameterType="Category" >
            update category_ set name=#{name} where id=#{id}   
        </update>
        <select id="list" resultType="Category">
            select * from   category_     
        </select>    
    </mapper>

CategoryService

package com.how2java.service;
 
import java.util.List;
 
import com.how2java.pojo.Category;
 
public interface CategoryService {
 
    List<Category> list();
 
}

CategoryServiceImpl

  • CategoryServiceImpl is marked as a Service by annotation @ Service
    And it's equipped with a categoryMapper
  • Code:
package com.how2java.service.impl;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.how2java.mapper.CategoryMapper;
import com.how2java.pojo.Category;
import com.how2java.service.CategoryService;
 
@Service
public class CategoryServiceImpl  implements CategoryService{
    @Autowired
    CategoryMapper categoryMapper;
     
    public List<Category> list(){
        return categoryMapper.list();
    }
 
}

CategoryController

  • CategoryController is marked as a Controller by @ Controller
    Automatically assembled the categoryService
  • Access the path / listCategory path to the method listCategory() through the @ RequestMapping map.
  • In the listCategory() method, get it through the categoryService and store it on the "cs" key.
  • Code:
package com.how2java.controller;
 
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.servlet.ModelAndView;
 
import com.how2java.pojo.Category;
import com.how2java.service.CategoryService;
 
// Tell spring mvc this is a controller class
@Controller
@RequestMapping("")
public class CategoryController {
    @Autowired
    CategoryService categoryService;
 
    @RequestMapping("listCategory")
    public ModelAndView listCategory(){
        ModelAndView mav = new ModelAndView();
        List<Category> cs= categoryService.list();
         
        // Put forward parameters
        mav.addObject("cs", cs);
        // Put jsp path
        mav.setViewName("listCategory");
        return mav;
    }
 
}

web.xml

Add web.xml in the WEB-INF directory. This web.xml has two functions:

  • When starting the web app through ContextLoaderListener, obtain the file name applicationContext.xml of contextConfigLocation configuration file, and carry out Spring related initialization

  • Any access is blocked by dispatcher servlet, which is the working mechanism of Spring MVC.

  • Code:

<?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"
         xmlns:web="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_2_5.xsd" version="2.5">
     
    <!-- spring Profile for-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
     
    <!-- spring mvc Core: distribution servlet -->
    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!-- spring mvc Profile for -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springMVC.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
     
</web-app>

applicationContext.xml

Create a new applicationContext.xml file in the src directory, which is the configuration file of Spring, and its function is to

  1. Through annotation, the Service life cycle is included in Spring management
<context:annotation-config />
<context:component-scan base-package="com.how2java.service" />
  1. Configure data source < bean id = "datasource" class = "org. Springframework. JDBC. Datasource. Drivermanagerdatasource" >
  2. Scan the category.xml < bean id = "sqlsession" class = "org. Mybatis. Spring. Sqlsessionfactorybean" >
  3. Scan mapper and incorporate its lifecycle into spring management < bean class = "org. Mybatis. Spring. Mapper. Mapperscannerconfigurer" >
  • 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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="
     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
     http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
     http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
     http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
     http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
     
   <context:annotation-config />
    <context:component-scan base-package="com.how2java.service" />
 
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
      <property name="driverClassName"> 
          <value>com.mysql.jdbc.Driver</value> 
      </property> 
      <property name="url"> 
          <value>jdbc:mysql://localhost:3306/how2java?characterEncoding=UTF-8</value> 
     
      </property> 
      <property name="username"> 
          <value>root</value> 
      </property> 
      <property name="password"> 
          <value>admin</value> 
      </property>    
    </bean>
     
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="typeAliasesPackage" value="com.how2java.pojo" />
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath:com/how2java/mapper/*.xml"/>
    </bean>
 
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.how2java.mapper"/>
    </bean>
     
</beans>

springMVC.xml

Create springMVC.xml in src directory

  1. Scan Controller and incorporate its lifecycle into Spring management
 <context:annotation-config/>
   <context:component-scan base-package="com.how2java.controller">
         <context:include-filter type="annotation" 
         expression="org.springframework.stereotype.Controller"/>
   </context:component-scan>

  1. Annotation driven, so that the matching of access path and method can be configured through annotation
    <mvc:annotation-driven />
  2. Static pages, such as HTML, CSS, JS and images, can access < MVC: default servlet handler / >
  3. View to / WEB/INF/jsp
<bean  class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
  • 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:aop="http://www.springframework.org/schema/aop"
    xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
        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
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
 
    <context:annotation-config/>
 
    <context:component-scan base-package="com.how2java.controller">
          <context:include-filter type="annotation"
          expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
 
    <mvc:annotation-driven />
     
    <mvc:default-servlet-handler />
 
    <!-- View location -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass"
            value="org.springframework.web.servlet.view.JstlView" />
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
</beans>

listCategory.jsp

  • Create the JSP directory under WEB-INF, and create the file listCategory.jsp.
    In this jsp file, through the forEach tag, traverse the collection data passed by the CategoryController.
  • Code:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
  
<table align='center' border='1' cellspacing='0'>
    <tr>
        <td>id</td>
        <td>name</td>
    </tr>
    <c:forEach items="${cs}" var="c" varStatus="st">
        <tr>
            <td>${c.id}</td>
            <td>${c.name}</td>
               
        </tr>
    </c:forEach>
</table>

Could not resolve type alias' categoryMap '. Cause: java.lang.ClassNotFoundException:

  • At first, I thought there was a problem with the path configured under sqlSession, but later I found that it was not
  • Go to tomcat's temporary path to see that there is no compiled. class file under the classes, and then see that there is no. class under the build of the project in the workspace, so there should be a bug in eclipse;
  • After clearing, restart eclipse

Effect:

Process combing

  1. First access path on Browser / listCategory
  2. According to the configuration information on web.xml, tomcat intercepts / listCategory and hands it over to dispatcher servlet for processing.
  3. According to the configuration of springMVC, DispatcherServlet sends the request to the CategoryController class for processing through @ RequestMapping, so the class needs to be instantiated
  4. When instantiating the CategoryController, inject the CategoryServiceImpl. (automatically assemble the instance that implements the CategoryService interface. Only the CategoryServiceImpl implements the CategoryService interface, so it will inject the CategoryServiceImpl)
  5. When instantiating the CategoryServiceImpl, inject the CategoryMapper
  6. According to the configuration information in ApplicationContext.xml, the CategoryMapper and Category.xml are associated.
  7. In this way, you get the instantiated CategoryController and call the list method
  8. In the list method, access the CategoryService, get the data, put the data on "cs", and then the server jumps to listCategory.jsp
  9. Finally, display the data in listCategory.jsp

Configure CRUD for SSM

Add editCategory.jsp

  • Code:
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 
 <div style="width:500px;margin:0px auto;text-align:center">
	
	
	<div style="text-align:center;margin-top:40px">
		
		<form method="post" action="updateCategory">
			//Classification Name: <input name="name" value="${c.name}" type="text"> <br><br>
			<input type="hidden" value="${c.id}" name="id">
			<input type="submit" value="Increase classification">
		</form>

	</div>	
 </div>
  • Where action=updateCategory

Modify CategoryController

  • Code:
package com.how2java.controller;


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.servlet.ModelAndView;

import com.how2java.pojo.Category;
import com.how2java.service.CategoryService;
import com.how2java.util.Page;

// spring mvc is a machine
@Controller
@RequestMapping("")
public class CategoryController {
	@Autowired
	CategoryService categoryService;

	@RequestMapping("listCategory")
	public ModelAndView listCategory(Page page){
	
		ModelAndView mav = new ModelAndView();
		List<Category> cs= categoryService.list(page);
		int total = categoryService.total();
		
		page.caculateLast(total);
		
		// Enter the roll number
		mav.addObject("cs", cs);
		// Enter jsp path
		mav.setViewName("listCategory");
		return mav;
	}
	
	@RequestMapping("addCategory")
	public ModelAndView addCategory(Category category){
		categoryService.add(category);
		ModelAndView mav = new ModelAndView("redirect:/listCategory");
	    return mav;
	}	
	@RequestMapping("deleteCategory")
	public ModelAndView deleteCategory(Category category){
		categoryService.delete(category);
		ModelAndView mav = new ModelAndView("redirect:/listCategory");
		return mav;
	}	
	@RequestMapping("editCategory")
	public ModelAndView editCategory(Category category){
		Category c= categoryService.get(category.getId());
		ModelAndView mav = new ModelAndView("editCategory");
		mav.addObject("c", c);
		return mav;
	}	
	@RequestMapping("updateCategory")
	public ModelAndView updateCategory(Category category){
		categoryService.update(category);
		ModelAndView mav = new ModelAndView("redirect:/listCategory");
		return mav;
	}	

}

  • page plug-in
  • Service

CategoryService

  • CategoryService.java
package com.how2java.service;

import java.util.List;

import com.how2java.pojo.Category;
import com.how2java.util.Page;

public interface CategoryService {

	List<Category> list();
	int total();
	List<Category> list(Page page);
	void add(Category c);
	void update(Category c);
	void delete(Category c);
	Category get(int id);

}

  • CategoryServiceImpl.java
package com.how2java.service.impl;

import java.util.List;

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

import com.how2java.mapper.CategoryMapper;
import com.how2java.pojo.Category;
import com.how2java.service.CategoryService;
import com.how2java.util.Page;

@Service
public class CategoryServiceImpl  implements CategoryService{
	@Autowired
	CategoryMapper categoryMapper;
	
	
	public List<Category> list(){
		return categoryMapper.list();
	}


	@Override
	public List<Category> list(Page page) {
		// TODO Auto-generated method stub
		return categoryMapper.list(page);
	}


	@Override
	public int total() {
		return categoryMapper.total();
	}


	@Override
	public void add(Category c) {
		categoryMapper.add(c);
		
	}


	@Override
	public void update(Category c) {
		categoryMapper.update(c);
	}


	@Override
	public void delete(Category c) {
		categoryMapper.delete(c.getId());
	}


	@Override
	public Category get(int id) {
		// TODO Auto-generated method stub
		return categoryMapper.get(id);
	};

}

Configure Page paging

  • Import package
  • page.java
package com.how2java.util;

public class Page {

	int start=0;
	int count = 5;
	int last = 0;
	public int getStart() {
		return start;
	}
	public void setStart(int start) {
		this.start = start;
	}
	public int getCount() {
		return count;
	}
	public void setCount(int count) {
		this.count = count;
	}
	public int getLast() {
		return last;
	}
	public void setLast(int last) {
		this.last = last;
	}
	
	public void caculateLast(int total) {
	    // If the total number is 50, which can be divided by 5, then the beginning of the last page is 45
	    if (0 == total % count)
	        last = total - count;
	    // If the total number is 51 and cannot be divided by 5, then the beginning of the last page is 50
	    else
	        last = total - total % count;		
	}

	
	
	
}

Insert a code slice here

Configure CategoryMapper

  • CategoryMapper.java
package com.how2java.mapper;
 
import java.util.List;

import com.how2java.pojo.Category;
import com.how2java.util.Page;;
 
public interface CategoryMapper {
 
      
    public int add(Category category);  
       
      
    public void delete(int id);  
       
      
    public Category get(int id);  
     
      
    public int update(Category category);   
       
      
    public List<Category> list();
    
    public List<Category> list(Page page);
    
      
    public int total();  
    
    
    
}
  • Category.xml
<?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">

	<mapper namespace="com.how2java.mapper.CategoryMapper">
	    <insert id="add" parameterType="Category" >
	        insert into category_ ( name ) values (#{name})    
	    </insert>
	    
	    <delete id="delete" parameterType="Category" >
	        delete from category_ where id= #{id}   
	    </delete>
	    
	    <select id="get" parameterType="_int" resultType="Category">
	        select * from   category_  where id= #{id}    
	    </select>

	    <update id="update" parameterType="Category" >
	        update category_ set name=#{name} where id=#{id}    
	    </update>
	    <select id="list" resultType="Category">
	        select * from   category_ order by id desc     
	        <if test="start!=null and count!=null">
                    limit #{start},#{count}
            </if>
            
	    </select>
	    <select id="total" resultType="int">
	        select count(*) from   category_      
	    </select>	    	    
	</mapper>

listCategory

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" import="java.util.*"%>
 
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
 
 <div style="width:500px;margin:0px auto;text-align:center">
	<table align='center' border='1' cellspacing='0'>
	    <tr>
	        <td>id</td>
	        <td>name</td>
	        <td>edit</td>
	        <td>delete</td>
	    </tr>
	    <c:forEach items="${cs}" var="c" varStatus="st">
	        <tr>
	            <td>${c.id}</td>
	            <td>${c.name}</td>
	            <td><a href="editCategory?id=${c.id}">edit</a></td>
	            <td><a href="deleteCategory?id=${c.id}">delete</a></td>
	        </tr>
	    </c:forEach>
	</table>
	<div style="text-align:center">
		<a href="?start=0">Home page</a>
		<a href="?start=${page.start-page.count}">Previous page</a>
		<a href="?start=${page.start+page.count}">next page</a>
		<a href="?start=${page.last}">Last page</a>
	</div>
	
	
	<div style="text-align:center;margin-top:40px">
		
		<form method="post" action="addCategory">
			Classification Name: <input name="name" value="" type="text"> <br><br>
			<input type="submit" value="Increase classification">
		</form>

	</div>	
 </div>

Effect

109 original articles published, 50 praised, 90000 visitors+
Private letter follow

Tags: xml Java Spring JSP

Posted on Thu, 13 Feb 2020 01:07:06 -0800 by ChrisMartino