美文网首页
SpringMVC学习day-66:SpringMVC的框架搭建

SpringMVC学习day-66:SpringMVC的框架搭建

作者: 开源oo柒 | 来源:发表于2019-10-23 23:04 被阅读0次

    一、SpringMVC的框架搭建

    1.SpringMVC的简介:

    MVC:
    Model(模型)是应用程序中用于处理应用程序数据逻辑的部分。通常模型对象负责在数据库中存取数据。
    View(视图)是应用程序中处理数据显示的部分。通常视图是依据模型数据创建的。
    Controller(控制器)是应用程序中处理用户交互的部分。通常控制器负责从视图读取数据,控制用户输入,并向模型发送数据。

    • 为什么学习SpringMVC:

    (1)我们发现,每当用户发送一个请求,就对应后台一个servlet,如果用户有100个请求,这个时候就需要用户书写100个servlet。
    (2)使用现在servlet进行页面数据接受的时候,我们发现相当的麻烦。
    (3)我们书写的java代码和servlet 之间的耦合太高。

    • SpringMVC的概念:

    springMVC是一种web层mvc框架,用于替代servlet(处理|响应请求,获取表单参数,表单校验等);
    Spring mvc

    示意图

    2.SpringMVC框架搭建:

    • SpringMVC搭建的步骤:
      (1)导包:


      jar包

      (2)配置web.xml:

    在web.xml中,配置ContextLoaderListener(解析spring配置文件)和springmvc的前端控制器。

    <servlet>
            <servlet-name>mvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc.xml</param-value>
            </init-param>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>mvc</servlet-name>
            <!--除了jsp之外的所有请求资源 -->
            <url-pattern>/</url-pattern>
            <!-- <url-pattern>*.action</url-pattern> -->
        </servlet-mapping>
    

    (3)在src下创建springmvc.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:aop="http://www.springframework.org/schema/aop"
        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-4.3.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.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">
            
            <!-- 扫描注解@Controller -->
            <context:component-scan base-package="com.zlw.controller"></context:component-scan>
            
            <!-- @RequestMapping -->
            <mvc:annotation-driven></mvc:annotation-driven>
    </beans>
    

    (4)编写控制器Controller:

    package com.zlw.controller;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    //用于标记在一个类上;该类就是一个SpringMvc Controller对象
    @Controller
    public class MyContorller {
        //处理对应的请求
        @RequestMapping("abc")
        public String Demo() {
    
            System.out.println("进入Demo!");
            
            //响应
            return "index.jsp";
        }
    }
    

    (5)编写jsp页面:

    <body>
        <h3>index.jsp</h3>
    </body>
    

    3.SpringMVC框架完善:

    • 静态资源的放行:
      (1)在web.xml中使用url-pattern配置:
    <servlet-mapping> 
      <servlet-name>mvc</servlet-name> 
      <url-pattern>*.do</url-pattern> 
      <url-pattern>*.action</url-pattern> 
     </servlet-mapping>
    

    (2)在springmvc中手动放行静态资源:

    <!-- 静态资源放行  mapping:指代的是网络的地址  location:指代的是放行本地的什么资源  -->
            <mvc:resources location="/imge/" mapping="/imge/**"></mvc:resources>
            <mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
            <mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
    
    结果

    二、SpringMVC进行参数接收

    • jsp页面:
    <body>
        <form action="demo4" method="post">
            <p>
                用户名:<input type="text" name="uname" />
            </p>
            <p>
                密码:<input type="password" name = "pwd"/>
            </p>
            <p>
                年龄:<input type="text" name="age" />
            </p>
            <p>
                出生日期:<input type="text" name="birth"/>
            </p>
            <p>
                爱好:
                吃:<input type="checkbox" name="hobby" value="eat"/>
                喝:<input type="checkbox" name="hobby" value="drink"/>
                玩:<input type="checkbox" name="hobby" value="play"/>
            </p>
            <p>
                <input type="submit" value="提交" />
            </p>
        </form>
      </body>
    

    1.参数获取方式一:

    /**
         * 参数获取方式一: 
         * 需要注意:我们需要的内置对象直接可以当作参数进行传递过来直接使用
         * 
         * @author zhang
         */
        @RequestMapping("demo")
        public String demo(HttpServletRequest request) {
            String uname = request.getParameter("uname");
            String pwd = request.getParameter("pwd");
            String age = request.getParameter("age");
            System.out.println(uname + "--" + pwd + "--" + age);
    
            return "success.jsp";
        }
    

    2.参数获取方式二:

    /**
         * 参数获取方式二: 
         * 注意:使用该方式进行数据接收时,保证形参的名称和前台form表单name的值必须一致
         */
        @RequestMapping("demo2")
        public String demo2(String uname, String pwd, int age) {
    
            System.out.println(uname + "--" + pwd + "--" + age);
    
            return "success.jsp";
        }
    

    3.参数获取方式三:

    /**
         * 参数接收方式三: 
         * 参数可以直接使用对象进行接收 注意:现在表单中的name属性必须和接收参数对象中的实体参数保持一致
         * 
         * @param user
         */
        @RequestMapping("demo3")
        public String demo3(User user) {
    
            System.out.println(user);
    
            return "success.jsp";
        }
    
    • User类:
        private String uname;
        private String pwd;
        private int age;
    

    4.参数获取方式四:

    /**
         * 参数接收方式四:
         * sql的Date 只含有年月日
         * util中的Date含有年月日和时分秒
         * @DateTimeFormat:接收日期格式的数据
         * @DateTimeFormat(pattren ="指定日期的格式")
         * @param hobby
         * @return
         */
        @RequestMapping("demo4")
        public String demo4(String[] hobby,@DateTimeFormat(pattern = "yyyy-mm-dd hh:mm:ss")Date birth) {
    
            System.out.println(hobby[0]+"---"+birth);
    
            return "success.jsp";
        }
    

    5.参数获取方式五:

    /**
         * springmvc/demo05/xx/123/uuu
         * 这种数据传递的方式,就是可以让数据传递变得更加的安全
         * @param name
         * @param pwd
         */
        @RequestMapping("/demo5/{name}/{pwd}")
        public String demo5(@PathVariable String name,@PathVariable String pwd){
            
            System.out.println(name+"==="+pwd);
            return "success.jsp";   
        }
    

    三、SSM框架整合

    1.导包:

    jar包

    2.创建实体类(参照数据库表的列名):

        private int userId;
        private String userName;
        private String userPass;
    

    3.编写mapper声明接口及映射文件:

    <?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.zlw.ssm.mapper.UserMapper">
    
        <select id="findAll" resultType="user">
            select * from t_user
        </select>
        
        <insert id="add" parameterType="user">
            insert into t_user(userName,userPass) values(#{userName},#{userPass})
        </insert>
    </mapper>
    

    4.创建service接口及实现类:

    package com.zlw.ssm.service.impl;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import com.zlw.ssm.mapper.UserMapper;
    import com.zlw.ssm.pojo.User;
    import com.zlw.ssm.service.UserService;
    
    @Service("userService")
    public class UserServiceImpl implements UserService{
    
        @Autowired
        private UserMapper userMapper;
        
        @Override
        public List<User> findAll() {
            return userMapper.findAll();
        }
    
        @Override
        public int add(User user) {
            return userMapper.add(user);
        }
    }
    

    5.在src下创建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:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd 
            http://www.springframework.org/schema/context
            http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/tx
            http://www.springframework.org/schema/tx/spring-tx.xsd">
    
        <!-- 扫描注解包 -->
        <context:component-scan base-package="com.zlw.ssm.service"></context:component-scan>
    
        <!-- 配置数据源 -->
        <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
            <property name="url" value="jdbc:mysql://localhost:3306/user"></property>
            <property name="username" value="root"></property>
            <property name="password" value="root"></property>
        </bean>
        <!-- 配置sqlSessionFactory,并注入数据源 -->
        <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <property name="typeAliasesPackage" value="com.zlw.ssm.pojo"></property>
        </bean>
        <!-- 配置MapperScannerConfigurer,用于扫描mapper -->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <property name="sqlSessionFactoryBeanName" value="factory"></property>
            <property name="basePackage" value="com.zlw.ssm.mapper"></property>
        </bean>
        <!-- 配置声明式事务 -->
        <bean id="transactionManager"
            class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
        <!-- 配置事务通知 -->
        <tx:advice id="Advice" transaction-manager="transactionManager">
            <tx:attributes>
                <tx:method name="findAll" propagation="SUPPORTS" />
                <tx:method name="add*" propagation="REQUIRED" />
            </tx:attributes>
        </tx:advice>
        <aop:config>
            <aop:pointcut expression="execution(* com.zlw.ssm.service.*.*(..))"
                id="point" />
            <aop:advisor advice-ref="Advice" pointcut-ref="point" />
        </aop:config>
    
    </beans>
    

    6.在web.xml中:

    配置ContextLoaderListener(解析spring配置文件)和springmvc的前端控制器;解决post提交的乱码问题。

    <?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"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        id="WebApp_ID" version="3.0">
        <display-name>x_springmvc02</display-name>
    
        <!-- 解析spring的配置文件 -->
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </context-param>
    
        <!-- 解决post乱码问题 -->
        <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>
    
        <!-- spring mvc的前端控制器,类似struts2的核心过滤器 -->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:springmvc.xml</param-value>
            </init-param>
        </servlet>
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    </web-app>
    

    7.在src下创建springmvc.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:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
          http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
          http://www.springframework.org/schema/mvc
          http://www.springframework.org/schema/mvc/spring-mvc.xsd
          http://www.springframework.org/schema/context
          http://www.springframework.org/schema/context/spring-context.xsd">
          
          <!-- 注解扫描 -->
          <context:component-scan base-package="com.zlw.ssm"></context:component-scan>
          
          <mvc:annotation-driven></mvc:annotation-driven>
    </beans>
    

    8.编写控制器Controller;

    package com.zlw.ssm.controller;
    
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import com.zlw.ssm.pojo.User;
    import com.zlw.ssm.service.UserService;
    
    @Controller
    public class UserController {
        
        @Autowired
        private UserService userService;
        //查询
        @RequestMapping("/list")
        public String list(HttpServletRequest request){
            
            List<User> list = userService.findAll();
            request.setAttribute("list", list);
            return "list.jsp";
        }
        //添加
        @RequestMapping("/add")
        public String add(User user){
            
            int n = userService.add(user);
            if (n>0) {
                return "/list";
            }
            return "error";
        }
    }
    

    9.编写jsp展现页面:

    (1)添加:

    <body>
        <h3>添加用户</h3>
        <form action="add" method="post">
            <p>
                用户名<input type="text" name="userName"/>
            </p>
            <p>
                密码:<input type="password" name="userPass"/>
            </p>
            <p>
                <input type="submit" value="注册"/>
            </p>
        </form>
        <span><a href="http://localhost:8080/x_springmvc02/list">查询所有</a></span>
      </body>
    

    (2)查询:

    <body>
      <h3 align="center">用户信息</h3>
        <table align="center" width="800px" border="1px">
      <tr>
        <th>用户ID</th>
        <th>用户名</th>
        <th>密码</th>
        <th>删除&nbsp;&nbsp;&nbsp;修改</th>
      </tr>
      <c:forEach items="${list }" var="user">
      <tr>
        <td>${user.userId }</td>
        <td>${user.userName }</td>
        <td>${user.userPass}</td>
        <td>删除&nbsp;&nbsp;&nbsp;修改</td>
      </tr>
      </c:forEach>
    </table>
    
    </body>
    

    • 实现效果:
    增加
    查询

    相关文章

      网友评论

          本文标题:SpringMVC学习day-66:SpringMVC的框架搭建

          本文链接:https://www.haomeiwen.com/subject/gkslvctx.html