SpringMVC

1、使用默认的构造方法创建bean对象

(1)导入依赖

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.3.4</version>
</dependency>

(2)创建userService

package com.tjetc.service;

public class UserService {
    public UserService() {
        System.out.println("UserService.UserService([])方法");
    }
}

(3)配置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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="userService" class="com.tjetc.service.UserService"></bean>
</beans>

(4)测试

package com.tjetc.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test1 {
    public static void main(String[] args) {
        //创建容器对象
        ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
    }
}

2、静态工厂方法创建bean对象

(1)创建工厂类和一个静态方法

package com.tjetc.factory;

import com.tjetc.service.UserService;

/**
 * 工厂类里写工厂方法
 */
public class UserServiceFactory {
    public static UserService createUserService(){
        System.out.println("UserServiceFactory.createUserService([])方法");
        //创建userService对象并返回
        return new UserService();
    }
}

(2)applicationContext.xml配置一个bean节点

<bean id="userServiceFactory" class="com.tjetc.factory.UserServiceFactory" factory-method="createUserService"></bean>

3、实例工厂方法创建bean对象

(1)写一个工厂类

package com.tjetc.factory;

import com.tjetc.service.UserService;

/**
 * 工厂类里写工厂方法
 */
public class UserServiceFactory {
    public  UserService createUserService(){
        System.out.println("UserServiceFactory.createUserService([])方法");
        //创建userService对象并返回
        return new UserService();
    }
}

(2)配置两个bean节点

<bean id="userServiceFactory" class="com.tjetc.factory.UserServiceFactory"></bean>
<bean id="userService" factory-bean="userServiceFactory" factory-method="createUserService"></bean>

4、BeanNameUrlHandlerMapping-Spring MVC 配置式开发

(1) pom.xml

  <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.4</version>
        </dependency>

(2) web.xml

   <!--配置dispatcherServlet-->
    <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>
        <!--tomcat启动时就加载-->
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

(3)新建类MyController

package com.tjetc.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyController extends AbstractController {
    protected ModelAndView handleRequestInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        ModelAndView mv = new ModelAndView();
        //设置视图
        mv.setViewName("index.jsp");
        mv.addObject("msg","毁灭吧");
        return mv;
    }
}

(4)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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="/my" class="com.tjetc.controller.MyController"></bean>
</beans>

(5)index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <base href="${pageContext.request.contextPath}/"/>
</head>
<body>
    ${msg}
</body>
</html>

5、SpringMVC请求参数

(1)
导入依赖

 <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.4</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>



    </dependencies>

(2)springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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
">
<context:component-scan base-package="com.tjetc"/>
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

(3)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <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>
    <!--配置前端控制器-->
    <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>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

(4)

HelloController


package com.tjetc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {
/*    @RequestMapping("/hello")
    public String hello(Model model){
        System.out.println("HelloController.hello([])方法");
        model.addAttribute("msg","Hello SpringMVC");
        return "index";
    } */
    @RequestMapping(value = "/hello")
    public String hello(@RequestParam(value = "un",required = true,defaultValue = "hyc") String username, Model model){
        System.out.println("HelloController.hello([])方法");
        System.out.println("username = " + username);
        model.addAttribute("msg",username);
        return "index";
    }

    @RequestMapping("/hello2")
    public String hello2(Model model){
        model.addAttribute("张三");
        return "msg";
    }


    @RequestMapping("/hello3")
    public String hello3(ModelMap modelMap){
        modelMap.addAttribute("msg","张三");
        return "msg";
    }


    @RequestMapping("/hello4")
    public ModelAndView hello4(){
        ModelAndView mv = new ModelAndView();
        mv.addObject("msg","张三");
        mv.setViewName("msg");
        return mv;
    }




}

(5) index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <base href="${pageContext.request.contextPath}/"/>
</head>
<body>
${msg}
</body>
</html>

(6) UseController

package com.tjetc.controller;

import com.tjetc.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/user")
public class UserController {
    @RequestMapping("/login")
    public String login(String username, String password, Model model){
        System.out.println("username = " + username);
        System.out.println("password = " + password);
        return "欢迎";
    }


    @RequestMapping("/login2")
    public String login2(User user){
        System.out.println("user = " + user);
        return "欢迎";
    }




    @RequestMapping("/del/{id}")
    public String del(@PathVariable("id")int a){
        System.out.println("a = " + a);
        return "welcome";
    }


    @RequestMapping("/login3/{username}/{password}")
    public String login3(@PathVariable("username") String username,@PathVariable("password") String password){
        System.out.println("username = " + username);
        System.out.println("password = " + password);
        return "welcome";
    }

    @RequestMapping("/my1")
    public String my1(){
        return "redirect:/user/del/6";
    }

    @RequestMapping("/my2")
    public String my2(){
        return "forward:/welcome.jsp";
    }
}

(7)login.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <base href="${pageContext.request.contextPath}/"/>
</head>
<body>
    <form action="/user/login3" method="post">
        用户名: <input type="text" name="username" > <br>
        密码: <input type="password" name="password" > <br>
        <input type="submit" value="提交"> <br>
    </form>
</body>
</html>

(8)StudentController

package com.tjetc.controller;

import com.tjetc.domain.Student;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/student")
public class StudentController {
    @RequestMapping("/add")
    public String add(Student student, Model model){
        System.out.println("student = " + student);
        //相当于request.setAttribute
        model.addAttribute("student",student);
        return "update";
    }
}

6、练习

题目:使用SpringMVC+Mybatis+jsp完成emp员工表在页面上的增删改查

(1)

<dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.4</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>5.3.4</version>
        </dependency>

        <dependency>
            <groupId>jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>


        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.23</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.2.0</version>
        </dependency>



        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.6</version>
        </dependency>


    </dependencies>

    <build>

        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>
    </build>

(2) web.xml

 <!--编码过滤器-->
    <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>
    <!--前端控制器-->
    <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>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

(3)springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans
        xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:mvc="http://www.springframework.org/schema/mvc"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.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
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
">
    <context:component-scan base-package="com.tjetc"/>
    <mvc:annotation-driven/>
    <mvc:default-servlet-handler/>
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    <context:property-placeholder location="classpath:db.properties"/>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:mybatis.xml"/>
    </bean>

    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSession"/>
        <property name="basePackage" value="com.tjetc.mapper"/>
    </bean>

    <aop:config>
        <aop:pointcut id="mycut" expression="execution(* com.tjetc.service..*.*(..))"></aop:pointcut>
        <aop:advisor advice-ref="txAdvice" pointcut-ref="mycut"></aop:advisor>
    </aop:config>

    <tx:advice id="txAdvice" transaction-manager="txManager">
        <tx:attributes>
            <tx:method name="add*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="del*" propagation="REQUIRED"/>
            <tx:method name="*" read-only="true"/>
        </tx:attributes>
    </tx:advice>
</beans>

(4)db.properties

jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql:///springmvc0714?serverTimezone=GMT%2B8
jdbc.username=root
jdbc.password=123456

(5)mybatis.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.tjetc.domain"/>
    </typeAliases>

    <plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
    </plugins>
</configuration>

(6)Emp

package com.tjetc.domain;

import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

public class Emp {
    private Integer id;
    private String name;
    private Integer age;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birthday;
    private String hobbies;
    private String sex;

    public Emp() {
    }

    public Emp(String name, Integer age, Date birthday, String hobbies, String sex) {
        this.name = name;
        this.age = age;
        this.birthday = birthday;
        this.hobbies = hobbies;
        this.sex = sex;
    }

    public Emp(Integer id, String name, Integer age, Date birthday, String hobbies, String sex) {
        this.id = id;
        this.name = name;
        this.age = age;
        this.birthday = birthday;
        this.hobbies = hobbies;
        this.sex = sex;
    }

    @Override
    public String toString() {
        return "Emp{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", birthday=" + birthday +
                ", hobbies='" + hobbies + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    public String getHobbies() {
        return hobbies;
    }

    public void setHobbies(String hobbies) {
        this.hobbies = hobbies;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }


}

(7)EmpMapper

package com.tjetc.mapper;

import com.tjetc.domain.Emp;

import java.util.List;

public interface EmpMapper {
    void add(Emp emp);

    void update(Emp emp);

    void del(int id);

    Emp findById(int id);

    List<Emp> listByName(String name);
}

(8)EmpMapper.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.tjetc.mapper.EmpMapper">
    <!--添加员工-->
    <insert id="add">
        insert into emp(name,age,birthday,hobbies,sex) values(#{name},#{age},#{birthday},#{hobbies},#{sex})
    </insert>

    <!--修改员工-->
    <update id="update">
        update emp
        <set>
            <if test="name!=null">
                name = #{name},
            </if>

            <if test="age!=null">
                age = #{age},
            </if>

            <if test="birthday!=null">
                birthday = #{birthday},
            </if>

            <if test="hobbies!=null">
                hobbies = #{hobbies},
            </if>

            <if test="sex!=null">
                sex = #{sex}
            </if>

        </set>
        where id = #{id}
    </update>


    <!--删除员工-->
    <delete id="del">
        delete from emp where id = #{id}
    </delete>

    <!--根据id查找员工-->
    <select id="findById" resultType="com.tjetc.domain.Emp">
        select * from emp where id =#{id}
    </select>

    <!--员工列表(名字模糊查询)-->
    <select id="listByName" resultType="com.tjetc.domain.Emp">
        select * from emp where name like concat('%',#{name},'%')
    </select>
</mapper>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

香鱼嫩虾

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值