springmvc 주해 설정 예 인 스 턴 스 코드 다운로드

오리지널 정리 가 쉽 지 않 습 니 다. 전재 출처 를 밝 혀 주세요. springmvc 주해 설정 예 인 스 턴 스 코드 다운로드
코드 다운로드 주소: http://www.zuidaima.com/share/1751860180044800.htm
글 에서 사용 하 는 프레임 워 크 버 전: spring 3, hibenate 3, 없 는 것 은 스스로 인터넷 에 접속 합 니 다.
웹. 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 " 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> </load - on - startup> 
 </servlet> 
 <servlet - mapping> 
 <servlet - name> spring </servlet - name> 
<!--      spring,         spring - servlet.xml   ,        controller --> 
 <url - pattern>* . do </url - pattern> 
 </servlet - mapping> 
 <welcome - file - list> 
 <welcome - file> index.jsp </welcome - file> 
 </welcome - file - list> 
 </web - app> 


 
spring - servlet, 주요 설정 controller 정보
<?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:context="http://www.springframework.org/schema/context" 
 xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://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 /> 
 <!--     @Controller       bean --> 
 <context:component-scan base-package="com.mvc.controller" /> 
 <!--   Spring MVC     ,       POJO    --> 
 <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> 
 
 <!--           ,              --> 
 <bean class="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 코드
<?xml version="1.0"encoding="UTF-8"?> 
 <beans xmlns="http://www.springframework.org/schema/beans" 
 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" /> <!--             --> 
 
 <context:property-placeholder location="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> <!--      ,        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    --> 
 <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> 


 
hibenate. properties 데이터베이스 연결 설정
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};password=${dataSource.password} 
dataSource.hbm2ddl.auto=update 


 
설정 이 완료 되 었 습 니 다. 다음 시작 예 는 데이터베이스 에 표를 만 듭 니 다. 예 는 my sql 데이터 베 이 스 를 사용 합 니 다.
CREATE TABLE `test`.`student` ( 
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT, 
 `name` varchar(45) NOT NULL, 
 `psw` varchar(45) NOT NULL, 
 PRIMARY KEY (`id`) 
) 


 
시 계 를 만 든 후 실체 류 를 생 성 합 니 다.
packagecom.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) 
 private 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() { 
 return user; 
 } 
 public void setUser(String user) { 
 this.user=user; 
 } 
 public String getPsw() { 
 return psw; 
 } 
 public void setPsw(String psw) { 
 this.psw= psw; 
 } 
} 


Dao 층 실현
package com.mvc.dao; 
 
 import java.util.List; 
 
 public interface EntityDao { 
 public List<Object> createQuery(final String queryString); 
 public Object save(final Object 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; 
 } 
 }); 
 } 
 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; 
 } 
 }); 
 } 
 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 는 applicationContext. xml 에 주입 합 니 다.
<bean id="entityDao" class="com.mvc.dao.EntityDaoImpl"> 
 <property name="sessionFactory" ref="sessionFactory" /> 
 </bean> 



 
Dao 는 한 가지 유형의 실현 만 있 습 니 다. 다른 service 층 에서 직접 호출 할 수 있 습 니 다. 다른 Dao 로 바 꾸 려 면 이 설정 만 수정 하면 됩 니 다.view 페이지 를 쓰기 시작 합 니 다. WEB - INF / view 아래 새 페이지 student. jsp, WEB - INF / view 경 로 는 spring - servlet. xml 파일 에 설정 되 어 있 습 니 다. 다른 경로 로 설정 할 수도 있 고 여러 경로 로 설정 할 수도 있 습 니 다.student. 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"> 
 <html> 
 <head> 
 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> 
 <title>    </title> 
 <script language="javascript" src="<%=request.getContextPath()%><!-- 
/script/jquery.min.js">  
// --></script> 
<style><!-- 
table{ border-collapse:collapse; } 
td{ border:1px solid #f00; } 
--></style><style mce_bogus="1">table
         
                           
         

 
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"> 
 <html> 
 <head> 
 <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> 
 <title>      </title> 
 <mce:script type="text/javascript"><!-- 
function turnback(){ 
 window.location.href="<%=request.getContextPath()%>/student.do"; 
} 
// --> </mce:script> 
 </head> 
 <body> 
 <form method="post" action="<%=request.getContextPath()%>/student.do?method=save"> 
 <div><c:out value="${addstate}"></c:out></div> 
 <table> 
 <tr><td>    </td><td><input id="user" name="user" type="text" /></td></tr> 
 <tr><td>    </td><td><input id="psw" name="psw" type="text" /></td></tr> 
 <tr><td colSpan="2" align="center"><input type="submit" value="  "/><input type="button" onclick="turnback()" value="  " /> </td></tr> 
 </table> 
 
 </form> 
 </body> 
 </html> 


 
controller 클래스 가 실 현 됩 니 다. 주 해 를 적 으 면 spring 은 자동 으로 해당 하 는 bean 을 찾 아 줍 니 다. 해당 하 는 주해 표시 의 미 를 알 수 없습니다. 모 르 는 것 은 @ Service, @ Controller, @ Entity 등 내용 을 스스로 찾 아 볼 수 있 습 니 다.
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 Exception{ 
 return "student_add"; 
 } 
 
 @RequestMapping(params="method=save") 
 public String save(HttpServletRequest request, ModelMap 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", "    "); 
 } 
 catch(Exception e){ 
 log.error(e.getMessage()); 
 modelMap.put("addstate", "    "); 
 } 
 
 return "student_add"; 
 } 
 
 @RequestMapping(params="method=del") 
 public void del(@RequestParam("id") String id, HttpServletResponse response){ 
 try{ 
 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(); 
 } 
 } 
} 


 
서비스 클래스 구현
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> getStudentList(){ 
 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, 예 를 다 썼 습 니 다.다른 업무 내용 이 있 습 니 다. view 를 직접 새로 만 들 고 해당 comtroller 와 service 를 실현 하면 됩 니 다. 설정 과 dao 층 의 내용 은 기본적으로 변 하지 않 습 니 다. 즉, 매번 jsp (view), contrller 와 service 가 dao 를 호출 하면 됩 니 다.
어 때, 이 걸 보 니, spring mvc 가 ssh 보다 더 편리 하고 유연 하지 않 아?
첨부 파일 원본: s3h 

좋은 웹페이지 즐겨찾기