SpringMVC总结

Posted 可峰科技

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringMVC总结相关的知识,希望对你有一定的参考价值。

MVC
M->Model:指代处理与记录数据的模型。
V->View:用于显示Model数据的界面。
C->Controller:是对Severlet的继续封装,可以使用注解来简化编程。

一般的流程是
第1步: 浏览器请求->Controller
第2步:Controller中接收请求的数据,进行处理(有可能和数据库打交道),然后把处理后的数据,存入Model中,返回给浏览器。
第3步:浏览器获取Model之后,对Model中的数据,在View中进行显示。

详细demo

1- 先在pojo中写一个Books类

package com.kuang.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books 

    private int bookID;
    private String bookName;
    private int bookCounts;
    private String detail;



然后写dao层,这里是BookMapper

package com.kuang.dao;

import com.kuang.pojo.Books;
import org.apache.ibatis.annotations.Param;

import java.util.List;

public interface BookMapper 

    //add
    int addBook(Books book);

    //delete
    int deleteBookById(@Param("bookId") int id);

    //update
    int updateBook(Books books);

    //query
    Books queryBookById(@Param("bookId") int id);

    //query all book
    List<Books> queryAllBook();

    //
    Books queryBookByName(@Param("bookName") String bookName);


BookMapper的实现BookMapper.xml

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

<mapper namespace="com.kuang.dao.BookMapper">

    <insert id="addBook" parameterType="Books">
        insert into ssmbuild.books (bookName, bookCounts, detail)
        values (#bookName, #bookCounts, #detail);
    </insert>

    <delete id="deleteBookById" parameterType="int">
        delete from ssmbuild.books where bookID = #bookId
    </delete>

    <update id="updateBook" parameterType="Books">
        update ssmbuild.books
        set bookName = #bookName,bookCounts=#bookCounts,detail=#detail
        where bookID=#bookID
    </update>

    <select id="queryBookById" resultType="Books" parameterType="int">
        select * from ssmbuild.books
        where bookID = #bookId
    </select>

    <select id="queryAllBook" resultType="Books">
        select * from ssmbuild.books
    </select>

    <select id="queryBookByName" resultType="Books">
        select * from ssmbuild.books
        where bookName = #bookName
    </select>


</mapper>

然后配置mybatis

-mybatis-config.xml

<?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>

        <settings>
            <setting name="logImpl" value="STDOUT_LOGGING"/>
        </settings>

    <typeAliases>
        <package name="com.kuang.pojo"/>
    </typeAliases>

    <mappers>
        <mapper class="com.kuang.dao.BookMapper"></mapper>
    </mappers>

</configuration>



接着配置数据库连接信息database.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&useUnicode=true&characterEncoding=UTF-8
name=root
password=123456

dao层写完了,就写service层

package com.kuang.service;

import com.kuang.pojo.Books;

import java.util.List;

public interface BookService 

    //add
    int addBook(Books book);

    //delete
    int deleteBookById(int id);

    //update
    int updateBook(Books books);

    //query
    Books queryBookById(int id);

    //query all book
    List<Books> queryAllBook();

    //
    Books queryBookByName(String name);


然后实现该service层,写BookServiceImpl

package com.kuang.service;

import com.kuang.dao.BookMapper;
import com.kuang.pojo.Books;

import java.util.List;

public class BookServiceImpl implements BookService

    //service调dao层:组合Dao
    private BookMapper bookMapper;

    public void setBookMapper(BookMapper bookMapper) 
        this.bookMapper = bookMapper;
    

    @Override
    public int addBook(Books book) 
        return bookMapper.addBook(book);
    

    @Override
    public int deleteBookById(int id) 
        return bookMapper.deleteBookById(id);
    

    @Override
    public int updateBook(Books books) 
        return bookMapper.updateBook(books);
    

    @Override
    public Books queryBookById(int id) 
        return bookMapper.queryBookById(id);
    

    @Override
    public List<Books> queryAllBook() 
        return bookMapper.queryAllBook();
    

    @Override
    public Books queryBookByName(String name) 
        return bookMapper.queryBookByName(name);
    


然后使用spring来托管dao层,编写spring-dao.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

<!--1.关联数据库配置文件-->
<context:property-placeholder location="classpath:database.properties"/>

<!-- 2.连接池-->
<!--    dbcp:半自动化操作,不能自动连接-->
<!--    c3p0:自动化操作(自动化的加载配置文件,并且可以自动设置到对象中!)-->
<!--    druid: hikari-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
    <property name="driverClass" value="$driver"/>
    <property name="jdbcUrl" value="$url"/>
    <property name="user" value="$name"/>
    <property name="password" value="$password"/>

    <property name="maxPoolSize" value="30"/>
    <property name="minPoolSize" value="10"/>
    <property name="autoCommitOnClose" value="false"/>
    <property name="checkoutTimeout" value="10000"/>
    <property name="acquireRetryAttempts" value="2"/>
</bean>

<!--    3.sqlSessionFactory-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis-config.xml"/>
    </bean>

<!--    配置dao接口扫描包,动态实现了dao接口可以注入到Spring容器中!-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!--        注入sqlSessionFactory-->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
        <property name="basePackage" value="com.kuang.dao"/>
    </bean>

</beans>

然后spring托管service层,编写spring-service.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/cache"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/cache
        http://www.springframework.org/schema/cache/spring-cache.xsd
        http://www.springframework.org/schema/aop
        https://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/tx
        https://www.springframework.org/schema/tx/spring-tx.xsd">

<!--        1.扫描service下的包-->
<context:component-scan base-package="com.kuang.service"/>

<!--    2.将我们的所有业务类,注入到Spring,可以通过配置,或者注解实现-->
    <bean id="BookServiceImpl" class="com.kuang.service.BookServiceImpl">
        <property name="bookMapper" ref="bookMapper"/>
    </bean>

<!--    3.声明式事务配置-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!--        注入数据源-->
        <property name="dataSource" ref="dataSource"/>
    </bean>

<!--    4.aop事务支持-->
<!--    结合AOP实现事务的植入-->
<!--    配置事务通知-->
<!--    <tx:advice id="txAdvice" transaction-manager="transactionManager">-->
<!--&lt;!&ndash;        给那些方法配置事务&ndash;&gt;-->
<!--&lt;!&ndash;        配置事务的传播特性&ndash;&gt;-->
<!--        <tx:attributes>-->
<!--            <tx:method name="*" propagetion="REQUIRED"></tx:method>-->
<!--        </tx:attributes>-->
<!--    </tx:advice>-->
<!--    -->
<!--&lt;!&ndash;    配置事务的切入&ndash;&gt;-->
<!--     <aop:config>-->
<!--         <aop:pointcut id="txPointCut" expression="* com.kuang.dao.*.*(..))"/>-->
<!--         <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointCut"></aop:advisor>-->
<!--     </aop:config>-->
</beans>

最后spring配置Controller层,编写spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        https://www.springframework.org/schema/context/spring-context.xsd">

    <import resource="classpath:spring-dao.xml"/>
    <import resource="classpath:spring-service.xml"/>

    <!--    1.注解驱动-->
    <mvc:annotation-driven/>
    <!--    2.静态资源过滤-->
    <mvc:default-servlet-handler/>
    <!--    3.扫描包:contoller-->
    <context:component-scan base-package="com.kuang.controller"/>
    <!--    4.视图解析器-->

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

编写Controller层,编写BookController类

package com.kuang.controller;

import com.kuang.pojo.Books;
import com.kuang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

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

@Controller
@RequestMapping("/book")
public class BookController 
    //controller 调 service层
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    //查询全部的书籍,并且返回到一个书籍展示页面
    @RequestMapping("/allBook")
    public String list(Model model)
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list",list);
        return "allBook";
    

    @RequestMapping("/toAddBook")
    public String toAddPaper()
        return "addBook";
    

    @RequestMapping("addBook")
    public String addBook(Books books)
        bookService.addBook(books);
        return "redirect:/book/allBook";
    

    @RequestMapping("/toUpdate")
    public String toUpdatePaper(int id, Model model)
        System.out.println("id is " + id);
        Books books = bookService.queryBookById(id);
        model.addAttribute("QBook", books);
        return "updateBook";
    基于Spring+SpringMVC+MyBatis开发书评网图书详情页-显示评论列表开发

基于Spring+SpringMVC+MyBatis-Plus开发书评网图书详情模块开发之获取图书信息并展示

SpringMVC框架详解(学习总结)

SpringMVC总结

springMVC学习总结 --springMVC表单处理和静态文件处理

springMVC学习总结 --springMVC重定向