新建项目的时候要选择Maven项目,经过Maven来管理项目的依赖很方便 html
新建项目的配置 java
项目建好之后的结构通常是下图这样,固然能够根据本身的须要来调整。mysql
项目搭建完成之后,运行项目时,选择"run on server",这样就能直接在浏览器中访问咱们的项目了。访问的地址为:http://localhost:8080/ + 项目名称。如我图中的项目名称为"search",则访问地址为:http://localhost:8080/search/spring
特别须要注意的是,若是你按照文章开头的连接建立项目的话,项目的名称可能有问题。在pom.xml文件中的最后面有filename节点,里面是设置项目名字的地方。要注意检查下这里的名称设置,不要一股脑照抄了。 sql
设置网页的文件路径,好比要设置访问的路径为http://localhost:8080/search/index数据库
编写本身的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-mvc
访问数据库的接口tomcat
public interface PersonDao {
Person getPersonById(int id);
}
复制代码
public interface PersonService {
public Person getPersonById(int id);
}
复制代码
@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";
}
}
复制代码
欢迎关注个人微信公众号,和我一块儿学习一块儿成长!