论坛首页 Java企业应用论坛

一个RESTful的简单例子,来自自己的EWeb4J框架

浏览 8161 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2011-07-16   最后修改:2011-07-16
呼,写了个用户指南,只完成了MVC部分。好累的说。
不过,也总算框架开发基本完成了。
至少,终于让它RESTful了。
下载地址:http://code.google.com/p/eweb4j/downloads/list

给出一个简单的Controller吧,囧
package test.controller;

import java.io.PrintWriter;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import test.po.Pet;
import test.service.PetService;

import com.cfuture08.eweb4j.component.DivPageComp;
import com.cfuture08.eweb4j.ioc.IOC;
import com.cfuture08.eweb4j.mvc.annotation.Controller;
import com.cfuture08.eweb4j.mvc.annotation.Param;
import com.cfuture08.eweb4j.mvc.annotation.RequestMapping;
import com.cfuture08.eweb4j.mvc.annotation.RequestMethod;
import com.cfuture08.eweb4j.mvc.annotation.Result;
import com.cfuture08.eweb4j.mvc.annotation.Singleton;
import com.cfuture08.eweb4j.mvc.annotation.ValField;
import com.cfuture08.eweb4j.mvc.annotation.ValParam;
import com.cfuture08.eweb4j.mvc.annotation.Validator;
import com.cfuture08.util.JsonConverter;
@Singleton
@Controller
@RequestMapping("pets")
public class PetController {
	private final PetService service = IOC.getBean("PetService");

	@RequestMapping("/")
	@Result(location = { "showAll.jsp" }, name = { "success" }, type = { "" }, index = { "0" })
	public String getAll(HttpServletRequest request) {
		List<Pet> pets = this.service.getAll();
		request.setAttribute("pets", pets);
		return "success";
	}

	@RequestMapping("/分页")
	@Result(location = { "showAll.jsp" }, name = { "success" }, type = { "" }, index = { "0" })
	public String getList(HttpServletRequest request, @Param("p") int pageNum,
			@Param("n") int numPerPage) {
		List<Pet> pets = this.service.getPage(pageNum, numPerPage);
		if (pets != null && pets.size() > 0) {
			DivPageComp dpc = new DivPageComp(pageNum, numPerPage,
					this.service.countAll(), 4);
			dpc.setLocation(String.format("分页?p={pageNum}&n=%s", numPerPage));
			dpc.doWork();
			request.setAttribute("pets", pets);
			request.setAttribute("dpc", dpc);
		}
		return "success";
	}

	@RequestMapping("/{id}")
	@Result(location = { "seeDetail.jsp" }, name = { "success" }, type = { "" }, index = { "0" })
	public String get(HttpServletRequest request, PrintWriter out,
			@Param("id") Integer id, @Param("ext") String ext) {
		Pet pet = this.service.getOne(id);
		if ("json".equalsIgnoreCase(ext)) {
			out.print("<pre>" + JsonConverter.convert(pet) + "</pre>");
			return "ajax";
		}

		request.setAttribute("pet", pet);
		return "success";
	}

	@RequestMapping("/{id}")
	@RequestMethod("DELETE")
	@Result(location = { "分页?p=1&n=10" }, name = { "success" }, type = { "redirect" }, index = { "0" })
	public String deleteOne(PrintWriter out, @Param("id") Integer id) {
		String error = this.service.delete(new Integer[] { id });
		if (error == null) {
			return "success";
		} else {
			out.print(String.format(
					"<script>alert('%s');history.go(-1)</script>", error));
			return "ajax";
		}

	}

	@RequestMapping("/{id}")
	@RequestMethod("PUT")
	@Result(location = { "分页?p=1&n=10" }, name = { "success" }, type = { "redirect" }, index = { "0" })
	@Validator(name = { "requried", "int", "int", "length" }, clazz = {}, index = {}, showErrorType = {})
	@ValField(name = { "id", "id", "age", "type" }, index = { "0", "1", "2",
			"3" }, message = { "请选择要修改的记录", "id必须是数字", "年龄必须是数字", "类型长度不能超过10" })
	@ValParam(index = { "3" }, name = { "maxLength" }, value = { "10" })
	public String put(PrintWriter out, Pet aPet) {
		String error = this.service.update(aPet);
		if (error == null) {
			return "success";
		} else {
			out.print(String.format(
					"<script>alert('%s');history.go(-1)</script>", error));
		}
		return "ajax";
	}

	@RequestMapping("/{id}/编辑")
	@Result(location = { "../edit.jsp" }, name = { "success" }, type = { "" }, index = { "0" })
	public String edit(HttpServletRequest request, @Param("id") Integer id) {
		Pet tPet = this.service.getOne(id);
		request.setAttribute("pet", tPet);
		return "success";
	}

	@RequestMapping("/添加")
	@Result(index = { "0" }, location = { "add.jsp" }, name = { "success" }, type = { "" })
	public String addPet() {
		return "success";
	}

	@RequestMapping("/")
	@RequestMethod("POST")
	@Result(location = { "分页?p=1&n=10" }, name = { "success" }, type = { "redirect" }, index = { "0" })
	@Validator(clazz = {}, index = { "0" }, name = { "int", "length" }, showErrorType = {
			"", "" })
	@ValField(index = { "0", "1" }, message = { "年龄必须是数字", "类型长度不能超过10" }, name = {
			"age", "type" })
	@ValParam(index = { "1" }, name = { "maxLength" }, value = { "10" })
	public String post(PrintWriter out, Pet aPet) {
		String error = this.service.create(aPet);
		if (error == null) {
			return "success";
		} else {
			out.print(String.format(
					"<script>alert('%s');history.go(-1)</script>", error));
		}
		return "ajax";
	}

}


PetService
package test.service;

import test.dao.PetDAO;
import test.po.Pet;

import com.cfuture08.eweb4j.orm.dao.base.BaseDAOImpl;

public class PetService extends BaseDAOImpl<Pet>{
	private PetDAO petDAO;
	public PetService() {
		super(Pet.class);
	}
	public void setPetDAO(PetDAO aPetDAO){
		this.petDAO = aPetDAO;
	}
}

对于我将Service去继承一个BaseDAO,大家有木有什么看法?因为我觉得我的这个程序木有什么业务逻辑,仅有的几个数据验证就让controller帮我做了,数据库访问逻辑让dao帮我做了,又没有什么事务性,所以干脆就让servcice继承一个BaseDAO来应对一些纯粹的数据库访问吧。其实很多的系统都这样吧,service层仅仅是简单的调用了DAO的方法而已。
PetDAO
package test.dao;

public interface PetDAO {
}


PetDAOImpl
package test.dao;

public class PetDAOImpl implements PetDAO {
}



Pet
package test.po;

/**
 * just a po
 * 
 * @author weiwei
 * 
 */
public class Pet {
	private Integer id = 0;
	private String name;
	private String type;
	private int age;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getType() {
		return type;
	}

	public void setType(String type) {
		this.type = type;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

	public String toString() {
		return "[Pet id:" + this.id + ",name:" + this.name + ",age:" + this.age
				+ ",type:" + this.type + "]";
	}
}



EWeb4J框架配置文件
ioc配置
<?xml version="1.0" encoding="UTF-8"?>

<beans>
  <bean id="PetService" scope="singleton" class="test.service.PetService" xmlBean="com.cfuture08.eweb4j.ioc.config.bean.IOCConfigBean">
    <inject ref="PetDAO" name="petDAO" type="" value="" xmlBean="com.cfuture08.eweb4j.ioc.config.bean.Injection"/>
  </bean>
  <bean id="PetDAO" scope="singleton" class="test.dao.PetDAOImpl" xmlBean="com.cfuture08.eweb4j.ioc.config.bean.IOCConfigBean">
    <inject ref="" name="" type="" value="" xmlBean="com.cfuture08.eweb4j.ioc.config.bean.Injection"/>
  </bean>
</beans>


dbInfo配置
<?xml version="1.0" encoding="UTF-8"?>

<beans>
  <bean name="myDBInfo" xmlBean="com.cfuture08.eweb4j.orm.dao.config.bean.DBInfoConfigBean">
    <dataBaseType>MYSQL</dataBaseType>
    <jndiName></jndiName>
    <jdbcUtil></jdbcUtil>
    <driverClass>com.mysql.jdbc.Driver</driverClass>
    <jdbcUrl>jdbc:mysql://localhost:3306/test</jdbcUrl>
    <user>root</user>
    <password>root</password>
    <initialPoolSize>3</initialPoolSize>
    <maxPoolSize>50</maxPoolSize>
    <minPoolSize>1</minPoolSize>
    <acquireIncrement>3</acquireIncrement>
    <idleConnectionTestPeriod>60</idleConnectionTestPeriod>
    <maxIdleTime>25000</maxIdleTime>
    <autoCommitOnClose>true</autoCommitOnClose>
    <preferredTestQuery></preferredTestQuery>
    <testConnectionOnCheckout>false</testConnectionOnCheckout>
    <testConnectionOnCheckin>false</testConnectionOnCheckin>
    <acquireRetryAttempts>30</acquireRetryAttempts>
    <acquireRetryDelay>1000</acquireRetryDelay>
    <breakAfterAcquireFailure>false</breakAfterAcquireFailure>
  </bean>
</beans>


eweb4j-satrt-config.xml
<?xml version="1.0" encoding="UTF-8"?>

<beans>
  <bean xmlBean="com.cfuture08.eweb4j.config.bean.ConfigBean">
    <debug>0</debug>
    <ioc xmlBean="com.cfuture08.eweb4j.config.bean.ConfigIOC">
      <open>1</open>
      <debug>true</debug>
      <logFile>ioc.log</logFile>
      <logMaxSize>5</logMaxSize>
      <iocXmlFiles xmlBean="com.cfuture08.eweb4j.config.bean.IOCXmlFiles">
        <path>eweb4j-ioc-config.xml</path>
      </iocXmlFiles>
    </ioc>
    <orm xmlBean="com.cfuture08.eweb4j.config.bean.ConfigORM">
      <open>true</open>
      <debug>true</debug>
      <logFile>orm.log</logFile>
      <logMaxSize>5</logMaxSize>
      <ormXmlFiles xmlBean="com.cfuture08.eweb4j.config.bean.ORMXmlFiles">
        <path></path>
      </ormXmlFiles>
      <dbInfoXmlFiles xmlBean="com.cfuture08.eweb4j.config.bean.DBInfoXmlFiles">
        <path>eweb4j-dbinfo-config.xml</path>
      </dbInfoXmlFiles>
    </orm>
    <mvc xmlBean="com.cfuture08.eweb4j.config.bean.ConfigMVC">
      <open>true</open>
      <debug>true</debug>
      <logFile>mvc.log</logFile>
      <logMaxSize>5</logMaxSize>
      <scanActionPackage>test.controller</scanActionPackage>
      <actionXmlFiles xmlBean="com.cfuture08.eweb4j.config.bean.ActionXmlFile">
        <path></path>
      </actionXmlFiles>
      <interXmlFiles xmlBean="com.cfuture08.eweb4j.config.bean.InterXmlFile">
        <path></path>
      </interXmlFiles>
    </mvc>
  </bean>
</beans>



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">
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <filter>
	<filter-name>EWeb4JFilter</filter-name>
	<filter-class>com.cfuture08.eweb4j.mvc.EWeb4JFilter</filter-class>
  </filter>
  <filter-mapping>
	<filter-name>EWeb4JFilter</filter-name>
	<url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics