spring mvc 解决乱码3.0MVC注脚怎么解决

在spring中,注脚是否优于xml配置 - XML/SOAP当前位置:& &&&在spring中,注脚是否优于xml配置在spring中,注脚是否优于xml配置&&网友分享于:&&浏览:2次在spring中,注解是否优于xml配置
Are annotations better than XML for configuring Spring?The introduction of annotation-based configurations raised the question of whether this approach is 'better' than XML. The short answer is it depends. The long answer is that each approach has its pros and cons, and usually it is up to the developer to decide which strategy suits her better. Due to the way they are defined, annotations provide a lot of context in their declaration, leading to shorterand more concise configuration. However, XML excels at wiring up components without touching their source code or recompiling them. Some developers prefer having the wiring close to the source while others argue that annotated classes are no longer POJOs and, furthermore, that the configuration becomes decentralized and harder to control. No matter the choice, Spring can accommodate both styles and even mix them together. It's worth pointing out that through its JavaConfig option, Spring allows annotations to be used in a non-invasive way, without touching the target components source code and that in terms of tooling,all configuration styles are supported by the SpringSource Tool Suite.
12345678910
12345678910
12345678910 上一篇:下一篇:文章评论相关解决方案 12345678910 Copyright & &&版权所有基于注脚的SpringMVC整合JPA_imooo软件程序bug解决方案
基于注脚的SpringMVC整合JPA
基于注解的SpringMVC整合JPA
实体类Departmentpackage com.sj.import java.util.Simport javax.persistence.CascadeTimport javax.persistence.Cimport javax.persistence.Eimport javax.persistence.GeneratedVimport javax.persistence.GenerationTimport javax.persistence.Id;import javax.persistence.OneToMimport javax.persistence.T@Entity@Table(name="department",catalog="sj")public class Department {&&& &&&&&& private S&&& private Set&Employee&&&& @Id&&& @Column(name="id")&&& @GeneratedValue(strategy=GenerationType.AUTO)&&& public int getId() {&&&&&&&&&& }&&& public void setId(int id) {&&&&&&& this.id =&&& }&&& @Column(name="name")&&& public String getName() {&&&&&&&&&& }&&& public void setName(String name) {&&&&&&& this.name =&&& }&&& @OneToMany(mappedBy="department",cascade=CascadeType.ALL)&&& public Set&Employee& getSets() {&&&&&&&&&& }&&& public void setSets(Set&Employee& sets) {&&&&&&& this.sets =&&& }&&& }Employeepackage com.sj.import java.io.Simport javax.persistence.CascadeTimport javax.persistence.Cimport javax.persistence.Eimport javax.persistence.GeneratedVimport javax.persistence.GenerationTimport javax.persistence.Id;import javax.persistence.JoinCimport javax.persistence.ManyToOimport javax.persistence.T@SuppressWarnings("serial")@Entity@Table(name="employee",catalog="sj")public class Employee implements Serializable{&&& &&&&&& private S&&& private D&&& @Id&&& @GeneratedValue(strategy=GenerationType.AUTO)&&& @Column(name="id")&&& public int getId() {&&&&&&&&&& }&&& public void setId(int id) {&&&&&&& this.id =&&& }&&& @Column(name="name")&&& public String getName() {&&&&&&&&&& }&&& public void setName(String name) {&&&&&&& this.name =&&& }&&& @ManyToOne(cascade=CascadeType.ALL)&&& @JoinColumn(name="deptid")&&& public Department getDepartment() {&&&&&&&&&& }&&& public void setDepartment(Department department) {&&&&&&& this.department =&&& }&&& }BaseDAOpackage com.sj.import java.util.Lpublic interface BaseDAO&T& {&&& &&& List&T& listAll();&&& Object findById(Class&T& c,int id);&&& boolean save(Object object);&&& boolean update(Object object);&&& boolean delete(Object object);&&& }&&& BaseDAOImplpackage com.sj.import java.util.Limport javax.persistence.EntityMimport javax.persistence.PersistenceCimport javax.persistence.Qimport org.@Component("baseDAO")public class BaseDAOImpl&T& implements BaseDAO&T& {&&& @PersistenceContext(unitName="sjPU")&&& private EntityManager entityM&&& &&& &&& public boolean delete(Object object) {&&&&&&& try {&&&&&&&&&&& entityManager.remove(object);&&&&&&&&&&&&&&&&&& } catch (Exception e) {&&&&&&&&&&& e.printStackTrace();&&&&&&& }&&&&&&&&&& }&&& public Object findById(Class&T& c,int id) {&&&&&&& try {&&&&&&&&&&& return entityManager.find(c, id);&&&&&&& } catch (Exception e) {&&&&&&&&&&& e.printStackTrace();&&&&&&& }&&&&&&&&&& }&&& public boolean save(Object object) {&&&&&&& try {&&&&&&&&&&& entityManager.persist(object);&&&&&&&&&&&&&&&&&& } catch (Exception e) {&&&&&&&&&&& e.printStackTrace();&&&&&&& }&&&&&&&&&& }&&& public boolean update(Object object) {&&&&&&& try {&&&&&&&&&&& entityManager.merge(object);&&&&&&&&&&&&&&&&&& } catch (Exception e) {&&&&&&&&&&& e.printStackTrace();&&&&&&& }&&&&&&&&&& }&&& @SuppressWarnings("unchecked")&&& public List&T& listAll() {&&&&&&& try {&&&&&&&&&&& Query query=entityManager.createQuery(" from Employee ");&&&&&&&&&&& return query.getResultList();&&&&&&& } catch (Exception e) {&&&&&&&&&&& e.printStackTrace();&&&&&&& }&&&&&&&&&& }}BaseServicepackage com.sj.import java.util.Lpublic interface BaseService&T& {&&& &&& List&T& listAll();&&& Object findById(Class&T& c,int id);&&& boolean save(Object object);&&& boolean update(Object object);&&& boolean delete(Object object);}BaseServiceImplpackage com.sj.import java.util.Limport javax.annotation.Rimport org.import org.springframework.transaction.annotation.Pimport org.springframework.transaction.annotation.Timport com.sj.dao.BaseDAO;@Component("baseServiceImpl")public class BaseServiceImpl&T& implements BaseService&T&{&&& @Resource(name="baseDAO")&&& private BaseDAO&T& baseDAO;&&& &&& public BaseDAO&T& getBaseDAO() {&&&&&&& return baseDAO;&&& }&&& public void setBaseDAO(BaseDAO&T& baseDAO) {&&&&&&& this.baseDAO = baseDAO;&&& }&&& @Transactional(propagation=Propagation.REQUIRED)&&& public boolean delete(Object object) {&&&&&&& return baseDAO.delete(object);&&& }&&& @Transactional(propagation=Propagation.REQUIRED)&&& public Object findById(Class&T& c, int id) {&&&&&&& return baseDAO.findById(c, id);&&& }&&& @Transactional(propagation=Propagation.REQUIRED)&&& public List&T& listAll() {&&&&&&& return baseDAO.listAll();&&& }&&& @Transactional(propagation=Propagation.REQUIRED)&&& public boolean save(Object object) {&&&&&&& return baseDAO.save(object);&&& }&&& @Transactional(propagation=Propagation.REQUIRED)&&& public boolean update(Object object) {&&&&&&& return baseDAO.update(object);&&& }&&& }EmployeeActionpackage com.sj.import java.util.Limport javax.annotation.Rimport org.springframework.stereotype.Cimport org.springframework.web.bind.annotation.RequestMimport org.springframework.web.bind.annotation.RequestMimport org.springframework.web.bind.annotation.ResponseBimport org.springframework.web.servlet.ModelAndVimport com.sj.bean.Eimport com.sj.service.BaseS@Controller@RequestMapping("/employee.action")public class EmployeeAction {&&& &&& @SuppressWarnings("unchecked")&&& @Resource(name="baseServiceImpl")&&& private BaseS&&& &&& &&& @SuppressWarnings("unchecked")&&& @RequestMapping(method=RequestMethod.GET,params="method=listAll")&&& public ModelAndView listAll(){&&&&&&& List&Employee& list=service.listAll();&&&&&&& return new ModelAndView("list").addObject("list", list);&&& }&&& &&& &&& @ResponseBody&&& @RequestMapping(params="method=listOther")&&& public String listOther(){&&&&&&& String str="&font color='red'&HelloWorld&/font&";&&&&&&&&&& }}TestApppackage com.sj.import javax.annotation.Rimport org.junit.Timport org.junit.runner.RunWimport org.springframework.test.context.ContextCimport org.springframework.test.context.junit4.SpringJUnit4ClassRimport com.sj.bean.Dimport com.sj.bean.Eimport com.sj.service.BaseS@ContextConfiguration(locations="file:D:\\Program Files\\MyEclipse 8.5-workspace\\sj\\WebRoot\\WEB-INF\\applicationContext.xml")@RunWith(SpringJUnit4ClassRunner.class)public class TestApp {&&& &&& @SuppressWarnings("unchecked")&&& @Resource(name="baseServiceImpl")&&& BaseService baseS&&& &&& @Test&&& public void save(){&&&&&&& Employee employee=new Employee();&&&&&&& employee.setName("张三");&&&&&&& Department department=new Department();&&&&&&& department.setName("软件测试组");&&&&&&& employee.setDepartment(department);&&&&&&& baseService.save(employee);&&& }&&& &&& @SuppressWarnings("unchecked")&&& @Test&&& public void query(){&&&&&&& Employee employee=(Employee) baseService.findById(Employee.class, 2);&&&&&&& System.out.println(employee.getId()+"\t"+employee.getName()+"\t"+employee.getDepartment().getName());&&& }&&& }&&& applicationContext.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:aop="http://www.springframework.org/schema/aop"&&& xmlns:tx="http://www.springframework.org/schema/tx"&&& xmlns:context="http://www.springframework.org/schema/context"&&& xsi:schemaLocation="http://www.springframework.org/schema/beans &&& http://www.springframework.org/schema/beans/spring-beans-3.0.xsd &&& http://www.springframework.org/schema/tx &&& http://www.springframework.org/schema/tx/spring-tx.xsd&&& http://www.springframework.org/schema/aop &&& http://www.springframework.org/schema/aop/spring-aop.xsd&&& http://www.springframework.org/schema/context&&& http://www.springframework.org/schema/context/spring-context.xsd"&&&& &&& &context:annotation-config/&&&& &context:component-scan base-package="com.sj.*"/&&&& &aop:aspectj-autoproxy/&&&& &&& &tx:annotation-driven transaction-manager="transactionManager" /&&&& &bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"&&&&&&&& &property name="persistenceUnitName" value="sjPU" /&&&&&&&& &property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml"&&/property&&&& &/bean&&&& &bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"&&&&&&&& &property name="entityManagerFactory" ref="entityManagerFactory" /&&&& &/bean&&/beans&dispatcherServlet-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:aop="http://www.springframework.org/schema/aop"&&& xmlns:tx="http://www.springframework.org/schema/tx"&&& xmlns:context="http://www.springframework.org/schema/context"&&& xsi:schemaLocation="http://www.springframework.org/schema/beans &&& http://www.springframework.org/schema/beans/spring-beans-3.0.xsd &&& http://www.springframework.org/schema/tx &&& http://www.springframework.org/schema/tx/spring-tx.xsd&&& http://www.springframework.org/schema/aop &&& http://www.springframework.org/schema/aop/spring-aop.xsd&&& http://www.springframework.org/schema/context&&& http://www.springframework.org/schema/context/spring-context.xsd"&&&& &&& &context:component-scan base-package="com.sj.action"/&&&& &bean id="defaultAnnotationHandlerMapping" class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping"/&&&& &bean id="annotationMethodHandlerAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"&&&&&&&& &property name="messageConverters"&&&&&&&&&&&& &list&&&&&&&&&&&&&&&& &bean class="org.springframework.http.converter.StringHttpMessageConverter"&&&&&&&&&&&&&&&&&&&& &property name="supportedMediaTypes"&&&&&&&&&&&&&&&&&&&&&&&& &list&&&&&&&&&&&&&&&&&&&&&&&&&&&& &value&text/charset=utf-8&/value&&&&&&&&&&&&&&&&&&&&&&&&&&&& &value&text/xml&/value&&&&&&&&&&&&&&&&&&&&&&&&&&&& &value&text/plain&/value&&&&&&&&&&&&&&&&&&&&&&&& &/list&&&&&&&&&&&&&&&&&&&& &/property&&&&&&&&&&&&&&&& &/bean&&&&&&&&&&&& &/list&&&&&&&& &/property&&&& &/bean&&&& &&& &bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"&&&&&&&& &property name="suffix" value=".jsp"&&/property&&&&&&&& &property name="prefix" value="/"&&/property&&&&&&&& &property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/&&&& &/bean&&&& &/beans&web.xml&?xml version="1.0" encoding="UTF-8"?&&web-app version="2.5" &&& xmlns="/xml/ns/javaee" &&& xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" &&& xsi:schemaLocation="/xml/ns/javaee &&& /xml/ns/javaee/web-app_2_5.xsd"&& &welcome-file-list&&&& &welcome-file&index.jsp&/welcome-file&& &/welcome-file-list&& & &listener&&&&&& &listener-class&org.springframework.web.context.ContextLoaderListener&/listener-class&& &/listener&&&&&&&& &context-param&&&&&&&&&& &param-name&contextConfigLocation&/param-name&&&&&&&&&& &param-value&/WEB-INF/applicationContext.xml&/param-value&&&&&& &/context-param&& &servlet&&&&&& &servlet-name&dispatcherServlet&/servlet-name&&&&&& &servlet-class&org.springframework.web.servlet.DispatcherServlet&/servlet-class&&&&&& &load-on-startup&1&/load-on-startup&& &/servlet&& &servlet-mapping&&&&&& &servlet-name&dispatcherServlet&/servlet-name&&&&&& &url-pattern&*.action&/url-pattern&& &/servlet-mapping&& &/web-app&src/META-INF/persistence.xml&?xml version="1.0" encoding="UTF-8"?&&persistence xmlns="/xml/ns/persistence"&&& xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"&&& xsi:schemaLocation="/xml/ns/persistence&&& /xml/ns/persistence/persistence_1_0.xsd"&&& version="1.0"&&&& &persistence-unit name="sjPU" transaction-type="RESOURCE_LOCAL"&&&&&&&& &provider&org.hibernate.ejb.HibernatePersistence&/provider&&&&&&&& &properties&&&&&&&&&&&& &property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" /&&&&&&&&&&&& &property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/sj" /&&&&&&&&&&&& &property name="hibernate.connection.username" value="root" /&&&&&&&&&&&& &property name="hibernate.connection.password" value="root" /&&&&&&&&&&&& &property name="hibernate.show_sql" value="true" /&&&&&&&&&&&& &property name="hibernate.format_sql" value="true" /&&&&&&&&&&&& &property name="hibernate.hbm2ddl.auto" value="update" /&&&&&&&& &/properties&&&& &/persistence-unit&&/persistence&list.jsp&%@ page language="java" contentType="text/ charset=UTF-8" pageEncoding="UTF-8"%&&%@ taglib prefix="c" uri="/jsp/jstl/core" %&&!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/ charset=UTF-8"&&title&雇员信息列表&/title&&/head&&body&&&& &c:if test="${empty requestScope.list}"&&&&&&&& 对不起,没有要显示的记录!!!!&&& &/c:if&&&& &c:if test="${!empty requestScope.list}"&&&&&&&& &c:forEach items="${requestScope.list}" var="s"&&&&&&&&&&&& &c:out value="${s.id}"/&&&&&&&&&&&& &c:out value="${s.name}"/&&&&&&&&&&&& &c:out value="${s.department.name}"/&&&&&&&&&&&& &br/&&&&&&&& &/c:forEach&&&& &/c:if&&/body&&/html&这里重点关注applicationContext.xml、dispatcherServlet-servlet.xml、EmployeeAction。其中dispatcherServlet-servlet.xml文件的命名规则遵循web.xml中配置的dispatcherServlet servlet的servlet-name属性的值。dispatcherServlet-servlet.xml里面配置了开启SpringMVC的注解解析器以及视图渲染器,和处理response时返回给浏览器的头信息.点我下载工程代码Spring ManyToOne注脚 - 软件架构设计当前位置:& &&&Spring ManyToOne注脚Spring ManyToOne注脚&&网友分享于:&&浏览:212次Spring ManyToOne注解
@Table(name="KS_ROLE_USER_AUTH")
public class RoleUserAuthorization extends Accountability
@ManyToOne
@JoinColumn(name="ROLE_ID", nullable=false)
@ManyToOne
@JoinColumn(name="USER_ID", nullable=false)
@Table(name="KS_ROLE")
@DiscriminatorColumn(name="role", discriminatorType=DiscriminatorType.STRING)
public class Role extends Identity
private static final long serialVersionUID = -4457036L;
@Column(name="ROLE_DESC")
private String roleD
@OneToMany(fetch=FetchType.LAZY, mappedBy="role")
private List&RoleUserAuthorization& roleU
public List&RoleUserAuthorization& getRoleUsers()
return this.roleU
public void setRoleUsers(List&RoleUserAuthorization& roleUsers) {
this.roleUsers = roleU
@Table(name="KS_USER")
@DiscriminatorColumn(name="User", discriminatorType=DiscriminatorType.STRING)
public class User extends Identity
private static final long serialVersionUID = 8658820L;
@Column(name="LAST_LOGIN_TIME")
@Temporal(TemporalType.TIMESTAMP)
private Date lastLoginT
@Column(name="USER_ACCOUNT")
private String userA
@Column(name="USER_PASSWORD")
private String userP
@Column(name="USER_DESC")
private String userD
@Column(name="LAST_MODIFY_TIME")
private Date lastModifyT
public Set&RoleUserAuthorization& getRoles()
return new HashSet(RoleUserAuthorization.findAuthorizationByUser(this));
单向关系中的JoinColumn
joinColumns={
@JoinColumn(name="customer_id",referencedColumnName="id")
领域层业务开发
//查找某个年龄段内的员工
public static List&Employee& findByAgeRange(Integer from, Integer to) {
return getRepository().findByNamedQuery("findEmployeesByAgeRange",
new Object[]{from, to}, Employee.class);
@JoinColumn
@OneToOne @JoinColumn(name = "addr_id") public AddressEO getAddress() {
} 若此时,不设置name的值,则在默认情况下,name的取值遵循以下规则: name=关联表的名称+“_”+ 关联表主键的字段名 例如,CustomerEO实体中,如果不指定name的值,默认将对应name=address_id;,实体AddressEO对应的表名为“address”;表address的主键是“id”,所以此时对应的默认的字段名称为“address_id”。 提示:@,将遵循其他的规则。 l 默认情况下,关联的实体的主键一般是用来做外键的。但如果此时不想主键作为外键,则需要设置referencedColumnName属性。例如,将address表中增加一个字段“ref_id”,address表的建表SQL变为以下所示。 CREATE TABLE address ( id int(20) NOT NULL auto_increment, ref_id int int(20) NOT NULL, province varchar(50) , city varchar(50) , postcode varchar(50) , detail varchar(50) , PRIMARY KEY (id) ) 此时,通过customer表中的“address_id”字段关联的是address表中的“ref_id”,而“ref_id”并不是address表中的主键,则实体中标注如代码下所示。 @OneToOne @JoinColumn(name = "address_id",referencedColumnName="ref_id") public AddressEO getAddress() {
} 属性referencedColumnName标注的是所关联表中的字段名,若不指定则使用的所关联表的主键字段名作为外键。 l ,@ManyToMany标记同时使用,它们所表示的含义不同,这些内容将在下文详细讲述。
12345678910
12345678910
12345678910 上一篇:下一篇:文章评论相关解决方案 12345678910 Copyright & &&版权所有SpringMVC 常见注脚_VC/MFC大全_优良自学吧 |
当前位置: >
> SpringMVC 常见注脚优良自学吧提供SpringMVC 常见注脚,SpringMVC 常见注解 详解Spring MVC 4常用的那些注解 http://favccxx./2185SpringMVC 常见注解 http://qing..cnSpringMVC 常见注解
详解Spring MVC 4常用的那些注解 http://favccxx./2185SpringMVC 常见注解 http://qing..cn//c048a0ba33003w90.html1o @Controller 2o @Service3o @Autowired4o @RequestMapping5o @RequestParam6o @ModelAttribute7o @Cacheable8o @CacheFlush9o @Resource10o @PostConstruct11o @PreDestroy12o @Repository13o @Component (不推荐使用)14o @Scope15o @SessionAttributes16o @InitBinder17o @Required18o @Qualifier19o @PathVariable& 20o @Valid& 21o @AttributeOverride 22o @Column1o& @Controller& 例如@Controllerpublic class SoftCreateController extends SimpleBaseController {} & 或者@Controller("softCreateController") & 说明@Controller 负责注册一个bean 到spring 上下文中,bean 的ID 默认为类名称开头字母小写2o& @Service& 例如@Servicepublic class SoftCreateServiceImpl implements ISoftCreateService {} & 或者@Service("softCreateServiceImpl") & 说明@Service 负责注册一个bean 到spring 上下文中,bean 的ID 默认为类名称开头字母小写3o& @Autowired& 例如@Autowiredprivate ISoftPMService softPMS & 或者 @Autowired(required=false)private ISoftPMService softPMService = new SoftPMServiceImpl(); & 说明@Autowired 根据bean 类型从spring 上线文中进行查找,注册类型必须唯一,否则报异常。与@Resource 的区别在于,@Resource 允许通过bean 名称或bean 类型两种方式进行查找@Autowired(required=false) 表示,如果spring 上下文中没有找到该类型的bean 时, 才会使用new SoftPMServiceImpl();@Autowired 标注作用于 Map 类型时,如果 Map 的 key 为 String 类型,则 Spring 会将容器中所有类型符合 Map 的 value 对应的类型的 Bean 增加进来,用 Bean 的 id 或 name 作为 Map 的 key。@Autowired 还有一个作用就是,如果将其标注在 BeanFactory 类型、ApplicationContext 类型、ResourceLoader 类型、ApplicationEventPublisher 类型、MessageSource 类型上,那么 Spring 会自动注入这些实现类的实例,不需要额外的操作。4o& @RequestMapping& 类@Controller@RequestMapping("/bbtForum.do")public class BbtForumController {@RequestMapping(params = "method=listBoardTopic")public String listBoardTopic(int topicId,User user) {}}& 方法@RequestMapping("/softpg/downSoftPg.do")@RequestMapping(value="/softpg/ajaxLoadSoftId.do",method = POST)@RequestMapping(value = "/osu/product/detail.do", params = { "modify=false" }, method =POST)& 说明@RequestMapping 可以声明到类或方法上& 参数绑定说明如果我们使用以下的 URL 请求:http://localhost/bbtForum.do?method=listBoardTopic&topicId=1&userId=10&userName=tomtopicId URL 参数将绑定到 topicId 入参上,而 userId 和 userName URL 参数将绑定到 user 对象的 userId 和 userName 属性中。和 URL 请求中不允许没有 topicId 参数不同,虽然 User 的 userId 属性的类型是基本数据类型,但如果 URL 中不存在 userId 参数,Spring 也不会报错,此时 user.userId 值为 0 。如果 User 对象拥有一个 dept.deptId 的级联属性,那么它将和 dept.deptId URL 参数绑定。5o& @RequestParam& 参数绑定说明@RequestParam("id")http://localhost/bbtForum.do?method=listBoardTopic&id=1&userId=10&userName=tomlistBoardTopic(@RequestParam("id")int topicId,User user) 中的 topicId 绑定到 id 这个 URL 参数, 那么可以通过对入参使用 @RequestParam 注解来达到目的@RequestParam(required=false):参数不是必须的,默认为true@RequestParam(value="id",required=false)请求处理方法入参的可选类型* Java 基本数据类型和 String默认情况下将按名称匹配的方式绑定到 URL 参数上,可以通过 @RequestParam 注解改变默认的绑定规则* request/response/session既可以是 Servlet API 的也可以是 Portlet API 对应的对象,Spring 会将它们绑定到Servlet 和 Portlet 容器的相应对象上* org.springframework.web.context.request.WebRequest内部包含了 request 对象* java.util.Locale绑定到 request 对应的 Locale 对象上* java.io.InputStream/java.io.Reader可以借此访问 request 的内容* java.io.OutputStream / java.io.Writer可以借此操作 response 的内容* 任何标注了 @RequestParam 注解的入参被标注 @RequestParam 注解的入参将绑定到特定的 request 参数上。* java.util.Map / org.springframework.ui.ModelMap它绑定 Spring MVC 框架中每个请求所创建的潜在的模型对象,它们可以被 Web 视图对象访问(如 JSP )* 命令/ 表单对象(注:一般称绑定使用 HTTP GET 发送的 URL 参数的对象为命令对象,而称绑定使用HTTP POST 发送的 URL 参数的对象为表单对象)它们的属性将以名称匹配的规则绑定到 URL 参数上,同时完成类型的转换。而类型转换的规则可以通过 @InitBinder 注解或通过 HandlerAdapter 的配置进行调 整* org.springframework.validation.Errors / org.springframework.validation.BindingResult为属性列表中的命令/ 表单对象的校验结果,注意检验结果参数必须紧跟在命令/ 表单对象的后面* org.springframework.web.bind.support.SessionStatus可以通过该类型 status 对象显式结束表单的处理,这相当于触发 session 清除其中的通过@SessionAttributes 定义的属性请求处理方法返回值的可选类型* void此时逻辑视图名由请求处理方法对应的 URL 确定,如以下的方法:@RequestMapping("/welcome.do")public void welcomeHandler() {}对应的逻辑视图名为 “ welcome ”* String此时逻辑视图名为返回的字符,如以下的方法:@RequestMapping(method = RequestMethod.GET)public String setupForm(@RequestParam("ownerId") int ownerId, ModelMap model) { Owner owner = this.clinic.loadOwner(ownerId);model.addAttribute(owner);return "ownerForm"; }对应的逻辑视图名为 “ ownerForm ” * org.springframework.ui.ModelMap和返回类型为 void 一样,逻辑视图名取决于对应请求的 URL ,如下面的例子:@RequestMapping("/vets.do")public ModelMap vetsHandler() {return new ModelMap(this.clinic.getVets());}对应的逻辑视图名为 “ vets ” ,返回的 ModelMap 将被作为请求对应的模型对象,可以在 JSP 视图页面中访问到。* ModelAndView当然还可以是传统的 ModelAndView 。6o& @ModelAttribute& 作用域:request& 例如@RequestMapping("/base/userManageCooper/init.do")public String handleInit(@ModelAttribute("queryBean") ManagedUser sUser,Model model,){ & 或者@ModelAttribute("coopMap")// 将coopMap 返回到页 面public Map&Long,CooperatorInfo& coopMapItems(){} & 说明 @ModelAttribute 声明在属性上,表示该属性的value 来源于model 里"queryBean" ,并被保存到model 里@ModelAttribute 声明在方法上,表示该方法的返回值被保存到model 里o& @Cacheable 和@CacheFlush7o& @Cacheable :声明一个方法的返回值应该被缓 存例如:@Cacheable(modelId = "testCaching") 8o& @CacheFlush :声明一个方法是清空缓存的触发器例如:@CacheFlush(modelId = "testCaching")& 说明要配合缓存处理器使用,参考: /blog/6037199o& @Resource& 例如@Resourceprivate DataSource dataS // inject the bean named 'dataSource'& 或者@Resource(name="dataSource")@Resource(type=DataSource.class)& 说明@Resource 默认按bean 的name 进行查找,如果没有找到会按type 进行查找,此时与@Autowired 类 似在没有为 @Resource 注解显式指定 name 属性的前提下,如果将其标注在 BeanFactory 类型、ApplicationContext 类型、ResourceLoader 类型、ApplicationEventPublisher 类型、MessageSource 类型上,那么 Spring 会自动注入这些实现类的实例,不需要额外的操作。此时 name 属性不需要指定 ( 或者指定为""),否则注入失败;o& @PostConstruct 和@PreDestroy10o @PostConstruct在方法上加上注解@PostConstruct ,这个方法就会在Bean 初始化之后被Spring 容器执 行(注:Bean 初始化包括,实例化Bean ,并装配Bean 的属性(依赖注入))。11o @PreDestroy在方法上加上注解@PreDestroy ,这个方法就会在Bean 被销毁前被Spring 容器执行。12o& @Repository& 与@Controller 、@Service 类似,都是向spring 上下文中注册bean ,不在赘述。13o& @Component (不推荐使用)@Component 是所有受Spring 管理组件的通用形式,Spring 还提供了更加细化的注解形式: @Repository 、@Service 、@Controller ,它们分别对应存储层Bean ,业务层Bean ,和展示层Bean 。目前版本(2.5 )中,这些注解与@Component 的语义是一样的,完全通用, 在Spring 以后的版本中可能会给它们追加更多的语义。 所以,我们推荐使用@Repository 、@Service 、@Controller 来替代@Component 。14o& @Scope& 例如@Scope("session")@Repository()public class UserSessionBean implementsSerializable {}& 说明在使用XML 定义Bean 时,可以通过bean 的scope 属性来定义一个Bean 的作用范围,同样可以通过@Scope 注解来完成@Scope中可以指定如下值:singleton:定义bean的范围为每个spring容器一个实例(默认值)prototype:定义bean可以被多次实例化(使用一次就创建一次)request:定义bean的范围是http请求(springMVC中有效)session:定义bean的范围是http会话(springMVC中有效)global-session:定义bean的范围是全局http会话(portlet中有效)15o& @SessionAttributes& 说明Spring 允许我们有选择地指定 ModelMap 中的哪些属性需要转存到 session 中,以便下一个请求属对应的 ModelMap 的属性列表中还能访问到这些属性。这一功能是通过类定义处标注 @SessionAttributes 注解来实现的。@SessionAttributes 只能声明在类上,而不能声明在方法上。&& 例如@SessionAttributes("currUser") // 将ModelMap 中属性名为currUser 的属性@SessionAttributes({"attr1","attr2"})@SessionAttributes(types = User.class)@SessionAttributes(types = {User.class,Dept.class})@SessionAttributes(types = {User.class,Dept.class},value={"attr1","attr2"})16o& @InitBinder&& 说明如果希望某个属性编辑器仅作用于特定的 Controller ,可以在 Controller 中定义一个标注 @InitBinder 注解的方法,可以在该方法中向 Controller 了注册若干个属性编辑器&& 例如@InitBinderpublic void initBinder(WebDataBinder binder) {SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");dateFormat.setLenient(false);binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));}17o& @Required& 例如@requiredpublic setName(String name){}& 说明@ required 负责检查一个bean在初始化时其声明的 set方法是否被执行, 当某个被标注了 @Required 的 Setter 方法没有被调用,则 Spring 在解析的时候会抛出异常,以提醒开发者对相应属性进行设置。 @Required 注解只能标注在 Setter 方法之上。因为依赖注入的本质是检查 Setter 方法是否被调用了,而不是真的去检查属性是否赋值了以及赋了什么样的值。如果将该注解标注在非 setXxxx() 类型的方法则被忽略。18o& @Qualifier 例如@Autowired@Qualifier("softService")private ISoftPMService softPMS 说明使用@Autowired 时,如果找到多个同一类型的bean,则会抛异常,此时可以使用 @Qualifier("beanName"),明确指定bean的名称进行注入,此时与 @Resource指定name属性作用相同。19o @PathVariable@PathVariable是用来对指定请求的URL路径里面的变量 eg: Java代码 @RequestMapping(value = "form/{id}/apply", method = {RequestMethod.PUT, RequestMethod.POST}) {id}在这个请求的URL里就是个变量,可以使用@PathVariable来获取20o @valid@Valid Production production //实体设置+类+类的引用 直接将页面传过来的production对象中的信息封装到里面去了21o& @AttributeOverride@AttributeOverride表示属性的映射,而@AttributeOverrides由多个@AttributeOverride& 注释组成,每个@AttributeOverride表示属性的映射,它的定义如以下所示:@Target({TYPE, METHOD, FIELD}) @Retention(RUNTIME)public @interface AttributeOverride {String name();Column column();}在使用@AttributeOverride注释应注意以下几方面的问题:&& ☆&&&& name属性表示嵌入式类中的属性名称。&& ☆&&&& column属性表示,所嵌入的实体类中的列定义,其中@Column标记表示的意义见第22项。&& ☆&&&&& 例如将tb_customer表中的customer_zip字段映射为Address中的属性zip。代码如下所示:@AttributeOverride(name = "zip",column = @Column(name = "customer_zip"))& ☆&&&&&& 使用嵌入式类的好处是:多个实体中都可以共享一个嵌入式类,方便了对实体的操作。例如现在ContactEO也嵌入Address类,就很方便的映射为以下所示:public class CustomerEO implements Serializable { &&&&&&&& private I&&&&&&&& private S&&&&&&&& private S……getter和setter方法省略&&&&&&&& private A&&&&&&&& @Embedded&&&&&&&& @AttributeOverrides( {&&&&&&&&&&&&&&&&&& @AttributeOverride(name = "zip", column = @Column(name = "contact_zip")),&&&&&&&&&&&&&&&&&& @AttributeOverride(name = "line1", column = @Column(name = "contact_line1")),&&&&&&&& })&&&&&&&& public Address getAddress() {&&&&&&&&&&&&&&&&&&&&&&&&&& }&&&&&&&& public void setAddress(Address address) {&&&&&&&&&&&&&&&&&& this.address =&&&&&&&& }}22o @Column @Column标记表示所持久化属性所映射表中的字段,该注释的属性定义如下:@Target({METHOD, FIELD}) @Retention(RUNTIME)public @interface Column {String name() default "";boolean unique()boolean nullable()boolean insertable()boolean updatable()String columnDefinition() default "";String table() default "";int length() default 255;int precision() default 0;int scale() default 0;}在使用此@Column标记时,需要注意以下几个问题:l&&&&&&&& 此标记可以标注在getter方法或属性前,例如以下的两种标注方法都是正确的:标注在属性前:@Entity@Table(name = "contact")public class ContactEO{@Column(name=" contact_name ")private S}标注在getter方法前:@Entity@Table(name = "contact")public class ContactEO{@Column(name=" contact_name ")public String getName() {&&&&&&&&}}提示:JPA规范中并没有明确指定那种标注方法,只要两种标注方式任选其一都可以。这根据个人的喜好来选择,笔者习惯使用第二种方法。l&&&&&&&& unique属性表示该字段是否为唯一标识,默认为false。如果表中有一个字段需要唯一标识,则既可以使用该标记,也可以使用@Table标记中的@UniqueConstraint。l&&&&&&&& nullable属性表示该字段是否可以为null值,默认为true。l&&&&&&&& insertable属性表示在使用“INSERT”脚本插入数据时,是否需要插入该字段的值。l&&&&&&&& updatable属性表示在使用“UPDATE”脚本插入数据时,是否需要更新该字段的值。insertable和updatable属性一般多用于只读的属性,例如主键和外键等。这些字段的值通常是自动生成的。l&&&&&&&& columnDefinition属性表示创建表时,该字段创建的SQL语句,一般用于通过Entity生成表定义时使用。l&&&&&&&& table属性表示当映射多个表时,指定表的表中的字段。默认值为主表的表名。有关多个表的映射将在本章的5.6小节中详细讲述。l&&&&&&&& length属性表示字段的长度,当字段的类型为varchar时,该属性才有效,默认为255个字符。l&&&&&&&& precision属性和scale属性表示精度,当字段类型为double时,precision表示数值的总长度,scale表示小数点所占的位数。下面举几个小例子:示例一:指定字段“contact_name”的长度是“512”,并且值不能为null。private S @Column(name="contact_name",nullable=false,length=512)public String getName() {&&&&&&&&}创建的SQL语句如下所示。CREATE TABLE contact (id integer not null,contact_name varchar (512) not null,primary key (id))示例二:指定字段“monthly_income”月收入的类型为double型,精度为12位,小数点位数为2位。&&&&&&&& private BigDecimal monthlyI &&&&&&&& @Column(name="monthly_income",precision=12, scale=2)&&&&&&&& public BigDecimal getMonthlyIncome() {&&&&&&&&&&&&&&&&&& return monthlyI&&&&&&&& }创建的SQL语句如下所示。CREATE TABLE contact (id integer not null,monthly_income double(12,2),primary key (id))示例三:自定义生成CLOB类型字段的SQL语句。private String& @Column(name=" contact_name ",columnDefinition="clob not null")public String getName() {&&&&&&&&&&&&&&&&&}生成表的定义SQL语句如下所示。CREATE TABLE contact (id integer not null,contact_name clob (200) not null,primary key (id))其中,加粗的部分为columnDefinition属性设置的值。若不指定该属性,通常使用默认的类型建表,若此时需要自定义建表的类型时,可在该属性中设置。提示:通过Entity定义生成表,还是通过表配置Entity,这两种ORM的策略。有关两种方法的映射策略好坏,将在本书的章节中“JPA工具的使用”一章进行详细的比较。示例四:字段值为只读的,不允许插入和修改。通常用于主键和外键。&&&&&&&& private I&&&&&&& &&&&&&&& @Column(name="id",insertable=false,updatable=false)&&&&&&&& public Integer getId() {&&&&&&&&&&&&&&&&&&&&&&&&&& }(本文来自互联网,不代表搜站(/)的观点和立场)本站所有内容来自互联网,若本站收录的信息无意侵犯了贵司版权,请给我们来信(),我们会及时处理和回复,谢谢编辑推荐最近更新

我要回帖

更多关于 springmvc cxf3.0整合 的文章

 

随机推荐