Eclipse搭建SpringMVC+Spring+MyBatis框架

准备工作

资源文件
安装配置相关的环境
创建第一个项目

部分说明

  • 新建项目的时候要选择Maven项目,通过Maven来管理项目的依赖很方便

  • 新建项目的配置

  • 项目建好以后的结构一般是下图这样,当然可以根据自己的需要来调整。

    • "com.xxq2dream"就是包名,"search"就是项目的名称
    • controller包下是处理具体的网络请求的地方
    • model是实体
    • service是访问数据库等
    • mapper是访问数据库的具体接口,数据库语句写在resources下面的mapper文件夹下

  • 项目搭建完成以后,运行项目时,选择"run on server",这样就能直接在浏览器中访问我们的项目了。访问的地址为:http://localhost:8080/ + 项目名称。如我图中的项目名称为"search",则访问地址为:http://localhost:8080/search/

  • 特别需要注意的是,如果你按照文章开头的链接创建项目的话,项目的名称可能有问题。在pom.xml文件中的最后面有filename节点,里面是设置项目名字的地方。要注意检查下这里的名称设置,不要一股脑照抄了。


如何自己来写业务逻辑

添加自己的路径
  • 设置网页的文件路径,比如要设置访问的路径为http://localhost:8080/search/index

    • spring-mvc.xml文件里设置文件存放的路径
    • 然后是controller包下面编写处理请求的方法,如下图所示,从数据库中获取数据以后,把数据设置到request里面,然后转给index.jsp文件处理
  • 编写自己的jsp文件,如下代码所示,person就是上面添加到request里面的person

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>Insert title here</title>  
</head>  
<body>  
    <h1>say Hello</h1>  
    <h2>${say}</h2>  
<c:if test="${person!=null}">  
<h1>您好:${person.name}</h1>  
</c:if>  
  
<c:if test="${person==null}">
<h1>对不起,没有取得用户名</h1>  
</c:if>  
  
</body>  
</html>  
复制代码
添加自己的数据库处理
  • 首先是在spring.xml文件中添加数据库的配置,可以直接写属性,也可以单独写个数据库的配置文件

  • 访问数据库

  • 访问数据库的接口

public interface PersonDao {	
    Person getPersonById(int id);
}
复制代码
  • 添加业务处理逻辑接口PersonService和具体实现类PersonServiceImpl
public interface PersonService {
	public Person getPersonById(int id);
}
复制代码
  • controller里调用
@Controller
@RequestMapping("/")
public class SearchController {
	
	@Autowired
	private PersonService personService;
	
	@RequestMapping(value="/index", produces="text/html;charset=UTF-8")
	public String getPerson(HttpServletRequest request, HttpServletResponse response){  
        Person person = personService.getPersonById(0);
        request.setAttribute("person", person);
        request.setAttribute("say", "test Say Hello");
        return "index";	      
    }  

}
复制代码

以上就是初次搭建SpringMVC+Spring+MyBatis框架中的一些过程

欢迎关注我的微信公众号,和我一起学习一起成长!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值