Eclipse搭建SpringMVC+Spring+MyBatis框架

准备工做

资源文件

安装配置相关的环境

建立第一个项目

部分说明

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

    新建Maven项目

  • 新建项目的配置 java

    新建项目时的设置

  • 项目建好之后的结构通常是下图这样,固然能够根据本身的须要来调整。mysql

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

项目结构示意

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

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

    pom.xml文件中的项目名称


如何本身来写业务逻辑

添加本身的路径

  • 设置网页的文件路径,好比要设置访问的路径为http://localhost:8080/search/index数据库

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

<%@ 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文件中添加数据库的配置,能够直接写属性,也能够单独写个数据库的配置文件 浏览器

    spring.xml里面配置数据库

  • 访问数据库 spring-mvc

    访问数据库的设置

  • 访问数据库的接口tomcat

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框架中的一些过程


欢迎关注个人微信公众号,和我一块儿学习一块儿成长!

AntDream
相关文章
相关标签/搜索