spring-搭建web项目

spring-搭建web项目

  • 1.创建maven,web项目
  • 2.加入依赖
  • 3.拷贝ch07-spring-mybatis中的代码和配置文件
  • 4.创建一个jsp发起请求,有参数id,name,email,age。
  • 5.创建Servlet,接收请求参数,调用Service,调用dao完成注册
  • 6.创建一个jsp作为显示结果的页面

  • 1.之前做的是javase项目有main方法的,执行代码是执行main方法的,在main里面创建的容器对象。
    ApplicationContext ctx = new ClassPathXmlApplicationContext("application.xml");
  • 2.web项目是在tomcat服务器上运行的。tomcat一启动,项目是一致运行的。
  • 3.需求:web项目中容器对象只需要创建一次,把容器对象放入到全局作用域servletContext中。
    怎么实现:使用监听器,当全局作用域对象被创建时,创建容器,存入ServletContext.
    监听器作用:
    1)创建容器对象,执行
    ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
    2)把容器对象放入到ServletContext,ServletContext.setAttribute(key,ctx)
    监听器可以自己创建,也可以 使用框架中提供好的ContextLoaderListener.
    在web项目中使用spring,完成学生注册功能

1.创建maven,web项目

spring-搭建web项目_第1张图片spring-搭建web项目_第2张图片
spring-搭建web项目_第3张图片

2.加入依赖

拷贝ch07-spring-mybatis中依赖,并加入 jsp,servlet依赖



<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0modelVersion>

  <groupId>com.putaogroupId>
  <artifactId>ch11-spring-webartifactId>
  <version>1.0-SNAPSHOTversion>
  <packaging>warpackaging>

  <properties>
    <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
    <maven.compiler.source>1.8maven.compiler.source>
    <maven.compiler.target>1.8maven.compiler.target>
  properties>

  <dependencies>
    
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
      <scope>testscope>
    dependency>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>5.2.5.RELEASEversion>
    dependency>
    
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-txartifactId>
      <version>5.2.5.RELEASEversion>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>5.2.5.RELEASEversion>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatisartifactId>
      <version>3.5.1version>
    dependency>
    
    <dependency>
      <groupId>org.mybatisgroupId>
      <artifactId>mybatis-springartifactId>
      <version>1.3.1version>
    dependency>
    
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>5.1.9version>
    dependency>
    
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>druidartifactId>
      <version>1.1.12version>
    dependency>

    <dependency>
      <groupId>javax.servletgroupId>
      <artifactId>javax.servlet-apiartifactId>
      <version>3.1.0version>
      <scope>providedscope>
    dependency>

    <dependency>
      <groupId>javax.servlet.jspgroupId>
      <artifactId>jsp-apiartifactId>
      <version>2.2.1-b03version>
      <scope>providedscope>
    dependency>


    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-webartifactId>
      <version>5.2.5.RELEASEversion>
    dependency>
  dependencies>

  <build>
    
    <resources>
      <resource>
        <directory>src/main/javadirectory>
        <includes>
          <include>**/*.propertiesinclude>
          <include>**/*.xmlinclude>
        includes>
        <filtering>falsefiltering>
      resource>
    resources>
    
    <plugins>
      <plugin>
        <artifactId>maven-compiler-pluginartifactId>
        <version>3.8.1version>
        <configuration>
          <source>1.8source>
          <target>1.8target>
        configuration>
      plugin>
    plugins>
  build>
project>

3.拷贝ch07-spring-mybatis中的代码和配置文件

  • 1)实体类
package com.putao.domain;

public class Student {
    //属性名和列名一样
    private Integer id;
    private String name;
    private String email;
    private Integer age;

    public Student() {
    }

    public Student(Integer id, String name, String email, Integer age) {
        this.id = id;
        this.name = name;
        this.email = email;
        this.age = age;
    }

    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 String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Integer getAge() {
        return age;
    }

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

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", email='" + email + '\'' +
                ", age=" + age +
                '}';
    }
}

  • 2)dao类,dao.xml类
package com.putao.dao;

import com.putao.domain.Student;

import java.util.List;

public interface StudentDao {

    int insertStudent(Student student);
    List<Student> selectStudents();
}


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.putao.dao.StudentDao">
    <insert id="insertStudent" >
        insert into student values(#{id},#{name},#{email},#{age})
    insert>

    <select id="selectStudents" resultType="com.putao.domain.Student" >
        select id,name,email,age from student order by id desc
    select>
mapper>
  • 3)service类,service实现类
 package com.putao.service;

import com.putao.domain.Student;

import java.util.List;

public interface StudentService {

    int addStudent(Student student);
    List<Student> queryStudents();
}
package com.putao.service.impl;

import com.putao.dao.StudentDao;
import com.putao.domain.Student;
import com.putao.service.StudentService;

import java.util.List;

public class StudentServiceImpl implements StudentService {

    //引用类型
    private StudentDao studentDao;

    //使用set注入,赋值
    public void setStudentDao(StudentDao studentDao) {
        this.studentDao = studentDao;
    }

    @Override
    public int addStudent(Student student) {
        int nums = studentDao.insertStudent(student);
        return nums;
    }

    @Override
    public List<Student> queryStudents() {
        List<Student> students = studentDao.selectStudents();
        return students;
    }
}

  • 4)配置文件
    spring.xml

<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:property-placeholder location="classpath:jdbc.properties"/>

    <bean id="myDataSource" class="com.alibaba.druid.pool.DruidDataSource"
          init-method="init" destroy-method="close" >


        <property name="url" value="${jdbc.url}"/> 
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.passwd}" />
        <property name="maxActive" value="${jdbc.max}" />
    bean>

    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

        <property name="dataSource" ref="myDataSource" />
        
        <property name="configLocation" value="classpath:mybatis.xml" />
    bean>

    
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
    
        <property name="basePackage" value="com.putao.dao" />
    bean>

    <bean id="studentService" class="com.putao.service.impl.StudentServiceImpl">
        <property name="studentDao" ref="studentDao" />
    bean>
beans>

jdbc.properties

jdbc.url=jdbc:mysql://localhost:3306/springdb?characterEncoding=utf-8
jdbc.username=root
jdbc.passwd=root
jdbc.max=30

mybatis.xml


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>


    <typeAliases>

        <package name="com.putao.domain"/>
    typeAliases>
    
    <mappers>
    
        <package name="com.putao.dao"/>
    mappers>
configuration>

4.创建一个jsp发起请求,有参数id,name,email,age。

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


    

注册学生

id
姓名:
email:
年龄:

5.创建Servlet,接收请求参数,调用Service,调用dao完成注册

package com.putao.controller;

import com.putao.domain.Student;
import com.putao.service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RegisterServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String strId = request.getParameter("id");
        String strName = request.getParameter("name");
        String strEmail = request.getParameter("email");
        String strAge = request.getParameter("age");

        //创建spring的容器对象
//        String config= "spring.xml";
//        ApplicationContext ctx = new ClassPathXmlApplicationContext(config);
        //org.springframework.context.support.ClassPathXmlApplicationContext@e685c79, started on Tue Sep 28 17:34:38 GMT+08:00 2021
        //org.springframework.context.support.ClassPathXmlApplicationContext@56f7297a, started on Tue Sep 28 17:36:15 GMT+08:00 2021
//        System.out.println("容器对象的信息===="+ctx);
        WebApplicationContext ctx = null;
        //获取ServletContext中的容器对象,创建好的容器对象,拿来就用
//        String key = WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE;
//        Object attr = getServletContext().getAttribute(key);
//        if (attr != null){
//            ctx = (WebApplicationContext) attr;
//        }

        //使用框架中的方法,获取容器对象
        ServletContext sc = getServletContext();
        ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
        //容器对象的信息====Root WebApplicationContext, started on Wed Sep 29 09:43:09 GMT+08:00 2021
        //容器对象的信息====Root WebApplicationContext, started on Wed Sep 29 09:43:09 GMT+08:00 2021
        System.out.println("容器对象的信息===="+ctx);

        //获取service
        StudentService service = (StudentService) ctx.getBean("studentService");
        Student student = new Student();
        student.setId(Integer.parseInt(strId));
        student.setName(strName);
        student.setEmail(strEmail);
        student.setAge(Integer.valueOf(strAge));
        service.addStudent(student);

        //给一个页面
        request.getRequestDispatcher("/result.jsp").forward(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}

6.创建一个jsp作为显示结果的页面

result.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


result.jsp注册成功


你可能感兴趣的:(#,Spring,spring)