Spring MVC Annotation Implementation

Source: Internet
Author: User
Tags aop getmessage log log object model stringbuffer

Abandoning struts, doing several projects with the Spring MVC framework, feeling good, and using annotations, can save a lot of configuration files. This article focuses on spring MVC, which is configured using annotations, and the spring3.0 MVC and Rest small examples that were previously written do not introduce the content of the data layer, and now this one is filled in. The following starts the code.

Frame version used in the article: Spring 3,hibernate 3, no, the Internet under their own.

First say Web.xml configuration:

<?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" id= "Webapp_ ID "version=" 2.5 > <display-name>s3h3</display-name> <context-param> <param-name> Contextconfiglocation</param-name> <param-value>classpath:applicationcontext*.xml</param-value > </context-param> <listener> <listener-class> Org.springframework.web.context.contextloaderlistener</listener-class> </listener> <servlet> <servlet-name>spring</servlet-name> <servlet-class> Org.springframework.web.servlet.dispatcherservlet</servlet-class> <load-on-startup>1</ load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring</servlet-name> <!--here in the spring, below also write a file named Spring-servlet.xml, mainly used to configure its controller--> <url-pattern>*.do</ url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file > </welcome-file-list> </web-app>

Spring-servlet, the main configuration of controller information

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" 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" xsi:schemalocation= "Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http ://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http:// Www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/context http:// Www.springframework.org/schema/context/spring-context-3.0.xsd "> <context:annotation-config/> <!-- Converts classes marked with @controller annotations to bean--> <context:component-scan base-package= "Com.mvc.controller"/> <!-- Start the annotation feature of spring MVC, complete the mapping of request and annotation Pojo--> <bean class= " Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHanDleradapter/> <!--resolves the model view name by adding prefix--> <bean class= to the Model view name Org.springframework.web.servlet.view.InternalResourceViewResolver "p:prefix="/web-inf/view/"p:suffix=". JSP "/ > <bean id= "multipartresolver" class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" P: defaultencoding= "Utf-8"/> </beans>

Applicationcontext.xml Code

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: aop= "HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP" xmlns:context= "Http://www.springframework.org/schema/context" xmlns:p= "http://www.springframework.org/schema/p" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi:schemalocation= "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/AOP http ://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http:// Www.springframework.org/schema/tx/spring-tx-3.0.xsd "> <context:annotation-config/> <context: Component-scan base-package= "Com.mvc"/> <!--automatically scans all annotations this path--> <context:property-placeholder " ClasspAth:/hibernate.properties "/> <bean id=" sessionfactory "class=" Org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean "> <property name=" DataSource " ref= "DataSource"/> <property name= "hibernateproperties" > <props> <prop key= "Hibernate.dialect" >${dataSource.dialect}</prop> <prop key= "Hibernate.hbm2ddl.auto" >${datasource.hbm2ddl.auto}</ prop> <prop key= "Hibernate.hbm2ddl.auto" >update</prop> </props> </property> <property Name= "Packagestoscan" > <list> <value>com.mvc.entity</value><!--Scan entity class, which is usually called model--> </list> </property> </bean> <bean id= "TransactionManager" class= " Org.springframework.orm.hibernate3.HibernateTransactionManager "> <property name=" sessionfactory "ref=" Sessionfactory "/> <property name= dataSource" ref= "DataSource"/> </bean> <bean id= "DataSource" Class= "Org.springframework.jdbc.datasource.DriverManagerDataSource "> <property name=" driverclassname value= "${datasource.driverclassname}"/> <property name= " URL "value=" ${datasource.url} "/> <property name=" username "value=" ${datasource.username} "/> <property Name= "Password" value= "${datasource.password}"/> </bean> <!--DAO implementation--> <bean id= "Entitydao" class= "Com.mvc.dao.EntityDaoImpl" > <property name= "sessionfactory" ref= "sessionfactory"/> </bean> <tx: Annotation-driven transaction-manager= "TransactionManager"/> <tx:annotation-driven mode= "AspectJ"/> < Aop:aspectj-autoproxy/> </beans>

Hibernate.properties Database Connection Configuration

datasource.password=123 datasource.username=root datasource.databasename=test dataSource.driverClassName= Com.mysql.jdbc.Driver Datasource.dialect=org.hibernate.dialect.mysql5dialect Datasource.servername=localhost : 3306 datasource.url=jdbc:mysql://localhost:3306/test Datasource.properties=user=${datasource.username}; Databasename=${datasource.databasename};servername=${datasource.servername};p Assword=${datasource.password} Datasource.hbm2ddl.auto=update

The configuration is complete, and the example below begins

First in the database to build tables, examples are used in the MySQL database

CREATE TABLE ' test '. ' Student ' (' id ' int () unsigned not null auto_increment, ' name ' varchar ' (=) not null, ' PSW ' varchar ( Not NULL, PRIMARY KEY (' id '))

When the table is built, the entity classes are generated.

Package com.mvc.entity; Import java.io.Serializable; Import Javax.persistence.Basic; Import Javax.persistence.Column; Import javax.persistence.Entity; Import Javax.persistence.GeneratedValue; Import Javax.persistence.GenerationType; Import Javax.persistence.Id; Import javax.persistence.Table; @Entity @Table (name = "Student") public class student implements Serializable {private static final long Serialversionuid = 1L; @Id @Basic (optional = False) @GeneratedValue (strategy = generationtype.identity) @Column (name = "Id", Nullable = False) PR Ivate Integer ID; @Column (name = "name") private String user; @Column (name = "PSW") private String PSW; Public Integer GetId () {return id;} public void setId (Integer id) {this.id = ID;} public String GetUser () R The public void SetUser (string user) {This.user = user} is public string getpsw () {return PSW;} public void Setpsw (string PSW) {this.psw = PSW;}}

DAO Layer Implementation

Package Com.mvc.dao; Import java.util.List; Public interface Entitydao {public list<object> createquery (Final String QueryString), Public Object Save (final OBJ ECT model); public void Update (final Object model); public void Delete (final Object model); }

Package Com.mvc.dao; Import java.util.List; Import Org.hibernate.Query; Import Org.springframework.orm.hibernate3.HibernateCallback; Import Org.springframework.orm.hibernate3.support.HibernateDaoSupport; public class Entitydaoimpl extends Hibernatedaosupport implements entitydao{public list<object> createquery ( Final String QueryString) {return (list<object>) gethibernatetemplate (). Execute (New hibernatecallback< Object> () {public Object doinhibernate (org.hibernate.Session session) throws Org.hibernate.HibernateException { Query query = session.createquery (querystring); list<object> rows = Query.list (); return rows; } }); The public object Save (final Object model) {return gethibernatetemplate (). Execute (new hibernatecallback<object> () { Public Object Doinhibernate (org.hibernate.Session session) throws Org.hibernate.HibernateException {Session.save ( model); return null; } }); public void Update (final Object model) {gethibernatetemplate (). Execute (New HibeRnatecallback<object> () {public Object doinhibernate (org.hibernate.Session session) throws org.hibernate.HibernateException {session.update (model); return null;}}); The public void Delete (final Object model) {gethibernatetemplate (). Execute (new hibernatecallback<object> () {public Object Doinhibernate (org.hibernate.Session session) throws Org.hibernate.HibernateException {Session.delete (model); return null; } }); }}  

DAO in Applicationcontext.xml Injection

<bean id= "Entitydao" class= "Com.mvc.dao.EntityDaoImpl" >
<property name= "Sessionfactory" ref= "Sessionfactory"/>
</bean>

DAO has only one class implementation, directly for other service layer calls, if you want to replace the other DAO implementation, just modify the configuration here.

Start to write the View page, Web-inf/view new page Student.jsp,web-inf/view This path is configured in Spring-servlet.xml file, you can configure other, can also multiple paths. student.jsp Code

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <%@ include file="/include/head.jsp "%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

student_add.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%> <%@ include file="/include/head.jsp "%> <! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

Controller class implementation, just write the annotations, spring will automatically help you find the appropriate bean, the corresponding annotation markup meaning, do not understand, you can check the @service, @Controller, @Entity and so on.

Package Com.mvc.controller; Import java.util.List; Import Javax.servlet.http.HttpServletRequest; Import Javax.servlet.http.HttpServletResponse; Import Org.apache.commons.logging.Log; Import Org.apache.commons.logging.LogFactory; Import org.springframework.beans.factory.annotation.Autowired; Import Org.springframework.stereotype.Controller; Import Org.springframework.ui.ModelMap; Import org.springframework.web.bind.annotation.RequestMapping; Import Org.springframework.web.bind.annotation.RequestMethod; Import Org.springframework.web.bind.annotation.RequestParam; Import Org.springframework.web.servlet.ModelAndView; Import com.mvc.entity.Student; Import Com.mvc.service.StudentService; @Controller @RequestMapping ("/student.do") public class Studentcontroller {Protected final transient log log = Logfactory . GetLog (Studentcontroller.class); @Autowired private Studentservice Studentservice; Public Studentcontroller () {} @RequestMapping public String load (Modelmap modelmap) {List<object> List = Studentservice.getstudentlist (); Modelmap.put ("list", list); return "student"; @RequestMapping (params = "method=add") public String Add (httpservletrequest request, Modelmap Modelmap) throws Exceptio n{return "Student_add";} @RequestMapping (params = "method=save") public String Save (httpservletrequest request, Modelma P modelmap) {String user = Request.getparameter ("user"); String PSW = Request.getparameter ("PSW"); Student st = new Student (); St.setuser (user); ST.SETPSW (PSW); try{Studentservice.save (ST); Modelmap.put ("Addstate", "add Success");} catch (Exception e) {log.error (E.getmessage ()); Modelmap.put ("Addstate", "Add Failed"); Return to "Student_add"; @RequestMapping (params = "Method=del") public void del (@RequestParam ("id") String ID, httpservletresponse response) {TR y{Student st = new Student (); St.setid (integer.valueof (ID)); studentservice.delete (ST); Response.getwriter (). Print ("{ /"del/":/"true/"} "); catch (Exception e) {log.error (E.getmessage ()); E.printstacktrace ();} }

Service class implementation

Package com.mvc.service; Import java.util.List; Import org.springframework.beans.factory.annotation.Autowired; Import Org.springframework.stereotype.Service; Import org.springframework.transaction.annotation.Transactional; Import Com.mvc.dao.EntityDao; Import com.mvc.entity.Student; @Service public class Studentservice {@Autowired private Entitydao Entitydao; @Transactional public list<object> ge Tstudentlist () {StringBuffer SFF = new StringBuffer (); Sff.append ("Select a From"). Append (Student.class.getSimpleName ( ). Append ("a"); list<object> list = Entitydao.createquery (sff.tostring ()); return list; public void Save (Student St.) {Entitydao.save (ST);} public void Delete (Object obj) {entitydao.delete (obj)}

OK, example finished. There are other business content, simply create a new view, and implement the corresponding Comtroller and service on the line, configuration and DAO layer content is basically the same, that is, each time just write JSP (view), Controller and Service call DAO on the line.

How, looking at this, spring MVC is not more convenient and flexible than SSH implementations.

Attachment Source: s3h

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.