您的位置:首页 > 编程语言 > Java开发

spring-mvc restful风格的实战例子

2018-01-22 19:50 495 查看
设计的架构层次图



pom.xml 中的配置文件

<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion>
<groupId>SpringMvcLession</groupId>
<artifactId>SpringMvcLession</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name/>
<description />

<dependencies>
<!-- 导入springmvc核心配置 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<!-- 导入jdbc的jar包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<!-- 导入mysql的jar包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>

<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.12</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>

<!-- 导入javaee的jar包 -->
<dependency>
<groupId>org.apache.openejb</groupId>
<artifactId>javaee-api</artifactId>
<version>5.0-1</version>
<scope>provided</scope>
</dependency>

<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-api</artifactId>
<version>1.2_04</version>
<scope>provided</scope>
</dependency>

<!-- 导入jstl的jar包 -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
<!-- provided 默认的不会自动加载到当前项目的bin目录 -->
<!-- compile 会自动加载到当前项目的bin目录 -->
<scope>compile</scope>

</dependency>

<!-- 导入jsp的jar包 -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.1</version>
<scope>compile</scope>
</dependency>

<dependency>
<groupId>javax.faces</groupId>
<artifactId>jsf-impl</artifactId>
<version>1.2_04</version>
<scope>provided</scope>
</dependency>
</dependencies>

<build>
<sourceDirectory>${basedir}/src</sourceDirectory>
<outputDirectory>${basedir}/WebRoot/WEB-INF/classes</outputDirectory>
<resources>
<resource>
<directory>${basedir}/src</directory>
<excludes>
<exclude>**/*.java</exclude>
</excludes>
</resource>
</resources>

<plugins>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<configuration>
<webappDirectory>${basedir}/WebRoot</webappDirectory>
<warSourceDirectory>${basedir}/WebRoot</warSourceDirectory>
</configuration>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.5</source>
<target>1.5</target>
</configuration>
</plugin>
</plugins>
</build>

</project>

web.xml的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<!-- 解决乱码的配置 -->
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<!-- 设置request 字符集 -->
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<!-- 设置response 字符集 -->
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 请求method支持 put和delete必须添加 过滤器 -->
<filter>
<filter-name>myFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>myFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- springmvc配置 -->
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

mvc-servlet.xml 中的配置
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd ">

<context:component-scan base-package="cn"></context:component-scan> <!-- 扫描cn所有的类 -->
<context:property-placeholder location="classpath:/cn/et/web/jdbc.properties"/> <!-- 扫描jdbc.properties -->

<!-- springmvc 配置拦截 / 所有资源都被拦截 图片无法展示 将除控制层以外的资源交回给servlet处理-->
<mvc:default-servlet-handler/>

<!-- 将springmvc注解的action交给springmvc处理 -->
<mvc:annotation-driven></mvc:annotation-driven>

<!-- 启用文件上传 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 限制上传文件大小 5M -->
<property name="maxUploadSize" value="5242880"></property>
</bean>

<!--连接数据库四要素 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <!-- 创建一个连接数据库的工具 -->
<property name="url" value="${url}" ></property> <!-- 添加里面的属性 -->
<property name="username" value="${userid}" ></property>
<property name="password" value="${password}" ></property>
<property name="driverClassName" value="${driverClass}" ></property>
</bean>

<!-- 事务管理器 不再使用jdbc的commit和rollback 必须由事务管理器提供 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>

<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>

<!-- 定义通知 通知的代码 spring已经实现 -->
<tx:advice id="myAdvise" transaction-manager="transactionManager">

<!-- 设置拦截的方法 name="*" 表示除了下面的三个开头的方法其他的都拦截 read-only="true 表示只读 不进行操作"-->
<tx:attributes>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="add*"/>
<tx:method name="delete*"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>

<!-- 定义一个切点 -->
<aop:config>
<aop:pointcut expression="execution(* cn.*..*.service.*.*(..))" id="myPoint"/>
<aop:advisor advice-ref="myAdvise" pointcut-ref="myPoint"/>
</aop:config>
</beans>

前段界面
<%@ 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">
<html>
<head>
<title>无线点餐平台</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<!-- 页面标题 -->
<div id="TitleArea">
<div id="TitleArea_Head"></div>
<div id="TitleArea_Title">
<div id="TitleArea_Title_Content">
<img border="0" width="13" height="13" src="${pageContext.request.contextPath}/detail/style/images/title_arrow.gif"/> 菜品列表
</div>
</div>
<div id="TitleArea_End"></div>
</div>
<div id="QueryArea">
<form action="${pageContext.request.contextPath}/showFood" method="get">
<input type="text" name="fname" title="请输入菜品名称">
<input type="submit" value="搜索">
<button><a href="${pageContext.request.contextPath}/detail/saveFood.jsp">添加</a></button>
</form>

</div>
<!-- 主内容区域(数据列表或表单显示) -->
<div id="MainArea">
<table width="100%" border="1" cellspacing="0" cellpadding="10">
<!-- 表头-->
<thead>
<tr align="center" valign="middle" id="TableTitle">
<td>菜编号  </td>
<td>菜名</td>
<td>价格</td>
<td>操作</td>
</tr>
</thead>
<!--显示数据列表 -->
<tbody id="TableData">
<c:forEach var="idtemp" items="${requestScope.foodList.data}">
<tr class="TableDetail1">
<td width="10%" align="left" >
<img style='width:200px; height:100px;' src="${pageContext.request.contextPath}//images//${pageScope.idtemp.imagepath}">

</td>
<td align="center"><a href="${pageContext.request.contextPath}/particulars/${pageScope.idtemp.foodid}">${pageScope.idtemp.foodname}</a></td>
<td align="center">${pageScope.idtemp.price}</td>
<td>
<button>
<a href="${pageContext.request.contextPath}/detail/updateFood.jsp?id=${pageScope.idtemp.foodid}&foodname=${pageScope.idtemp.foodname}&price=${pageScope.idtemp.price}&intro=${pageScope.idtemp.intro}&imagepath=${pageScope.idtemp.imagepath}">更新</a>
</button>
<p> </p>
<form action="${pageContext.request.contextPath}/deleteFood/${pageScope.idtemp.foodid}" method="post">
<input type="hidden" name="_method" value="delete"/>
<input type="submit" value="删除">
</form>
</td>
</tr>

dd77
</c:forEach>
<tr>
<td colspan="4">
<a href="${pageContext.request.contextPath}/showFood?curPage=1">首页</a>
<a href="${pageContext.request.contextPath}/showFood?curPage=${requestScope.foodList.prePage}">上一页</a>
<c:forEach var="i" begin="1" end="${requestScope.foodList.totalPage}" step="1">
<a href="${pageContext.request.contextPath}/showFood?curPage=${pageScope.i}">${pageScope.i}</a>
</c:forEach>
<a href="${pageContext.request.contextPath}/showFood?curPage=${requestScope.foodList.nextPage}">下一页</a>
<a href="${pageContext.request.contextPath}/showFood?curPage=${requestScope.foodList.totalPage}">尾页</a>
</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>


jdbc配置
url=jdbc:mysql://localhost:3306/test
driverClass=com.mysql.jdbc.Driver
userid=root
password=88888888
工具类 用来分页的

package cn.et.web.util;

import java.util.List;

public class PageTools {
/**
* 构造参数
* @param curPage 页面传入的当前页
* @param totalCount 数据库查询的总记录数
* @param pageCount 每页显示的条数
*/
public PageTools(Integer curPage,Integer totalCount,Integer pageCount){
this.curPage =curPage;
this.totalCount = totalCount;
this.pageCount = pageCount==null?this.pageCount:pageCount;
this.prePage= (curPage==1?1:curPage-1);
this.totalPage = totalCount%this.pageCount==0?totalCount/this.pageCount:totalCount/this.pageCount+1;
this.nextPage = (curPage==totalPage)?totalPage:(curPage+1);
this.startIndex =(curPage-1)*this.pageCount+1;
this.endIndex = curPage*this.pageCount;
}
/**
* 当前页(由页面传递)
*/
private Integer curPage;

/**
* 每页显示的数量
*/
private Integer pageCount=5;

/**
* 上一页
* prePage=curPage==1?1:curPage-1
* 举例
* 2 -- 1
* 3 -- 2
* 4 -- 3
*/
private Integer prePage;

/**
* 下一页
* 举例:
* nextPage=curPage==totalPage?totalPage:(curPage+1)
* curPage totalPage nextPage
* 1 3 2
*/
private Integer nextPage;

/**
* 总页数
* pageCount(每页显示的条数) total(总记录数) totalpage
* 10 20 3
*/
private Integer totalPage;

/**
* 总记录数(从数据库查询)
*/
private Integer totalCount;

/**
* 查询最终查询的数据
*/
private List data;

/**
* 开始索引
* curPage pageCount start-end
* 1 10 1-10
* 2 10 11-20
* (curPage-1)*pageCount+1 curPage*pageCount
*/
private Integer startIndex;

/**
* 结束索引
* @return
*/
private Integer endIndex;

public Integer getCurPage() {
return curPage;
}

public void setCurPage(Integer curPage) {
this.curPage = curPage;
}

public Integer getPageCount() {
return pageCount;
}

public void setPageCount(Integer pageCount) {
this.pageCount = pageCount;
}

public Integer getPrePage() {
return prePage;
}

public void setPrePage(Integer prePage) {
this.prePage = prePage;
}

public Integer getNextPage() {
return nextPage;
}

public void setNextPage(Integer nextPage) {
this.nextPage = nextPage;
}

public Integer getTotalPage() {
return totalPage;
}

public void setTotalPage(Integer totalPage) {
this.totalPage = totalPage;
}

public Integer getTotalCount() {
return totalCount;
}

public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}

public List getData() {
return data;
}

public void setData(List data) {
this.data = data;
}

public Integer getStartIndex() {
return startIndex;
}

public void setStartIndex(Integer startIndex) {
this.startIndex = startIndex;
}

public Integer getEndIndex() {
return endIndex;
}

public void setEndIndex(Integer endIndex) {
this.endIndex = endIndex;
}

public static void main(String[] args) {
int curPage=3;
int total =26;
int pageCount =5;
PageTools pt =new PageTools(curPage, total, pageCount);
System.out.println(pt.getNextPage());
System.out.println(pt.getPrePage());
System.out.println(pt.getTotalPage());
System.out.println(pt.getStartIndex());
System.out.println(pt.getEndIndex());
}

}


service层的接口
package cn.et.web.service;

import java.util.List;
import java.util.Map;

import cn.et.web.util.PageTools;

public interface FoodService {
public Integer getTableListCount(String name);

public void addFood(String fname, String price, String intro,String imagepath);

public void deleteFood(String id);

public void updateFood(String id,String fname, String price, String intro,String imagepath);

public PageTools getqueryAll(String fname,int curPage);

public List<Map<String, Object>> foodId(String id);

}


service的实现类
package cn.et.web.service.impl;

import java.util.List;
import java.util.Map;

import javax.print.attribute.standard.MediaSize.NA;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.et.web.dao.FoodDao;
import cn.et.web.service.FoodService;
import cn.et.web.util.PageTools;
@Service
public class FoodServiceImpl implements FoodService {

@Autowired
private FoodDao dao;

public Integer getTableListCount(String name) {
if (name==null) {
name="";
}
return dao.getTableListCount(name);
}

public void addFood(String fname, String price, String intro,String imagepath) {
dao.addFood(fname, price, intro, imagepath);

}

public void deleteFood(String id) {
dao.deleteFood(id);
}

public void updateFood(String id, String fname, String price, String intro,String imagepath) {
dao.updateFood(id, fname, price, intro, imagepath);
}

public PageTools getqueryAll(String fname,int curPage) {
if (fname==null) {
fname="";
}
Integer totalCount = dao.getTableListCount(fname);
PageTools pt =new PageTools(curPage, totalCount, 2);
List<Map<String, Object>> tableListPager =dao.getqueryAll(fname, pt.getStartIndex()-1, pt.getPageCount());
pt.setData(tableListPager);
return pt;
}

public List<Map<String, Object>> foodId(String id) {

return dao.foodId(id);
}
}



dao层的接口
package cn.et.web.dao;

import java.util.List;
import java.util.Map;
public interface FoodDao {
/**
* 获取总行数
*/
public Integer getTableListCount(String name);

/**
* 增加
*/
public void addFood(String fname, String price, String intro,String imagepath);

/**
* 删除
*/
public void deleteFood(String id);

/**
* 修改
*/
public void updateFood(String id,String fname, String price, String intro,String imagepath);

/**
* 查看
*/
public List<Map<String, Object>> getqueryAll(String fname,Integer startIndex,Integer length);

/**
* 根据id获取当前的详细信息
*/
public List<Map<String, Object>> foodId(String id);

}


dao层的实现类
package cn.et.web.dao.impl;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import cn.et.web.dao.FoodDao;

@Repository
public class FoodDaoImpl implements FoodDao {

@Autowired
private JdbcTemplate jdbc;

/**
* 总行数
*/
public Integer getTableListCount(String name) {
String sql = "select count(*) as cr from food where foodname like '%"+name+"%'";
List<Map<String, Object>> result= jdbc.queryForList(sql);
return Integer.valueOf(result.get(0).get("cr").toString());
}

/**
* 增加
*/
public void addFood(String fname, String price, String intro,String imagepath) {
String sql ="insert into food(foodname,price,intro,imagepath) values('"+fname+"','"+price+"','"+intro+"','"+imagepath+"')";
jdbc.execute(sql);
}

/**
* 删除
*/
public void deleteFood(String id) {
String sql ="delete from food where foodid="+id;
jdbc.execute(sql);

}

/**
* 修改
*/
public void updateFood(String id,String fname, String price, String intro,String imagepath) {
String sql ="update food set foodname='"+fname+"',price='"+price+"',intro='"+intro+"',imagepath='"+imagepath+"' where foodid="+id;
jdbc.execute(sql);
}

/**
* 查看
*/
public List<Map<String, Object>> getqueryAll(String fname,Integer startIndex,Integer length) {
String sql ="select * from food where foodname like '%"+fname+"%' limit "+startIndex+","+length;
return jdbc.queryForList(sql);
}

/**
* 通过id获取当前的数据
*/
public List<Map<String, Object>> foodId(String id) {
String sql ="select * from food where foodid="+id;
return jdbc.queryForList(sql);
}
}


controller层
package cn.et.web.controller;

import java.io.File;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import com.sun.org.apache.xpath.internal.operations.Mod;

import cn.et.web.service.FoodService;
import cn.et.web.util.PageTools;

@Controller
public class FoodController {

@Autowired
FoodService service;

/**
* 下载
*/
@RequestMapping(value="/download",method=RequestMethod.GET)
public ResponseEntity<byte[]> updateFood(String imagePath) throws Exception{
String absPath ="D:\\软件\\myeclipse\\springmvc_project\\WebRoot\\images\\"+imagePath;
String fileName =imagePath;
//需要下载的目标文件
File file =new File(absPath);
//设置响应头
HttpHeaders hh =new HttpHeaders();
//设置下载的文件的名称
hh.setContentDispositionFormData("attachment", URLEncoder.encode(fileName,"UTF-8"));
//读取目标文件为二进制数组
byte[] fileByte =FileCopyUtils.copyToByteArray(file);
//构建ResponseEntity对象
ResponseEntity<byte[]> re =new ResponseEntity<byte[]>(fileByte,hh,HttpStatus.CREATED);
return re;
}

/**
* 添加
*/
@RequestMapping(value="/addFood",method=RequestMethod.POST)
public String addFood(MultipartFile imageUrl,String foodName,String price,String introduce,Model model) throws Exception{
String fileName =imageUrl.getOriginalFilename();
String path ="D:\\软件\\myeclipse\\springmvc_project\\WebRoot\\images\\"+fileName;
imageUrl.transferTo(new File(path));
service.addFood(foodName, price, introduce, fileName);
return queryFood(foodName,1, model);
}

/**
* 删除
*/
@RequestMapping(value="/deleteFood/{id}",method=RequestMethod.DELETE)
public String deleteFood(@PathVariable String id , Model model) throws Exception{
service.deleteFood(id);
return queryFood(null,1, model);
}

/**
* 修改
*/
@RequestMapping(value="/updateFood/{id}",method=RequestMethod.POST)
public String updateFood(@PathVariable String id,String foodname,String price,String intro,MultipartFile imagepath, Model model) throws Exception{
String fileName =imagepath.getOriginalFilename();
String path ="D:\\软件\\myeclipse\\springmvc_project\\WebRoot\\images\\"+fileName;
imagepath.transferTo(new File(path));

service.updateFood(id, foodname, price, intro, fileName);
return queryFood(foodname,1, model);
}

/**
*查看所有信息
*/
@RequestMapping(value="/showFood",method=RequestMethod.GET)
public String queryFood(String fname,Integer curPage,Model model){
if (curPage==null) {
curPage=1;
}
PageTools getqueryAll = service.getqueryAll(fname, curPage);
model.addAttribute("foodList", getqueryAll);
return "/detail/foodList.jsp";
}

/**
*查看所有信息
*/
@RequestMapping(value="/particulars/{id}",method=RequestMethod.GET)
public String foodId(@PathVariable String id,Model model){
List<Map<String, Object>> foodid = service.foodId(id);
System.out.println(foodid);
model.addAttribute("foodid", foodid);
return "/detail/particulars.jsp";
}
}



运行的效果如下图

界面



添加



修改



以上就是springmvc的实例rest风格
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: