SSH architecture: Spring + struts 2 + hibernate, xml implementation and annotation implementation

1, MVC layering overview

1. Request execution process

[view layer: jsp] - > [control layer: (struts: action) useraction class]

                           ---> [business layer: userservice] - > [dao layer: (hibernate): userdao]

2. Overview of correspondence of each layer

  • Server side (operation data)

(1) Control layer: action --- call the business layer
(2) Business layer: service --- call dao layer processing class and process dao layer results

  •   Define service interface
  •   Define the service implementation class

(3) dao layer - specific operation database

  •   Define dao interface
  • Define dao implementation classes

  • Client (user requests)

(4) View layer --- user operation interface

2, Implementing SSH with xml

1. Encapsulate entity class (Type)

(1) Corresponding database table [class name = table name, field name = table field name]

            setget encapsulates everything, tostring rewrites, constructor (remove id)
(2) Create an xml Mapping file for the class (hibernate)

(3) Inject the XML file (the value of the list in the sessionFectory configuration) into the spring schema in applicationContext.xml
    [note]: for entity classes that have no corresponding relationship with the database, it is not necessary to generate the mapping file of entity classes. The mapping file is the mapping between entity classes and database objects

//1. Entity class: commodity and category are many to one relationships
public class Product {
  //Class properties
    private int id;
	private String name;
    //tid foreign keys do not need encapsulation. They are 1-to-many. The object of 1 is declared in many classes
    private Type type;	
	public Type getType() {
			return type;
	public void setType(Type type) {
			this.type = type;
  //set get encapsulation properties
   public int getId() {
		return id;
	public void setId(int id) { = id;
	public String getName() {
		return name;
	public void setName(String name) { = name;
  //Parameterless, parameterless constructor, toString omitted
public class Type {
	private int id;
	private String name;
	//Declare a collection of multiple types in one (one type corresponds to multiple product s)
	private Set<Product> pis=new HashSet<>(0);
	//set get encapsulates a collection
	public Set<Product> getPis() {
		return pis;
	public void setPis(Set<Product> pis) {
		this.pis = pis;
	public int getId() {
		return id;
	public void setId(int id) { = id;
	public String getName() {
		return name;
	public void setName(String name) { = name;
//2. hibernate relational mapping file xml

<!-- 1.table Is the corresponding table name in the database -->
    <class name="com.sqf.entity.Product" table="product">
   <!--  2.All colum Change the value of to the same value name Lower case with the same value -->
        <id name="id" type="int">
            <column name="id" />
            <!-- 3.Change here to native -->
            <generator class="native" />
        <property name="name" type="java.lang.String">
            <column name="name" />
        <property name="brand" type="java.lang.String">
            <column name="brand" />
        <property name="num" type="int">
            <column name="num" />
       <!--  3.Configure mapping relationship:name Value is declared in this class type Object, column of name For foreign keys in the database tid -->
        <many-to-one name="type" class="com.sqf.entity.Type" fetch="select" lazy="false">
            <column name="tid" />
    <class name="com.sqf.entity.Type" table="type">
        <id name="id" type="int">
            <column name="id" />
            <generator class="native" />
        <property name="name" type="java.lang.String">
            <column name="name" />
        <!-- Configure mapping relationship: name Is the name of the collection object declared in this class, inverse by true Indicates abandonment of maintenance, column of name Still foreign key tid
                                cascade: Generate cascade operation           
        <set name="pis" table="product" inverse="true" cascade="all">
                <column name="tid" />
            <one-to-many class="com.sqf.entity.Product" />
//3. Configure Spring configuration file
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean"> 
  <!-- Connect database in file, configure hibernate Its own attributes are omitted -->
  <!-- Class mapping file written in value The mapping file path corresponding to the class added here, and the path of the class injected in the annotation -->
  <property name="mappingResources">

2. dao layer [database data specific operation layer, processing specific values]

  (1) Define dao interface (TypeDao) and declare only function name
  (2) Define to the interface implementation class (TypeDaoImple), inherit the dao interface and implement its functions [first declare the sessionFectory object and set encapsulation; then complete the implementation class]
  (3) To applicationContext.xml, inject dao layer into spring architecture with bean node

  •   The id value is the dao layer object name declared by the dao layer in the spring architecture;
  • Class: enter the name of the implementation class of TypeDaoImple and the path prompted;
  • Within the bean node, use the property node to assign a value to the sessionFectory object declared in daoimpl

3. service layer [the layer that calls dao layer functions and processes dao layer operation results]

(1) Define the service interface (TypeService) and declare the corresponding function name in the dao interface
(2) Define the service implementation class (TypeServiceImpl), inherit the service interface, and implement the classes therein

  •     First, declare the object declared by the dao layer in the spring architecture in the implementation class (that is, the id value of the bean node declared by the dao in applicationContext.xml),
  •     set get encapsulation, the dao layer object is used to invoke the function of the dao layer in the service implementation class.

(3) To applicationContext.xml, use the bean node to inject the service layer into the spring architecture (similar to dao layer injection), and use the property node inside the bean node to assign values to the dao layer objects declared in the service implementation class

      [note]  :   The id value is the service layer object name declared by the service layer in the spring architecture

//The function code of dao and service layers is omitted. It only shows how to configure the objects of each layer into the Spring container for unified management
//[applicationContext.xml] spring configuration file
  <!--(1)dao layer  -->  
  <bean id="productDao" class="com.sqf.dao.ProductDaoImpl">
       <property name="sessionFactory" ref="sessionFactory"></property>
  <!-- (2)service layer -->
  <bean id="productService" class="com.sqf.service.ProductServiceImpl">
    <property name="productDao" ref="productDao"></property>
  <!--(3)action layer  -->
  <bean id="productAction" class="com.sqf.action.ProductAction">
      <property name="productService" ref="productService"></property>

4. action layer [layer calling service layer function]

(1) Obtain the entity class service object, that is, declare the object declared by the service layer in the spring architecture (inject the id value of the bean corresponding to the service layer), and set encapsulation
(2) Write the action class, and the database operation is realized by calling its function through the declared service object
(3) To applicationContext.xml, inject the action layer into the Spring architecture with a bean node, and assign values to the service layer objects declared in the action layer with a property node

          [note]: the id value of the bean is the object declared by the action layer

(4) Configure the struts.xml file, and the class can directly call the object (id value). The function is the same as writing the path of the action class

          [note]: the function of the struts.xml file is to connect the action layer and the front-end request

//[action class] - take a function function as an example
//1. Declared as the action layer, obtain the session object through the interface class and obtain the front-end parameters through ModelDriven
public class ProductAction implements SessionAware,ModelDriven<Product>{
//2. Get the front-end object through ModelDriven
	Product product=new Product();
	public Product getModel() {
		return this.product;
//3. Obtain session
	Map<String, Object> session;
	public void setSession(Map<String, Object> arg0) {
//4. Obtain the object declared in the bean used by the service layer, encapsulate the set, and inject the object through the set method
	ProductService productService;
	public void setProductService(ProductService productService) {
		this.productService = productService;
	//5. Write processing function
	  public String add(){
		int i=productService.add(product);
		  return "success";
		}else{return "error";}

//[struts.xml] connect the front and back ends
	<constant name="struts.i18n.encoding" value="utf-8"></constant>
	<!-- Define a name digital Package, inheritance struts 2 The default package for the specified namespace is"/" -->
	<package name="digital" namespace="/" extends="struts-default">
		<!-- [Note] configure the mapping for the methods in the class: name: jsp in action Request name
		class: by applicationcontexxml In the file action Defined id(Or fill action The path of the class, method Is the name of the processing function
		result Equivalent to in annotation result to configure, name The string returned for the handler function-->
		<!-- Add function -->
		<action name="add" class="productAction" method="add">
			<result name="error">add.jsp</result>
			<result name="success" type="redirect">getAll</result>

[note] there are three front and rear end parameter transmission modes

  • Hyperlink parameter passing: in the action class, set get encapsulates the parameter name passed in the jsp [the two should be consistent]

    < A herf = request name? Parameter name = value >

  • The name attribute of jsp passes parameters: in action: declare an object ui of this class and setget the object; jsp:

  <input name=ui.password>

  • model driven parameter passing: directly inherit the modelDriven class in the action class; The name attribute value ui in the jsp is removed,

< input name = corresponding attribute in class >

 <input name=password>

3, Implement SSH in annotation mode

(1) entity class layer [omit xml configuration file of class]:
Notes to be added are:
<1> Before class: @ entity [identify entity] @ table (name = corresponding table name, catalog = database name) [identify which table in which database the entity class is mapped to]
<2> Before the primary key id: @ id [id] @ Generatevalue (strategy=GenerationType.identity) [primary key generation strategy: Auto increment. The primary key in the database must be set to auto increment, otherwise an error will occur] @ column(name=id)
<3> Other attributes: @ column(name = attribute name)
<4> Associated (such as one to many relationship with type class):
Type type; [declare a class object associated with it]
@ManyToOne (fetch = fechtype. Eagle) [equivalent to last = false, no delay] @ JoinColumn(name="tid") [name is the corresponding type foreign key tid of the product class in the database, corresponding to the field in the database]
(2) Dao layer [omit the set after injecting Dao layer object (including id) and declaring sessionFectory object in spring XML file]
<1> In front of the Daoimpl implementation class: @ Repository ("productinfoDao") [identify it as the dao layer and declare an object productinfoDao externally, which is equivalent to the id value declared by the bean in the xml configuration file injected into spring]
<2> Annotate the objects declared in the class (the objects to be declared in the class, and set injection):
SessionFectory sessionFectory; [in this way, only declaration is required, and set injection is not required]
(3) Service layer [omit the set that injects the service layer object and declares the dao layer object in the spring XML file]
<1> Before serviceimpl implements the class: @ service ("poducinfoservice") [identify this class as a service layer class and declare an object poducinfoservice of this layer]
      productdao productinfoDao; [this is the object productinfodao declared by dao layer]
(4) Action layer [omit the configuration of injecting action layer objects and strut s into spring xml files]
<1> Before action class: @ cotoller [identify this class as the class of the control layer]
<2> service object required for annotation
      Productservice poducinfoservice [is the object declared externally when the service layer annotation is declared]
<3> Before the action processing function: [p311]
@action (value = "url passed from the front end: value after")
[the processing process remains unchanged]
Finally: out.write (variable) is passed to the front-end jsp
(5) jsp [using easyui] pass data and action request name in javascript [p309]

[note] 1. Omitted parts:
(1) Class configuration file is not needed
(2)strut. xml is not needed
(3) spring's ApplicationContext. There is no need to use bean s to inject objects at all levels in xml [only write to the transaction manager]
2. Parts to be modified:
<1> Change the injection of entity class xml file to annotate the location of entity class [annotate a class, inject a don't forget in spring!!!]
<2>appicationCntext. In xml, the injection of objects at all levels should be changed to enable the annotation processor [p229]

To be sorted out, to be more

Tags: Spring ssh xml architecture

Posted on Fri, 29 Oct 2021 09:18:35 -0400 by chipev