Os primeiros projetos eram relativamente simples, principalmente tratados diretamente com JSP, Servlet + JDBC. Posteriormente, o Struts1 (Struts2)+mola+hibernato foi usado para impulsionar o desenvolvimento do projeto estritamente de acordo com o conceito de camada. Desta vez, o MVC da primavera foi usado para substituir as suportes para o desenvolvimento.
O MVC já é uma parte muito importante do desenvolvimento da web moderno. Vamos introduzir o ambiente de desenvolvimento Construção de Springmvc+Spring3+Hibernate4.
Vamos dar uma olhada na estrutura do projeto:
O código específico não será mais demonstrado; é principalmente uma rota muito comum, a estrutura do MVC-Servcie-Dao-Hibernate, o código-fonte pode ser baixado, observe principalmente o arquivo de configuração. Veja os comentários para explicação
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" xmlns: web = "http://java.sun.com/xml/ns/javaee/web-app_2.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" = "2.5">> <name> <lmed-File> index.jsp </ld-welcome-file> </list-fil-list> <!-Configurar Spring-> <Context-Param> <Maam-Name> contextConfigLocation </amam-Name> <amam-value> ClassPath*: config/spring-*. <Ilvier-class> org.springframework.web.context.contextLoaderListener </lister-class> </ouvinte> <!-Configure springmvc-> <ervlet> <servlet-name> springmvc </servlet> <ervlet-class> org.springfringfringweb.web.web.web.web.werbring.web.web.web.werbring.web.web.web.web.wertlet> servlet-class </classTringfamebrweb.web.web.web.web.werbl. <iit-param> <amam-name> contextConfigLocation </param-name> <amam-value> ClassPath*: config/spring-ervlet.xml </param-value> </irit-param> <adlet-on-startp> 1 </load-on-startup> </servlet> <ar Servlet-mapping> <arletname> Springmv. </servlet-mapping> <!-Definir conjunto de caracteres-> <filter> <filter-name> EncodingFilter </ftrid-Name> <filter-Class> org.springframework.web.filter.characterenCodingfilter </filter-class> <iit-param> <tam-name> </paramname> <iit-param> <amam-name> forcencoding </amam-name> <amam-value> true </amam-value> </irit-param> </ftruter> <filter-Mapping> <filter-name> codingfilter </filter-name> <url-stattern>/*</url-tattern> </filter-mapping> switch para shuttning para controlar <erl-Pattern>/*</url-stattern> </filter-mapping> switch> shittle para controlar <rlting> <erl-Pattern>/*</url> <filter-Class> org.springframework.orm.hibernate4.support.opensessionInViewFilter </filter-Class> </ftrhter> <filter-Mapping> <filter-name> Open-Name </filter-Name> <url-Pattern>/*</url-tattern> </filter-mapping> </web-App>
spring-servlet.xml
<? xml versão = "1.0" coding = "utf-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: context = "http://wwwxt.springframework.org/schema =" http://wwwx. xmlns: p = "http://www.springframework.org/schema/p" xmlns: mvc = "http://www.springframework.org/schema/mvc" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "> <!-Anotation Package-> <Contexto: componente-scan-Pack-Pack-Packsd"> <! <!-Método de anotação Processamento-> <!-<Bean/>-> <!-Processamento de mapeamento da classe de anotação-> <!-<Bean> </i Bean>-> <!-Open Scheme de anotação 2-> <mvc: annotation-driven/> <! <MVC: Recursos Location = "/JS/" Mapping = "/JS/**"/> <!-Acesso de Recursos estáticos, Esquema 2-> <!-<MVC: Padrão-Servlet-Handler/>-> <!-Visualizar classe de interpretação-> <Bean Id = "ViewResolver"> <Paise) <!-Prefix " A classe de interpretação da exibição com base na sua extensão-> <propriedade name = "sufix" value = ". name = "maxinMemorySize" value = "40960"/> </sien> -> </ Beans>
spring-hibernate.xml
<? xml versão = "1.0" coding = "utf-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: context = "http://wwwxt.springframework.org/schema =" http://wwwx. xmlns: p = "http://www.springframework.org/schema/p" xmlns: mvc = "http://www.springframework.org/schema/mvc" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "> <! value = "com.mysql.jdbc.driver" /> <propriedade name = "url" value = "jdbc: mysql: //127.0.0.1/springmvc" /> <nome da propriedade = "nome do usuário" /"root" /> <names = "senha" "=" 12346 " <bean id = "sessionFactory"> <propriedade name = "DataSource" ref = "DataSource"/> <Propriedade name = "hibernateProperties"> <ports> <props key = "hibernate.dialect"> org.hibernate.dialect.mysqldialect </prop> <phance = "hibernate.hibernate.dialect.mysqldialect </prop> <phance =" hibernate " key = "hibernate.show_sql"> true </prop> <prop) </prop> </property> <names name = "configlocations"> <list> <Value> ClassPath*: config/hibernate/hibernate.cfg.xml> Gerenciador-> <bean id = "transactionManager"> <propriedade name = "sessionFactory" ref = "sessionFactory"> </Property> </bean> <!-Class de agente de transação-> <bean id = "transactionBese" lazy-init = "true" abstrato = "true"> <propriedades = "namesmanager" "=" transactmanager = "true"> </"> <weead) <namesanager" (transactomanager = "true"> "> key = "Add*"> propagation_required, -exception </pp> <props key = "update*"> propagation_required, -exception </prop> <prop key = "insert*"> propagation_required, -exception </prop> <prop> key = "insert*"> propagoud_required, -Exception </prop. key = "Modify*"> propagation_required, -exception </prop> <props key = "modify*"> propagation_required, -exception </prop> <propl key = "delete*"> propagation_required, -exception </prop> <ppy = "del*"> propagation_reQuired, -Exception </prop. </sports> </propriedade> </shean> </ Beans>
spring-core.xml
<? xml versão = "1.0" coding = "utf-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: context = "http://wwwxt.springframework.org/schema =" http://wwwx. xmlns: p = "http://www.springframework.org/schema/p" xmlns: mvc = "http://www.springframework.org/schema/mvc" 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.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd "> <! </ Beans>
Spring-user.xml
<? xml versão = "1.0" coding = "utf-8"?> <! "Org/springframework/web/context/web-inf/contextinclude.xml">]> <Beans> <!-spring bean-> <bean id = "userdao"> <propriedades name = "sessionFactory" ref = "sessionFactory"> </propriedade> </bean> <bean id = "userManagerBase">> </bean> <!-Pai é transmission, indicando que as transações são suportadas-> <bean id = "userManager" parent = "transactionBese"> <propriedade name = "Target" Ref = "UserManagerBase"> </Property> </shean> </ Beans>
hibernate.cfg.xml
<! Doctype Hibernate-Configuration public "-// Configuração de Hibernate/Hibernato DTD 3.0 // pt" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configurature> <Session-fligaturation-3.0. <Mapping/> </session-factory> </Hibernate-Configuration>
Vamos dar uma olhada no controlador
pacote com.jialin.Controller; importar java.io.ioException; importar java.io.printwriter; importar java.util.list; importar javax.annotation.resource; importar javax.servlet.http.httpServletRequest; importar javax.servlet.http.httpServletResponse; importar org.springframework.tereotype.controller; importar org.springframework.web.bind.annotation.requestmapping; importação com.jianin.entity.User; importação com.jianin.service.userManager; @Controller // Action-struts-Like @RequestMapping ("/User") classe pública UserController {@Resource (name = "UserManager") // Obtenha o ID do Bean no arquivo de configuração da primavera como UserManager e injete private iUserManager UserManager; @RequestMapping ("/adduser") // Solicite o mapeamento de endereço do URL, semelhante ao public string public string adduser (usuário) {if (userManager.adduser (usuário)) {// redirect retornar "redirect:/user/getalluser"; } else {return "/falha"; }} @ReQuestMapping ("/updateUser") public String UpdateUser (usuário do usuário, httpServletRequest request) {if (userManager.UpDateUser (user)) {user = userManager.getOneUser (usuário); request.setAttribute ("Usuário", usuário); retornar "/userEdit"; } else {return "/falha"; }} @RequestMapping ("/deluser") public void deluser (usuário do usuário, httpServletResponse resposta) {string result = "{/" resultado/":/" error/"}"; if (userManager.delUser (user)) {resultado = "{/" resultado/":/" success/"}"; } PrintWriter Out = null; Response.setContentType ("Application/JSON"); tente {out = Response.getWriter (); out.write (resultado); } catch (ioexception e) {e.printStackTrace (); }} @ReQuestMapping ("/toadduser") public String toadduser () {return "/userAdd"; } @RequestMapping ("/ToupDateUser") public String ToupDateUser (usuário do usuário, httpServletRequest Request) {user user1 = userManager.getOneUser (usuário); request.setAttribute ("user1", user1); retornar "/userEdit"; } @ReQuestMapping ("/getAlLUser") public string getAllUser (httpServletRequest Request) {list UserList = userManager.getAllUser (); request.setAttribute ("userlist", userlist); retornar "/UserMain"; }}Download do código -fonte ...
O exposto acima é todo o conteúdo deste artigo. Espero que seja útil para o aprendizado de todos e espero que todos apoiem mais o wulin.com.