学习springboot过程中的心得

springboot与servlet两者封装对象的方式

springboot的Controller层当中

1
2
3
4
5
6
@PostMapping("/add")
public String addSuccess(Employee employee){
System.out.println("add-->"+employee);
employeeDao.addNewEmployee(employee);
return "redirect:/emp";
}

addSuccess方法中使用Employee对象作为入参,在前端html代码的form表单中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<form th:action="@{/add}" method="post">
<div class="form-group">
<label class="col-sm-2 control-label">名字</label>
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="请输入名字" name="name">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">邮箱</label>
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="请输入邮箱" name="email">
</div>
</div>
<div class="form-group">
<label>部门</label>
<!-- 因为department是一个对象,传参的时候不能传一个对象,故先传对象的id值,然后后端接受了id值后,通过id值来查询department,并将查询到的department赋值给employee -->
<select class="form-control" name="department.id">
<option th:text="${department.getDepartmentName()}" th:each="department:${departments}" th:value="${department.getId()}"></option>
</select>
</div>
<div class="form-group">
<label class="col-sm-2 control-label">日期</label>
<div class="col-sm-10">
<input type="text" class="form-control" placeholder="请输入日期" name="birth">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">添加</button>
</div>
</div>
</form>


每一个input标签的name属性都与对象的属性名相对应,通过form表单提交后,后端将所有的name属性封装程一个employee对象作为入参

Servlet中

同样,通过前端jsp代码的from表单向后端传值
在servlet代码中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
@WebServlet( value="/LoginServlet")
public class LoginServlet extends HttpServlet {
public LoginServlet() {

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");

String name=request.getParameter("uname");
String password=request.getParameter("upwd");

Login login=new Login(name,password);
int count=LoginDao.Login(login);
if(count>0) {
response.sendRedirect("welcome.jsp");
}else {
response.sendRedirect("login.jsp");
}
}
}

通过request.getParameter()方法接受前端传来的值,并赋值给对应的变量,然后将手动将变量封装成Login对象

三层架构的组成

  1. 表示层(USL:user show layer ;视图层)
     -前台:对应于mvc中的view,用于和用户交互、界面的显示
     -后台:servlet controller  用于控制跳转
    
  2. 业务逻辑层(BLL:business logic layer ; service层)
     --组装数据访问层,逻辑性的操作(增删改查,进行操作之前先查找
     --用于接收表示层的请求 调用
    
  3. 数据访问层(DAL:Data access Layer ; dao层)
     --直接访问数据库的操作,原子性的操作 
    

get请求和post请求

  1. get请求包括<form method="get">,地址栏,超链接<a href=""></a>
  2. get请求在地址栏显示请求信息(但是地址栏能够容纳的信息有限4-5kb,如果请求数据存在大文件,图片,会报错)
  3. 文件上传操作必须是post

请求转发和重定向redirect的区别

  1. 图标格式的区分
    类型 | 请求转发 | 重定向
    :—— | :——: | :——:
    地址栏是否改变 | 不变 | 改变
    是否保留第一次请求的数据 | 保留 | 不保留
    请求的次数 | 1 | 2
  2. 举例说明
    请求转发:
    张三(客户端) -> 服务窗口A -> 服务窗口A去找服务窗口B
    重定向:
    张三(客户端) -> 服务窗口A -> 叫张三(客户端)自己去找服务窗口B
    张三(客户端)-> 服务窗口B
  3. springboot中
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    @GetMapping("/delete/{id}")
    public String delete(@PathVariable("id") Integer id){
    employeeDao.deleteEmployeeById(id);
    return "redirect:/emp";
    }
    @RequestMapping("/emp")
    public String list(Model model){
    Collection<Employee> employees = employeeDao.getAllEmployee();

    model.addAttribute("employees",employees);

    return "employee/list";
    }
    delete函数中重定向到了list函数,实际上是通过list的model参数传值给前端。也就是说,也可以将list函数中的相关代码写入delete函数,然后在delete函数 return "employee/list"

springboot中Dao层与springMybatis

  1. springboot中Dao层中(省略了数据库,直接在Java代码中创建数据库)
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    public Collection<Employee> getAllEmployee(){
    return Employees.values();
    }

    //获取一个员工的信息
    public Employee getEmployeeById(Integer id){
    return Employees.get(id);
    }

    //删除一个员工的信息
    public void deleteEmployeeById(Integer id){
    Employees.remove(id);
    }

    //修改一个员工的信息
    public void updateEmployee(Integer id,Employee employee){
    Department department = employee.getDepartment();
    employee.setDepartment(departmentDao.getDepartmentById(department.getId()));
    Employees.replace(id,employee);
    }
  2. springMybatis中的xxmapper.java文件
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    public interface StudentMapper {
    Person queryPersonById(int id);
    List<Person> queryAllPerson();
    void updatePersonById(Person person);
    void addPerson(Person person);

    studentBusiness queryStudentByBusiness(int sno);

    student queryStudentByOO(int sno);
    // studentClass queryStudentByO2M(int classid);
    student queryStudentByO2M(int sno);
    }

    只不过xxmapper.java中有专门的xxmapper.xml配置文件来写底层的增删改查语句

Mybatis与springbootJDBC与JDBC与SpringMybatis

Mybatis中

  1. conf.xml
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    <environments default="development">
    <!-- 开发环境(自己的计算机) -->
    <environment id="development">
    <transactionManager type="JDBC"/>
    <dataSource type="POOLED">
    <property name="driver" value="com.mysql.jdbc.Driver"/>
    <property name="url" value="jdbc:mysql://localhost:3306/football?serverTimezone=UTC"/>
    <property name="username" value="root"/>
    <property name="password" value="MyNewPass"/>
    </dataSource>
    </environment>
    </environments>
    在environment下配置dataSource
  2. test.java
    省略了pojo、mapper包
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    public static void addStudent() throws IOException {
    //加载mybatis配置文件conf.xml(为了访问数据库)
    Reader reader = Resources.getResourceAsReader("conf.xml");
    SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);

    SqlSession session = sessionFactory.openSession();
    StudentMapper studentMapper = session.getMapper(StudentMapper.class);
    Person person=new Person(2,"yuqun",123);
    studentMapper.addPerson(person);

    session.commit();
    session.close();
    System.out.println("成功");
    }

    public static void queryPersonById() throws IOException {
    Reader reader = Resources.getResourceAsReader("conf.xml");
    SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(reader);

    SqlSession session = sessionFactory.openSession();
    StudentMapper studentMapper = session.getMapper(StudentMapper.class);

    //MyBatis底层通过动态代理将Object对象变成一个Person对象
    Person person = studentMapper.queryPersonById(1);
    session.commit();
    session.close();
    System.out.println(person);
    }

    SpringMybatis

  3. db.properties
    1
    2
    3
    4
    driver=com.mysql.jdbc.Driver
    url=jdbc:mysql://localhost:3306/football?serverTimezone=UTC
    username=root
    password=MyNewPass
  4. ApplicationContext.xml
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    <!-- 加载db.properties文件 需要特定的类才能加载 preferencesPlaceHolderConfigurer-->
    <bean id="config" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">
    <property name="locations">
    <!-- 数组类型可以用array来赋值 -->
    <!-- 配置了 配置文件的位置之后 就可以用 EL表达式来赋值 -->
    <array>
    <value>classpath:db.properties</value>
    </array>
    </property>
    </bean>

    <!-- 替代mybatis配置文件conf.xml 配置数据库信息-->
    <!-- 配置数据库相关 BasicDataSource类会自动提交事务 jdbc需要手动提交-->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="driverClassName" value="${driver}"></property>
    <property name="url" value="${url}"></property>
    <property name="username" value="${username}"></property>
    <property name="password" value="${password}"></property>
    <property name="maxActive" value="10"></property>
    <property name="maxIdle" value="6"></property>
    </bean>

    <!-- 在springioc容器中 创建mybatis的核心类 sqlsessionfactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
    <property name="dataSource" ref="dataSource"></property>
    <!-- 加载mybatis配置文件 将applicationContext.xml配置文件设置为主配置文件
    <property name="configLocation" value="classpath:conf.xml"></property>
    -->
    <!-- 加载mapper.xml文件 -->
    <property name="mapperLocations" value="org/pvtwen/mapper/*.xml"></property>
    </bean>

JDBC

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public static void main(String[] args) throws Exception{
// TODO Auto-generated method stub
final String URL="jdbc:mysql://localhost:3306/football?serverTimezone=UTC";
final String USERNAME="root";
final String PWD="MyNewPass";
ResultSet set=null;
//a.导入驱动 加载具体的驱动类
//通过反射直接加载 class文件
Class.forName("com.mysql.jdbc.Driver");
//b.与数据库建立连接
Connection connection = DriverManager.getConnection(URL, USERNAME, PWD);
//c.发送sql,执行增删改
Statement stmt=connection.createStatement();
//String sql="insert into game values('1','2','2022-03-23')";
String sql="select * from game order by Tno1";

//int res=stmt.executeUpdate(sql);
set=stmt.executeQuery(sql);

while(set.next()) {
String team1=set.getString(1);
String team2=set.getString(2);
Date date=set.getDate(3);
System.out.println(team1+"----"+team2+"-----"+date);
}
//if(res>0) {
//System.out.println("插入成功!");
//}
if(stmt!=null) {
stmt.close();
}
if(connection!=null) {
connection.close();
}
}