涉及loc、bean的Spring webmvc启动流程

**

一.mvc是什么?

**
MVC全名是Model View Controller,是模型(model)-视图(view)-控制器(controller)的缩写,一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。

在我的理解中,简单的说,mvc是一种思想,是将前端页面(界面),用户交互(业务逻辑),后端数据处理(数据),分离的思想。

***在我的程序中,我是这样用的:***在这里插入图片描述

二.loc和bean

最大的难点在于loc和bean的概念,在这个链接里,某大佬有了很清晰的阐述:
https://www.awaimai.com/2596.html

1.在实践中,首先需要在web.xml和资源文件/webapp中创建新的xml来进行配置。
我在资源文件中新建了xml
在这里插入图片描述

  • web.xml中主要是使用DispatcherServlet,并且把新建的xml文件的地址设置为contextConfigLocation的值。
    代码如下:
 <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:app-context.xml</param-value>
        </context-param>
    
        <servlet>
            <servlet-name>app</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:app-servlet.xml</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>

        <servlet-mapping>
            <servlet-name>app</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
  • 在app-servlet.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">

    <context:component-scan base-package="class12.controller"/>
    <context:component-scan base-package="class12.model"/>
    <context:component-scan base-package="class12.jdbc"/>
</beans>
  • 在app-context.xml中,用loc的思想,将数据库驱动设为了bean
    <bean id="datasource"
          class="org.apache.commons.dbcp.BasicDataSource"
          destroy-method="close">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://127.0.0.1:3306/school"/>
        <property name="username" value="root"/>
        <property name="password" value="123456"/>
    </bean>

2.在java包里的使用
在这里插入图片描述

  • controller
@Controller
public class addstudent extends HttpServlet {

    @RequestMapping(value = "/addstudent",method = RequestMethod.POST)
    protected String addstudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");//设置编码,以防表单提交的内容乱码

        student st = new student();
        st.setId(req.getParameter("id"));
        st.setName(req.getParameter("name"));
        Date date = new Date();
        st.setCreateTime(date);
        StudentJdbc.addstudent(st);

        return "allstudent.jsp";
    }
}
  • model
    简单的将三个model类注册成了bean,且规定prototype,因为之后在方法selectall中使用,每次使用都储存不同的实例。
@Component
@Scope("prototype")

关于bean的scope可以见这篇文章:
https://www.cnblogs.com/mmzs/p/10411269.html

  • jdbc
    在jdbc中有两个地方使用了bean
    (1)使用bean代替了之前使用的new homework
//全局变量
    private static ApplicationContext ct;
    static{
        ct=new AnnotationConfigApplicationContext(homework.class);
    }
//这是在selectall方法中的语句,摘出来的
    homework hw =(homework)ct.getBean("homework");

(2)数据库驱动改成了在app-context.xml中管理的bean

ApplicationContext ac = new ClassPathXmlApplicationContext("app-context.xml");
        DataSource ds = (DataSource)ac.getBean("datasource");

        List<homework> list = new ArrayList<>();
        try(Connection connection =  ds.getConnection()) {
        ……
        }

三.整个代码具体流程

  • 前端web页面
    jsp页面的用法不必多说,展示其中一个页面:
// An highlighted block
<div align="center">
    <h2>添加作业</h2>
    <form action="${pageContext.request.contextPath}/AddStudentHomeworkServlet" method="post">
        <table style="line-height: 40px">
            <tr>
                <th>学号:</th>
                <td><input type="text" name="id" maxlength="30" size="50" required></td>
            </tr>
            <tr>
            <th>作业id:</th>
            <td><input type="text" name="hwid" maxlength="30" size="50" required></td>
        </tr>
            <tr>
                <th>作业名称:</th>
                <td><input type="text" name="hwname" maxlength="30" size="50" required></td>
            </tr>
            <tr>
                <th>作业内容:</th>
                <td><input type="text" name="content" maxlength="30" size="50" required></td>
            </tr>

            <tr align="center">
                <td><input type="submit" value="添加作业"> </td>
            </tr>
        </table>
    </form>
</div>
  • controller
    在这里用到了bean,接受了前端数据,建了实例并且传到jdbc类进行数据操作
@Controller
public class addstudent extends HttpServlet {

    @RequestMapping(value = "/addstudent",method = RequestMethod.POST)
    protected String addstudent(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");//设置编码,以防表单提交的内容乱码

        student st = new student();
        st.setId(req.getParameter("id"));
        st.setName(req.getParameter("name"));
        Date date = new Date();
        st.setCreateTime(date);
        StudentJdbc.addstudent(st);

        return "allstudent.jsp";
    }
}
  • jdbc
    接收controller传过来的实例,并启动数据库插入数据。
    在前端要展示所有数据时候,selectall方法启动数据库并且用bean创建实例,存入list,在前端展示list。
@Configuration
public class StudentHomeworkJdbc {
    private static ApplicationContext ct;
    static{
        ct=new AnnotationConfigApplicationContext(StudentHomework.class);
    }
    public static void main(String[] args) {
        List<StudentHomework> list = selectAll();

        for (StudentHomework sh : list){
            System.out.println(sh.getHomeworkContent());
        }
    }

    public static boolean addStudentHomework(StudentHomework sh){

        String sqlString = "insert into s_student_homework (student_id,homework_id,homework_title,homework_content,create_time) values(?,?,?,?,?)";
        ApplicationContext ac = new ClassPathXmlApplicationContext("app-context.xml");
        DataSource ds = (DataSource)ac.getBean("datasource");

        int resultSet = 0;
        try (Connection connection = ds.getConnection()) {
            try (PreparedStatement ps = connection.prepareStatement(sqlString)) {
                ps.setString(1,sh.getStudentId());
                ps.setString(2,sh.getHomeworkId());
                ps.setString(3,sh.getHomeworkTitle());
                ps.setString(4,sh.getHomeworkContent());
                ps.setTimestamp(5,new Timestamp(sh.getCreateTime().getTime()));
                resultSet = ps.executeUpdate();

            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return resultSet > 0;
    }

    public static List<StudentHomework> selectAll(){


        String sqlString = "SELECT * FROM s_student_homework";
        ApplicationContext ac = new ClassPathXmlApplicationContext("app-context.xml");
        DataSource ds = (DataSource)ac.getBean("datasource");

        List<StudentHomework> list = new ArrayList<>();
        try(Connection connection =  ds.getConnection()) {
            try(Statement statement = connection.createStatement()){
                try(ResultSet resultSet = statement.executeQuery(sqlString)){
                    // 获取执行结果
                    while (resultSet.next()){
                        StudentHomework sh =(StudentHomework) ct.getBean("StudentHomework");
                        sh.setId(resultSet.getLong("id"));
                        sh.setStudentId(resultSet.getString("student_id"));
                        sh.setHomeworkId(resultSet.getString("homework_id"));
                        sh.setHomeworkTitle(resultSet.getString("homework_title"));
                        sh.setHomeworkContent(resultSet.getString("homework_content"));
                        sh.setCreateTime(resultSet.getTimestamp("create_time"));
                        list.add(sh);
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return list;
    }

}

四.github

https://github.com/Xinchan233/javaee

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring框架中的IOC(Inversion of Control,控制反转)和AOP(Aspect Oriented Programming,面向切面编程)是两个核心概念。 IOC,也被称为依赖注入(Dependency Injection),是一种设计模式,通过将对象的创建和依赖关系的管理交给容器来实现。在Spring中,IOC容器负责创建和管理各个对象,开发者只需要通过配置文件或注解来描述对象及其依赖关系,而无需手动实例化对象。 通过IOC,我们可以将应用程序中的各个组件解耦,提高代码的可维护性和可测试性。Spring的IOC容器可以根据配置文件或注解自动实例化对象,并自动解决对象之间的依赖关系。 AOP是一种编程范式,通过将系统中的各个功能模块(被称为切面)从业务逻辑中抽离出来,以一种横切的方式进行管理。在Spring中,AOP可以帮助我们实现诸如日志记录、事务管理、性能监控等与业务逻辑无关但又必需的功能。 通过AOP,我们可以将这些横切关注点独立出来,并通过配置文件或注解将其应用到指定的目标方法或类上。Spring使用动态代理或字节码增强的方式实现AOP,使得我们可以在不修改原有代码的情况下,对系统进行功能增强。 总结来说,IOC和AOP是Spring框架中的两个重要概念。IOC实现了对象的创建和依赖关系的管理,帮助我们解耦组件,提高代码的可维护性;AOP则实现了横切关注点的管理,帮助我们实现与业务逻辑无关但必需的功能增强。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值