Java Framework Springmvc Example of CRUD operations on the user table

Source: Internet
Author: User
Tags foreach arrays bind dateformat html form

Introduction to Spring MVC

Spring MVC is a follow-on product of Springframework and has been merged into Spring Web flow. The Spring framework provides a full-featured MVC module for building WEB applications. Using spring's pluggable MVC architecture, you can choose to use Spring's SPRINGMVC framework or integrate other MVC development frameworks, such as STRUTS1,STRUTS2, when using sring to start the web.

Through the policy interface, the Spring framework is highly configurable and contains a variety of view technologies, such as JavaServer Pages (JSP) technology, Velocity, Tiles, Itext, and POI. The Spring MVC Framework does not know the views used, so you will not be forced to use only JSP technology. Spring MVC separates the roles of controllers, model objects, dispatchers, and handler objects, which makes them easier to customize.

Lifecycle for overriding binding, validation, etc, is easy to integrate seamlessly with other view frames (tiles, etc.) and is easy to test with IOC.
It is a classic textbook MVC architecture, unlike struts, which are variants or not entirely based on an MVC system, and for beginners or people who want to know about MVC I think spring is the best, and it's a textbook! Second, it is a pure servlet system, just like tapestry, which is not as strong as the tapestry of struts. And the framework itself has code that looks easy to understand.



------------------------------------------------------------------Web.xml------------------------------------------------ -----------------------------------------

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

<web-app xmlns:xsi= "http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id= "Webapp_ ID "version=" 2.5 >

<display-name>SpringMVCTest3</display-name>

<welcome-file-list>

<welcome-file>index.html</welcome-file>

<welcome-file>index.htm</welcome-file>

<welcome-file>index.jsp</welcome-file>

<welcome-file>default.html</welcome-file>

<welcome-file>default.htm</welcome-file>

<welcome-file>default.jsp</welcome-file>

</welcome-file-list>



<!--configuration of Springmvc Dispatcherservlet-->

<servlet>

<servlet-name>springDispatcherServlet</servlet-name>

<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!--Configure an initialization parameter for Dispatcherservlet: The role is to configure the location and name of the SPRINGMVC configuration file-->

<init-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:spring.xml</param-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>



<servlet-mapping>

<servlet-name>springDispatcherServlet</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>

<!--configuration filter: Converts a POST request to delete, put request-->

<filter>

<filter-name>HiddenHttpMethodFilter</filter-name>

<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>HiddenHttpMethodFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

</web-app>


---------------------------------------------------Spring.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:context=" Http://www.springframework.org/schema/context "

Xmlns:mvc= "Http://www.springframework.org/schema/mvc"

xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans.xsd

Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd

Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd ">

<!--configure automatically scanned packages-->

<context:component-scan base-package= "Controller;dao;domain"/>

<!--configuration View parser-->

<bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >

<property name= "prefix" value= "/web-inf/views/"/>

<property name= "suffix" value= ". jsp"/>

</bean>



<!--will define a defaultservlethttprequesthandler in the SPRINGMVC context, he will filter the request to enter Dispatcherservlet, if the discovery is not a mapped request, The default servlet processing of the application server that requests the request to the web is handled by Dispatcherservlet if it is not a static resource request

The name of the servlet for the general Web application Server is default-->

<mvc:default-servlet-handler/>

<mvc:annotation-driven></mvc:annotation-driven>

</beans>



---------------------------------------------------------------------------------------------------Comtroller. Userhandler.java--------------------------------------------

Package controller;

@Controller Note: This class is represented as a controller

@Controller

public class Userhandler {



@Autowired It can annotate the class member variables, methods and constructors, and complete the automatic assembly work. Eliminates the Set,get method through the use of @Autowired.

@Autowired

Private Userdao Userdao;

@Autowired

Private Addressdao Addressdao;



/**

* methods that have @ModelAttribute tags are called by Springmvc before each target method executes.

* @RequestParam (value= "id", Required=false) the parameters in the form, required indicate whether you must

*/

@ModelAttribute

public void SetUser (@RequestParam (value= "id", required=false) Integer ID, map<string, object> Map) {

if (ID!= null) {

Map.put ("User", Userdao.getuser (ID));

}

}

/**

* Modify Save operation

*

* @RequestMapping ("/adduser") uses requestmapping to map the request for URL method

*/

@RequestMapping (value= "/saveuser", Method=requestmethod.put)

Public String updateuser (user user) {

Userdao.saveuser (user);

return "Redirect:/getusers";

}

/**

* Edit Modify Operation

*

* @RequestMapping ("/adduser") uses requestmapping to map the request for URL method

* @PathVariable ("id") The parameter information in the path URL

*/

@RequestMapping (value= "/edituser/{id}", Method=requestmethod.get)

Public String Edituser (@PathVariable ("id") Integer ID, map<string, object> Map) {

Map.put ("Addresses", addressdao.getaddresses ());

Map.put ("User", Userdao.getuser (ID));

return "Add";

}

/**

* Delete operation

*

* @RequestMapping ("/adduser") uses requestmapping to map the request for URL method

* @PathVariable ("id") to accept parameters

*/

@RequestMapping (value= "/deleteuser/{id}", Method=requestmethod.delete)

Public String DeleteUser (@PathVariable ("id") Integer ID) {

Userdao.deleteuser (ID);

Show action after delete

return "Redirect:/getusers";

}



/**

* Save operation

*

* @RequestMapping ("/adduser") uses requestmapping to map the request for URL method

*/

@RequestMapping (value = "/saveuser", method = Requestmethod.post)

Public String saveuser (user user) {

Userdao.saveuser (user);

Enter the display operation when the save is complete

return "Redirect:/getusers";

}



/**

* Go to add Action page

*

* @RequestMapping ("/adduser") uses requestmapping to map the request for URL method

*/

@RequestMapping (value = "/adduser", method = Requestmethod.get)

Public String AddUser (map<string, object> Map) {

Map.put ("Addresses", addressdao.getaddresses ());

Corresponding from Form object inside Struts1

Map.put ("User", new user ());

return "Add";

}



/**

* Display operation

*

* @RequestMapping ("/adduser") uses requestmapping to map the request for URL method

*/

@RequestMapping ("/getusers")

Public String getuses (map<string, object> Map) {

Map.put ("Users", Userdao.getusers ());

return "List";

}

}

-------------------------------------------DAO. Userdao.java------------------------------------------------------------

Package DAO;

@Repository Note: It is used to identify the class of the data Access layer (DAO layer) as a Spring Bean

@Repository

public class Userdao {

private static Map<integer, user> users;



@Autowired

Private Addressdao Addressdao;

static {

Users = new Hashmap<integer, user> ();

Users.put (1, New User (1, "a", one, 1, new address ("Beijing"));

Users.put (2, New User (2, "B", 0, new address (102, "Shanghai")));

Users.put (3, New User (3, "C", 1, New address ("Guangzhou"));

}

private static Integer Initid = 4;



public void Saveuser (user user) {

if (user.getid () = null) {

User.setid (initid++);

}

User.setaddress (Addressdao.getaddress (User.getaddress (). GetId ()));

Users.put (User.getid (), user);

}



Public collection<user> getusers () {

return Users.values ();

}



Public User GetUser (Integer ID) {

return Users.get (ID);

}



Public User DeleteUser (Integer ID) {

return Users.remove (ID);

}

}
-------------------------------------------------------------DAO. Addressdao.java-------------------------------------------------------------------

Package DAO;

@Repository

public class Addressdao {

private static Map<integer, address> addresses;

static {

addresses = new Hashmap<integer, address> ();

Addresses.put (A, new address ("Beijign"));

Addresses.put (102, new address (102, "Shanghai"));

Addresses.put (The new address ("Guangzhou");

}



Public collection<address> getaddresses () {

return Addresses.values ();

}



Public Address getaddress (Integer ID) {

return Addresses.get (ID);

}

}
-----------------------------------------Domain------------------------------------------------

Package domain;

public class Address {

Private Integer ID;

private String name;

}

----------------------------

Package domain;

public class User {

Private Integer ID;

private String name;

Private Integer age;

Private Integer sex;

private address address;

}

--------------------------------------------views/jsp------------------------------------------

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "

pageencoding= "UTF-8"%>

<%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >



<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">

<title>insert title here</title>


<body>

<c:if test= "${empty requestscope.users}" >

No Employee information

</c:if>

<c:if test= "${!empty requestscope.users}" >

<table border= "1" >

<tr>

<th>id</th>

<th>name</th>

<th>age</th>

<th>sex</th>

<th>address</th>

<th>edit</th>

<th>delete</th>

</tr>

<c:foreach items= "${requestscope.users}" var= "User" >

<tr>

<td>${user.id}</td>

<td>${user.name}</td>

<td>${user.age}</td>

<td>${user.sex==0? " Female ":" Male "}</td>

<td>${user.address.name}</td>

<td><a href= "Edituser/${user.id}" >edit</a></td>

<td>

<form action= "Deleteuser/${user.id}" method= "POST" >

<input type= "hidden" name= "_method" value= "DELETE"/>

<input type= "Submit" value= "Delete"/>

</form></td>

</tr>

</c:forEach>

</table>

</c:if>

<br>

<br>

<a href= "AddUser" >addUser</a>

</body>

---------------------------------------------------------------------------

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "

pageencoding= "UTF-8"%>

<% @page import= "Java.util.HashMap"%>

<%@ taglib prefix= "form" uri= "Http://www.springframework.org/tags/form"%>

<%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >



<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 ">

<title>insert title here</title>


<body>

<form:form action= "${pagecontext.request.contextpath}/saveuser" method= "POST" modelattribute= "User" >

<c:if test= "${user.name==null}" >

Name:<form:input path= "Name"/><br>

</c:if>

<c:if test= "${user.name!=null}" >

<form:hidden path= "id"/>

<input type= "hidden" name= "_method" value= "put" >

</c:if>

Age:<form:input path= "Age"/><br>

<%

hashmap<string, string> sex = new hashmap<string, string> ();

Sex.put ("0", "female");

Sex.put ("1", "male");

Request.setattribute ("Sex", sex);

%>

Sex:<form:radiobuttons path= "Sex" items= "${sex}"/><br>

Address:<form:select path= "address.id" items= "${addresses}" itemlabel= "name" itemvalue= "id"/><br>

<input type= "Submit" value= "Submit" >

</form:form>

</body>

============================================SPRINGMVC Form Label =================================================== ============

<!--springform form tags: form:input, Form:password, Form:hidden, Form:textarea: text, password, hidden, corresponding HTML form TextArea label-->

<!--Form:radiobutton: The Radio box is a label that is selected when the corresponding property and value value for that form bean are equal. -->

<!--form:radiobuttons: a Radio box component label for constructing multiple radio boxes

-items: Can be a list, String "" or map

-itemvalue: Specifies the value of the radio. Can be a property value of a bean in the collection

-itemlabel: Specifies the label value of the radio

-delimiter: Multiple Radio boxes can specify the delimiter by delimiter-->



<!--form:checkbox: check box component. User constructs a single check box

Form:checkboxs: User constructs multiple check boxes. Use the same form:radiobuttons label

Form:select: Used to construct a Drop-down box component that is used in the same way as the Form:radiobuttons label

Form:option: Dropdown box option component label. Use is equivalent to Form:radiobuttons label

From:errors: Displays the error for the form component or data checksum-->


a CRUD controller based on spring MVC

Based on the SPRINGMVC, the controller of the entity simply inherits the method of modifying and deleting the class immediately.
Like what:
@Controller
@RequestMapping ("/role")
Rolecontroller extends Crudcontroller<role>
As long as simple inheritance can be managed through/role/save.do,/role/remove.do, and other ways to manage entities, if there are more complex business operations, you can rewrite the parent class callback functions, similar to the aspect-oriented programming.

Package cn.jcwx.core.web;

Import java.io.IOException;
Import Java.text.SimpleDateFormat;
Import Java.util.Arrays;
Import Java.util.Date;
Import java.util.List;
Import Java.util.Map;

Import Javax.annotation.Resource;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Import Org.slf4j.Logger;
Import Org.slf4j.LoggerFactory;
Import Org.springframework.beans.propertyeditors.CustomDateEditor;
Import Org.springframework.beans.propertyeditors.CustomNumberEditor;
Import org.springframework.validation.BindException;
Import Org.springframework.validation.ObjectError;
Import Org.springframework.validation.Validator;
Import Org.springframework.web.bind.ServletRequestDataBinder;
Import Org.springframework.web.bind.WebDataBinder;
Import Org.springframework.web.bind.annotation.InitBinder;
Import org.springframework.web.bind.annotation.RequestMapping;
Import Org.springframework.web.multipart.MultipartFile;
Import Org.springframework.web.multipart.support.ByteArrayMultipartFileEditor;
Import Org.springframework.web.servlet.ModelAndView;
Import Org.springframework.web.util.WebUtils;

Import Cn.jcwx.core.service.HibernateDao;
Import Cn.jcwx.core.service.support.ScrollResult;
Import Cn.jcwx.core.tag.table.TableTag;
Import Cn.jcwx.core.utils.BeanUtils;
Import Cn.jcwx.core.utils.StringUtils;

Import Com.google.gson.Gson;
Import Com.google.gson.GsonBuilder;
Import com.google.gson.JsonElement;

/**
* Controller <br/> for CRUD functionality
* Suggest subclasses override callback functions <br/><br/>
*
* Save or update entity: Save.do <br/>
* Delete entity: Remove.do <br/>
* Query Individual entity information: Show.do <br/>
*
* @author EwinLive@gmail.com
* @date 2011-2-23
* @version 1.0
*/
Public abstract class crudcontroller<t>{
@Resource
Private Validator Validator;

Protected static final Logger Logger = Loggerfactory.getlogger (Crudcontroller.class);

protected Gson Gson = new Gsonbuilder (). Setdateformat ("Yyyy-mm-dd"). Create ();

protected String className;

protected String entityname;

protected T entity;

protected String ListView = null;

protected String FormView = null;

public static final String Successview = "/share/common/success.jsp";

Public Crudcontroller () {
ClassName = Beanutils.getsuperclassgenrictype (GetClass ()). GetName ();
EntityName = Stringutils.substringafterlast (ClassName, ".");
EntityName = entityname.substring (0, 1). toLowerCase () + entityname.substring (1, Entityname.length ());
ListView = "list.jsp";
FormView = "form.jsp";
}

/**
* Get an instance of the Entity service class
* @return
*/
Protected abstract hibernatedao<t, integer> getentityservice ();

@InitBinder
public void Initbinder (Webdatabinder binder) {
SimpleDateFormat DateFormat = new SimpleDateFormat ("Yyyy-mm-dd");
Binder.registercustomeditor (Date.class, New Customdateeditor (DateFormat, true));
Binder.registercustomeditor (Integer.class, New Customnumbereditor (Integer.class, true));
Binder.registercustomeditor (Double.class, New Customnumbereditor (Double.class, true));
Binder.registercustomeditor (Multipartfile.class, New Bytearraymultipartfileeditor ());
}

/**
* Paging query based on the default request parameters.
* Callback function: Beforedolist (...), afterdolist (...)
* @param request the current HttpServletRequest
* @param filtermap filtration conditions, such as: Filtermap.put ("Id_eq_i", 12). can be null
*
* @param sortmap sorting conditions, such as: Sortmap.put ("id", "desc");    ASC is positive, DESC is in reverse order. can be null
* @return scrollresult<t>
*/
@RequestMapping (value = "List.do")
Public Modelandview dolist (httpservletrequest request, httpservletresponse response) {
Modelandview Mav = new Modelandview (ListView);

Extract filter conditions and sorting criteria that the client may transmit
map<string, object> filtermap = webutils.getparametersstartingwith (Request, "Search_");
map<string, object> sortmap = webutils.getparametersstartingwith (Request, "Sort_");

Integer no, size;
String psize = (string) request.getparameter ("P_size");
String pNo = (string) request.getparameter ("P_no");
if (Stringutils.isempty (PNo)) {
no = 1;
} else {
No = Integer.parseint (PNo);
}

if (Stringutils.isempty (psize)) {
size = Tabletag.def_rows_min;
} else {
Size = Integer.parseint (psize);
}

Beforelist (Request, Filtermap, sortmap);

scrollresult<t> result = (scrollresult<t>) getentityservice (). Findscrollresult (No, size, Filtermap, SORTMAP);
Mav.addobject (EntityName + "s", Result.getresultlist ());
Mav.addobject ("Totalrows", Result.gettotal ());

Afterlist (Request, response, MAV);
return MAV;
}

/**
* Paging Query (list.do) callback function that is invoked before the query is executed. You can continue to add filter conditions and sorting criteria.
* @param request
* @param filtermap
* @param sortmap
*/
protected void Beforelist (HttpServletRequest request, map<string, object> Filtermap, map<string, object> Sortmap) {};

/**
* Paging Query (list.do) callback function, which is called before the view is returned. You can continue to add return information.
* @param request
* @param response
* @param MAV
*/
protected void Afterlist (HttpServletRequest request, httpservletresponse response, Modelandview Mav) {};

/**
* The form interface directed to the new entity <br/>
* Callback function: OnCreate (...)
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping (value = "Create.do")
Public Modelandview docreate (httpservletrequest request, httpservletresponse response) throws Exception {
Modelandview Mav = new Modelandview (FormView);
OnCreate (Request,response, MAV);
return MAV;
}

/**
* New entity's form interface (Create.do) callback function. This method is called before returning the view, and you can continue to add the return information.
* @param request
* @param response
* @param MAV
*/
protected void OnCreate (HttpServletRequest request, httpservletresponse response, Modelandview Mav) {};

/**
* Form Editing interface
*/
@RequestMapping (value = "Edit.do")
Public Modelandview edit (httpservletrequest request, httpservletresponse response) throws Exception {
Modelandview Mav = new Modelandview (FormView);
String id = request.getparameter ("id");
if (Stringutils.isnotempty (ID)) {
entity = Getentityservice (). Get (integer.valueof (ID));
Mav.addobject (EntityName, entity);
}

OnEdit (Entity, MAV, request);
return MAV;
}

protected void OnEdit (T entity, Modelandview Mav, HttpServletRequest request) {};

/**
* Save Entities <br/>
* Callback function: Beforedosave (...), Afterdosave (...)
* @param request
* @param response
* @return
* @throws Exception
*/
@SuppressWarnings ("Unchecked")
@RequestMapping (value = "Save.do")
Public Modelandview Dosave (httpservletrequest request, httpservletresponse response) throws Exception {
Modelandview Mav = new Modelandview (Successview);

String id = request.getparameter ("id");
if (Stringutils.isempty (ID)) {
entity = (T) beanutils.getsuperclassgenrictype (GetClass ()). Newinstance ();
} else {
entity = Getentityservice (). Get (integer.valueof (ID));
}

Boolean check = beforebindrequestentity (Request, entity, MAV);
if (!check)
return MAV;

Beforebindrequestentity (Request, entity, MAV);
Bindexception errors = bindrequestentity (request, entity);

BeforeSave (Request, Entity, errors, MAV);

if (Errors.haserrors ()) {
Logger.error (Errors.getmessage ());
Mav.addobject ("msg", Getmessagefromerrors (Errors));
Mav.addobject ("state", "failed");
Mav.addobject ("url", "list.do");
return MAV;
}

Getentityservice (). Save (entity);
Mav.addobject ("msg", "Save success!");
Mav.addobject ("state", "OK");
Aftersave (Request, Response, MAV, entity);

return MAV;
}

/**
* Bind objects from request and verify them.
*/
Protected bindexception bindrequestentity (HttpServletRequest request, T entity) throws Exception {
Servletrequestdatabinder Binder = new Servletrequestdatabinder (entity);
Initbinder (binder);
Binder.bind (Request);
Bindexception errors = new Bindexception (Binder.getbindingresult ());
Validator.validate (entity, errors);
return errors;
}

/**
* Save the Entity (Save.do) callback function, which is invoked before the execution entity is bound to the request parameter.
* Note: Since entity may be a managed object, modifications made to entity will be reflected in the database.
* Therefore, it is necessary in this method to conduct early data validation in order to avoid accidents.
* @param request
* @param entity
* @param MAV
* @return whether to pass the checksum
*/
Protected Boolean beforebindrequestentity (HttpServletRequest request, T entity, Modelandview Mav) {return false;};

/**
* Save the Entity (Save.do) callback function, which is invoked before the save execution. Data validation is possible.
* @param request HttpServletRequest
* @param entity entity objects
* @param errors Bindexception can add error messages
* @param mav Modelandview
*/
protected void BeforeSave (HttpServletRequest request, T entity, bindexception errors, Modelandview mav) {};

/**
* Saves the Entity (Save.do) callback function, which is invoked before returning the view. You can continue to add return information.
* @param request
* @param response
* @param MAV
*/
protected void Aftersave (HttpServletRequest request, httpservletresponse response, Modelandview Mav, T entity) {};

@RequestMapping (value = "Remove.do")
Public Modelandview Doremove (httpservletrequest request, httpservletresponse response) throws Exception {
Modelandview Mav = new Modelandview (Successview);
String id = request.getparameter ("id");

t = Getentityservice (). Load (integer.valueof (ID));

Beforeremove (Request, response, T);
Getentityservice (). Remove (t);
Afterremove (Request, Response, MAV, New StringBuilder (). Append ("successfully deleted")
. Append ("1"). Append (EntityName)
. Append ("ID:"). Append (ID). toString ());

return MAV;
}

/**
* Bulk Delete Entity <br/>
* Callback function: Beforedoremove (...), Afterdoremove (...)
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping (value = "Batchremove.do")
Public Modelandview Dobatchremove (httpservletrequest request, httpservletresponse response) throws Exception {
Modelandview Mav = new Modelandview (Successview);
string[] ids = request.getparametervalues ("itemlist");
String entity = request.getparameter ("EntityName");
StringBuilder SB = null;
int success = 0;
T t = null;
if (IDs!= null) {
for (String id:ids) {
t = Getentityservice (). Get (integer.valueof (ID));
Beforeremove (Request, response, T);
Getentityservice (). Remove (t);
success++;
}
SB = new StringBuilder (). Append ("delete successfully")
. Append (Success). Append ("a"). Append (Entity)
. Append ("IDs:"). Append (arrays.tostring (IDs));
Mav.addobject ("msg", sb.tostring ());
} else {
Mav.addobject ("msg", "not selected" + entity);
}

Afterremove (Request, Response, MAV, sb.tostring ());
return MAV;
}

/**
* Deletes the entity (Remove.do) callback function, which is invoked before the save execution. Data validation is possible.
* @param request
* @param response
* @param entity entity objects
*/
protected void Beforeremove (HttpServletRequest request, httpservletresponse response, T entity) {};

/**
* Deletes the entity (Remove.do) callback function, which is invoked before returning the view. You can continue to add return information.
* @param request
* @param response
* @param MAV
*/
protected void Afterremove (HttpServletRequest request, httpservletresponse response, Modelandview Mav, String msg) {};

/**
* Query Entity Information <br/>
* Callback function: OnShow (...)
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping (value = "Show.do")
Public Modelandview doshow (httpservletrequest request, httpservletresponse response) throws Exception {
Modelandview Mav = new Modelandview (FormView);

entity = Getentityservice (). Get (Integer.valueof (Request.getparameter ("id"));
Mav.addobject (EntityName, entity);

OnShow (Request, Response, entity, MAV);
return MAV;
}

/**
* Query Entity information (show.do) callback function, which is invoked before returning the view. You can continue to add return information.
* @param request
* @param response
* @param entity entity objects
* @param MAV
*/
protected void OnShow (HttpServletRequest request, httpservletresponse response, T entity, Modelandview Mav) {};

@SuppressWarnings ("Unchecked")
Private String getmessagefromerrors (bindexception errors) {
StringBuilder sb = new StringBuilder ();
Sb.append ("error message:");
List<objecterror> list= errors.getallerrors ();
for (Objecterror error:list) {
Sb.append (Error.getdefaultmessage ()). Append (";");
}
return sb.tostring ();
}

/**
* Write JSON data to the client
* @param response
* @param element Jsonelement subclasses can be Jsonarray or jsonobject
*/
protected void Writejsondate (httpservletresponse response, jsonelement Element) {
try {
Response.setcharacterencoding ("UTF-8");
Response.getwriter (). Print (element.tostring ());
catch (IOException e) {
E.printstacktrace ();
}
}
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.