springmvc 注解简单回顾
当下注解已经成为一种趋势,spring也不能例外,臃肿的配置文件,会减慢的开发的速度。所以在开发当中好多是使用注解。当如果是自己理解的话,可以先学配置,这样有助于理解
在编写例子之间先要理解注解标签的意思
@Controller标识控制器类,应用在类的前面
@RequestMapping()控制器访问路径配置,它可以应用在类的前面,也可以是在方法的前面
@ResponseBody响应的内容,当我们需要返回的数据,不是对象,而是其他的xml文件,还有在ajax应用的时候,json数据时就要用到这个
@Resource注解自动引用需要的bean
@Valid对数据进行验证
@PathVariable路径参数引用作为参数
@InitBinder初始化数据绑定当数据绑定的时候会毁掉整个方法,在这里你这作一些预前的处理,比如可以过滤一下参数不需要验证,或者自定义数据的格式装换
在springmvc中json应用,采用了jackson进行分装,在应用的时候加入jackson包,进行配置就行了
看例子
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5"> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> <init-param> <param-name>forceEncoding</param-name> <param-value>false</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <context-param> <param-name>log4jConfigLocation</param-name> <param-value>/WEB-INF/log4j.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class> </listener> <servlet> <servlet-name>travel</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring_context.xml </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <context-param> <param-name>contextConfigLocation</param-name> <param-value> classpath:spring_context.xml </param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet-mapping> <servlet-name>travel</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <listener> <listener-class>com.common.InitListener</listener-class> </listener> <jsp-config> <taglib> <taglib-uri>http://www.ishijian.net</taglib-uri> <taglib-location>/WEB-INF/ishijian.xml</taglib-location> </taglib> </jsp-config> <servlet> <servlet-name>kindEditorUpload</servlet-name> <servlet-class>com.common.KindeditorUploadController</servlet-class> <init-param> <param-name>savePath</param-name> <param-value> e:\pic </param-value> </init-param> <init-param> <param-name>userSession</param-name> <param-value> USERSESSION </param-value> </init-param> <init-param> <param-name>maxSize</param-name> <param-value>1000000</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> <servlet-mapping> <servlet-name>kindEditorUpload</servlet-name> <url-pattern>/kindEditorUpload</url-pattern> </servlet-mapping> <servlet> <description></description> <display-name>KindeditorFileManagerController</display-name> <servlet-name>KindeditorFileManagerController</servlet-name> <servlet-class>com.common.KindeditorFileManagerController</servlet-class> <init-param> <param-name>userSession</param-name> <param-value> USERSESSION </param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>KindeditorFileManagerController</servlet-name> <url-pattern>/kindeditorFileManagerController</url-pattern> </servlet-mapping> </web-app>
controller类
package com.controller.sys; import java.util.ArrayList; import java.util.List; import java.util.UUID; import javax.annotation.Resource; import javax.validation.Valid; import org.apache.log4j.Logger; import org.springframework.expression.AccessException; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.WebRequest; import com.common.AjaxOperationObject; import com.common.ErrorCode; import com.common.TimestampEditor; import com.domain.AdminCustomerDomain; import com.services.ServicesFactory; @Controller @RequestMapping(value = "/sys/adminCustomer") public class SysAdminCustomerController{ private static final Logger logger = Logger .getLogger(SysAdminCustomerController.class); @Resource(name = "serviceFactory") ServicesFactory serviceFactory; /** * 使用ajax的方式添加数据 * * @param model * @return */ @RequestMapping(value = "/add") public @ResponseBody AjaxOperationObject addAdminCustomerDomain(@Valid AdminCustomerDomain domain, BindingResult result) { AjaxOperationObject object = null; try { object = new AjaxOperationObject(); if (result.hasErrors()) { this.logger.info("添加失败啊"); object.setErrorCode(ErrorCode.Exception); return object; } // 判断是否存在重复字段,如果重复,则返回 if (this.serviceFactory.getAdminCustomerServices().getAdminCustomerDomainCount(domain) <= 0) { domain.setCustomerid(UUID.randomUUID().toString()); this.serviceFactory.getAdminCustomerServices().insertAdminCustomerDomain(domain); object.setErrorCode(ErrorCode.NoError); } else { object.setErrorCode(ErrorCode.Repeat); object.setErrorMessage("已经存在相同的数据了"); } object.setErrorCode(ErrorCode.NoError); } catch (Exception e) { this.logger.error("添加adminCustomerDomain出错了,异常信息为:" + e.toString()); object = new AjaxOperationObject(); object.setErrorCode(ErrorCode.Exception); object.setErrorMessage(e.getMessage()); } return object; } /** * 分页查询 * * @param model * @return * @throws AccessException */ @RequestMapping(value = "/list/{page}") public String queryAdminCustomerDomainByPage(@PathVariable("page") Integer page, Model model,AdminCustomerDomain adminCustomerDomain) throws AccessException { adminCustomerDomain.setPage(page); if (adminCustomerDomain.getTotalCount() == 0) { int totalCount = this.serviceFactory.getAdminCustomerServices() .getAdminCustomerDomainCount(adminCustomerDomain); adminCustomerDomain.setTotalCount(totalCount); } List<AdminCustomerDomain> list = this.serviceFactory.getAdminCustomerServices().getAdminCustomerDomain(adminCustomerDomain); model.addAttribute("list", list); model.addAttribute("domain",adminCustomerDomain); return "sys/function/adminCustomer/queryAdminCustomer"; } /** * 删除 * @param model * @return * @throws AccessException */ @RequestMapping(value = "/del/{customerid}") public String delAdminCustomerDomain(@PathVariable("customerid") String customerid, Model model) throws AccessException { // 判断是否批量删除 // 多个用户id之间用","号相隔 List<String> list = null; if (customerid.indexOf(",") > 0) { String[] userIds = customerid.split(","); list = new ArrayList<String>(); for (int i = 0; i < userIds.length; i++) { list.add(userIds[i]); } } if (list != null && list.size() > 0) { this.serviceFactory.getAdminCustomerServices().delAdminCustomerDomain(list); } else this.serviceFactory.getAdminCustomerServices().delAdminCustomerDomain(customerid); return "redirect:/sys/adminCustomer/list/1"; } /** * 获取 * @param model * @return * @throws AccessException */ @RequestMapping(value = "/getModify/{customerid}") public String getModifyAdminCustomerDomain(@PathVariable("customerid") String customerid, Model model) throws AccessException { AdminCustomerDomain adminCustomerDomain=this.serviceFactory.getAdminCustomerServices().getAdminCustomerDomain(customerid); if(adminCustomerDomain!=null) model.addAttribute("domain", adminCustomerDomain); else model.addAttribute("domain", new AdminCustomerDomain()); return "sys/function/adminCustomer/modifyAdminCustomer"; } /** * 使用ajax的方式更新数据 * * @param model * @return */ @RequestMapping(value = "/update") public @ResponseBody AjaxOperationObject modifyAdminCustomerDomain(@Valid AdminCustomerDomain domain, BindingResult result) { AjaxOperationObject object = null; try { object = new AjaxOperationObject(); if (result.hasErrors()) { this.logger.info("更新失败啊"); object.setErrorCode(ErrorCode.Exception); return object; } this.serviceFactory.getAdminCustomerServices().updateAdminCustomerDomain(domain); object.setErrorCode(ErrorCode.NoError); } catch (Exception e) { this.logger.error("添加字段出错了,异常信息为:" + e.toString()); object = new AjaxOperationObject(); object.setErrorCode(ErrorCode.Exception); object.setErrorMessage(e.getMessage()); } return object; } @InitBinder public void initBinder(WebDataBinder binder, WebRequest request) { if (binder.getTarget() instanceof AdminCustomerDomain) { // 自定义字段类型转换的customerEditor binder.registerCustomEditor(java.sql.Timestamp.class, new TimestampEditor()); } } }
contextApplication.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" xmlns:beans="http://www.springframework.org/schema/beans" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> <!-- Scans the classpath of this application for @Components to deploy as beans --> <!-- s-扫描注解包 --> <context:component-scan base-package="com" /> <!-- e-扫描注解包 --> <!-- Configures the @Controller programming model --> <mvc:annotation-driven /> <mvc:default-servlet-handler /> <!-- Configures Handler Interceptors --> <!-- s-拦截器的引用 --> <mvc:interceptors> <mvc:interceptor> <!-- s-应用的路径 --> <mvc:mapping path="/sys/**" /> <mvc:mapping path="/page/**/**" /> <!-- e-应用的路径 --> <bean class="com.common.DoorInteceptor" /><!-- 拦截器类实现 HandlerInterceptor 或继承HandlerInterceptorAdapter --> </mvc:interceptor> </mvc:interceptors> <!-- e-拦截器的引用 --> <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the directory --> <!-- <mvc:resources mapping="/resources/**" location="/resources/" /> <mvc:resources mapping="/image/**" location="/image/" /> --> <!-- Saves a locale change using a cookie --> <bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" /> <!-- Application Message Bundle --> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basename" value="/WEB-INF/messages/messages" /> <property name="cacheSeconds" value="0" /> </bean> <!-- Resolves view names to protected .jsp resources within the /WEB-INF/views directory --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/" /> <property name="suffix" value=".jsp" /> </bean> <!-- s-json应用 --> <bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jacksonMessageConverter" /> </list> </property> </bean> <!-- e-json应用 --> <!-- s文件上传拦截--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- one of the properties available; the maximum file size in bytes --> <property name="maxUploadSize" value="10000000" /> </bean> <!-- e文件上传拦截--> <!-- s-事务拦截 --> <tx:annotation-driven transaction-manager="transactionManager"/> <!-- e-事务拦截 --> <!-- s 数据源配置--> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="com.mysql.jdbc.Driver" /> <property name="url" value="jdbc:mysql://localhost:3306/travel?characterEncoding=utf8" /> <property name="username" value="root" /> <property name="password" value="root" /> </bean> <!-- e-数据源配置--> <!-- s-事物管理器 --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource" /> </bean> <!-- e-事物管理器 --> <!-- JPA EntityManagerFactory --> <beans:import resource="spring_dao_services.xml" /> </beans>
自定数据转换
继承PropertyEditorSupport
实现setsetAsText()方法
package com.common; import java.beans.PropertyEditorSupport; import java.sql.Timestamp; import java.text.SimpleDateFormat; import org.springframework.expression.ParseException; import org.springframework.util.StringUtils; public class TimestampEditor extends PropertyEditorSupport { private String format = "yyyy-MM-dd HH:mm:ss"; // 缺省 public void setFormat(String format) { this.format = format; } public void setAsText(String text) throws IllegalArgumentException { if (text != null || StringUtils.hasText(text)) { if (text.trim().length() == 10) { text = text + " 00:00:00"; } try { setValue(new Timestamp( (new SimpleDateFormat(this.format).parse(text)) .getTime()));//给字段赋值 } catch (ParseException e) { e.printStackTrace(); } catch (java.text.ParseException e) { e.printStackTrace(); } } } } 应用自定义的类型转化 @InitBinder public void initBinder(WebDataBinder binder, WebRequest request) { if (binder.getTarget() instanceof AdminCustomerDomain) { // 自定义字段类型转换的customerEditor binder.registerCustomEditor(java.sql.Timestamp.class, new TimestampEditor()); } }
相关推荐
JudeJoo 2020-08-21
meleto 2020-08-15
小鱿鱼 2020-06-26
MicroBoy 2020-06-17
zhongliwen 2020-06-13
咻pur慢 2020-05-27
小鱿鱼 2020-05-08
neweastsun 2020-05-04
牧场SZShepherd 2020-02-21
凯哥Java 2020-02-16
neweastsun 2020-01-10
melonjj 2020-01-05
玫瑰小妖 2020-07-18
dlutbob 2020-07-04
zmysna 2020-07-04
zhongliwen 2020-06-13
qingjiuquan 2020-06-07