spring3.1 mvc+spring
學習了一段時間的spring mvc,個人覺得在配置方面相比struts更為簡單。RESTful URL、幾乎0配置、不需要實現任何接口或繼承任何類的Controller、方法級別的攔截,一個方法對應一個url、靈活的方法參數和返回值、多種view、處理ajax的請求更是方便...
lib 如下:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <filter> <filter-name>encodingFilter</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>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>*.htm</url-pattern> </filter-mapping> <servlet> <servlet-name>spring3</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spring3</servlet-name> <url-pattern>*.htm</url-pattern> </servlet-mapping> <error-page> <error-code>404</error-code> <location>/error/e-404.html</location> </error-page> <error-page> <error-code>500</error-code> <location>/error/e-500.jsp</location> </error-page> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app></strong>
子上下文文件聲明:
1、不寫,使用默認值:/WEB-INF/<servlet-name>-servlet.xml
2、<param-value>/WEB-INF/classes/springMVC.xml</param-value>
3、<param-value>classpath*:springMVC-mvc.xml</param-value>
4、多個值用逗號分隔
注:我們這里默認/WEB-INF/spring3-servlet.xml
</span>
父子上下文說明:
Spring會創建一個WebApplicationContext上下文,稱為父上下文(父容器) ,保存在 ServletContext中,key是WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE的值。
可以使用Spring提供的工具類取出上下文對象:WebApplicationContextUtils.getWebApplicationContext(ServletContext);
DispatcherServlet是一個Servlet,可以同時配置多個,每個 DispatcherServlet有一個自己的上下文對象(WebApplicationContext),稱為子上下文(子容器),子上下文可以訪問父上下文中的內容,但父上下文不能訪問子上下文中的內容。 它也保存在 ServletContext中,key是"org.springframework.web.servlet.FrameworkServlet.CONTEXT"+Servlet名稱。當一個Request對象產生時,會把這個子上下文對象(WebApplicationContext)保存在Request對象中,key是DispatcherServlet.class.getName() + ".CONTEXT"。
可以使用工具類取出上下文對象:RequestContextUtils.getWebApplicationContext(request);
說明 :Spring 并沒有限制我們,必須使用父子上下文。我們可以自己決定如何使用。我們這里用的是自上下文。
上下文配置:
<beans xmlns="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
</beans> </pre>
spring也支持了jndi(這里就不再講解jndi了):
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiName"> <value>myTestDataSource</value> </property> <!-- 如果你不想使用 'java:comp/env/'前綴的話請設置下面的值為true, 默認值為false --> <property name="resourceRef"> <value>false</value> </property> </bean>好了到這里我們的配置基本上就完了。。在編寫業務代碼前還有一些知識需要大家去學習一下:
<p>@Controller 聲明Action組件
常用注解:
@Service 聲明Service組件 @Service("myMovieLister")
@Repository 聲明Dao組件
@Component 泛指組件, 當不好歸類時.
@RequestMapping("/menu") 請求映射
@Resource 用于注入,( j2ee提供的 ) 默認按名稱裝配,@Resource(name="beanName")
@Autowired 用于注入,(srping提供的) 默認按類型裝配
@Transactional( rollbackFor={Exception.class}) 事務管理
@ResponseBody
@Scope("prototype") 設定bean的作用域
contorller代碼:</p>package com.springdemo.module.usermgr.controller;import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView;
import com.springdemo.core.ActionException; import com.springdemo.core.BaseContoller; import com.springdemo.core.ServiceException; import com.springdemo.module.usermgr.service.UserMgrService; import com.springdemo.module.usermgr.vo.SUser; /**
- 用戶登錄管理
- @author joe
@date 2011-10-24 下午03:34:39 */ @Controller public class UserLoginMgr extends BaseContoller{ @Autowired private UserMgrService userMgrService;
@RequestMapping(value="saveLogin.htm",method=RequestMethod.POST) public ModelAndView saveLogin(HttpSession session,SUser user,ModelMap modelMap){
if(user!=null){ String userName = user.getUserName(); try { SUser dbuser = userMgrService.getUserByUserName(userName); if(dbuser==null){ //成功后重定向的歡迎界面,防止重復提交 return new ModelAndView("login",COMMON_FAIL_ALERT_KEY,"用戶不存在!"); } if(!dbuser.getPwd().equals(user.getPwd())){ return new ModelAndView("login",COMMON_FAIL_ALERT_KEY,"密碼錯誤!"); } session.setAttribute(USER_SESSION_KEY, dbuser); } catch (ServiceException e) { e.printStackTrace(); } } //成功后重定向的歡迎界面,防止重復提交 return new ModelAndView("redirect:login_succ.htm");
} //獲取 @RequestMapping(value="get/{id}.htm",method=RequestMethod.GET) public ModelAndView get(@PathVariable Integer id) throws Exception{
SUser sUser = userMgrService.getUserById(id); if(sUser==null){ throw new ActionException("用戶["+id+"]不存在!"); } return new ModelAndView("user_detail","user",sUser);
} //列表 @RequestMapping(value="list.htm",method=RequestMethod.GET) public ModelAndView list() throws ServiceException{
List<SUser> users = userMgrService.getUsers(); return new ModelAndView("/test/user_list","users",users);
} //注冊成功 @RequestMapping(value="login_succ.htm") public String signuoSucc(HttpSession session,ModelMap map){
SUser user = (SUser) session.getAttribute(USER_SESSION_KEY); if(user==null){ return "redirect:login.htm"; } map.put("user", user); return "index";
} @RequestMapping("logout.htm") public String logout(HttpSession session){
session.invalidate(); return "redirect:login.htm";
} //首頁 @RequestMapping(value="index.htm") public String index(){
return "forward:login_succ.htm";
} }</pre>
service代碼:
package com.springdemo.module.usermgr.service;import java.util.Date; import java.util.List;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.dao.EmptyResultDataAccessException; import org.springframework.stereotype.Service;
import com.springdemo.core.BaseService; import com.springdemo.core.ServiceException; import com.springdemo.module.usermgr.dao.UserMgrDao; import com.springdemo.module.usermgr.vo.SUser; @Service("userMgrService") public class UserMgrService extends BaseService{
@Autowired private UserMgrDao userMgrDao; public void signUp(SUser user) throws ServiceException{ try { user.setSignUpTime(new Date()); userMgrDao.addUser(user); } catch (Exception e) { throw new ServiceException("注冊失敗", e); } } public SUser getUserById(Integer id) throws ServiceException{ try { return userMgrDao.getUserByColunm("id",id); } catch (Exception e) { throw new ServiceException("獲取失敗", e); } } public List<SUser> getUsers() throws ServiceException{ try { return userMgrDao.getUsers(); } catch (Exception e) { throw new ServiceException("獲取失敗", e); } } public SUser getUserByUserName(String userName) throws ServiceException { try { return userMgrDao.getUserByColunm("userName",userName); } catch (Exception e) { if(e instanceof EmptyResultDataAccessException){ return null; } throw new ServiceException("獲取失敗", e); } }
}</pre>
model 代碼:
package com.springdemo.module.usermgr.dao;import java.util.List;
import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.stereotype.Repository;
import com.springdemo.core.BaseDao; import com.springdemo.module.usermgr.vo.SUser;
@Repository("userMgrDao") @SuppressWarnings("unchecked") public class UserMgrDao extends BaseDao{
public SUser addUser(final SUser sUser){ sUser.setId(super.saveAndReturnKey(sUser).intValue()); return sUser; } public List<SUser> getUsers() { return getJdbcTemplate().query("select * from suser", new BeanPropertyRowMapper(SUser.class)); } public SUser getUserByColunm(String columnName, Object value) { return getJdbcTemplate().queryForObject("select * from suser where "+columnName+"=?", new BeanPropertyRowMapper(SUser.class),value); }
}</pre>
jap 代碼:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <body> <h3>用戶登錄</h3> ${fail_key }<br/> <form action="<%=request.getContextPath() %>/saveLogin.htm" method="post"> username:<input type="text" name="userName" ><br/> password:<input type="password" name="pwd"/><br/> <input type="submit"/> </form> <br/> <a href="javascript:void(0);" onclick="javascript:self.location='<%=request.getContextPath() %>/usermgr/signup.htm'">注冊</a> </body> </html></pre>這里附件太大 有需要實例的留郵箱~</div> </span></span></span>