好看的亚洲午夜视频在线,在线视频中文字幕久,日韩制服丝袜先锋影音http://www.aygfsteel.com/paulwong/category/50899.htmlzh-cnSun, 02 Nov 2014 09:56:26 GMTSun, 02 Nov 2014 09:56:26 GMT60springMVC 文件下載http://www.aygfsteel.com/paulwong/archive/2014/10/29/419177.htmlpaulwongpaulwongWed, 29 Oct 2014 09:17:00 GMThttp://www.aygfsteel.com/paulwong/archive/2014/10/29/419177.htmlhttp://www.aygfsteel.com/paulwong/comments/419177.htmlhttp://www.aygfsteel.com/paulwong/archive/2014/10/29/419177.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/419177.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/419177.htmlimport java.io.File;  
import java.io.IOException;  
  
import org.apache.commons.io.FileUtils;  
import org.springframework.context.annotation.Scope;  
import org.springframework.http.HttpHeaders;  
import org.springframework.http.HttpStatus;  
import org.springframework.http.MediaType;  
import org.springframework.http.ResponseEntity;  
import org.springframework.stereotype.Component;  
import org.springframework.web.bind.annotation.RequestMapping;  
  
/** 
 * <一句話功能簡述> 
 * <功能詳細描述> 
 *  
 * 
@author  Administrator 
 * 
@version  [版本號, 2014年3月7日] 
 * 
@see  [相關(guān)類/方法] 
 * 
@since  [產(chǎn)品/模塊版本] 
 
*/  
@Component  
@Scope("prototype")   
@RequestMapping("/downloadFile")  
public class DownloadAction  
{  
  
    @RequestMapping("download")    
    public ResponseEntity<byte[]> download() throws IOException {    
        String path="D:\\workspace\\.metadata\\.plugins\\org.eclipse.wst.server.core\\tmp0\\wtpwebapps\\springMVC\\WEB-INF\\upload\\圖片10(定價后).xlsx";  
        File file=new File(path);  
        HttpHeaders headers = new HttpHeaders();    
        String fileName=new String("你好.xlsx".getBytes("UTF-8"),"iso-8859-1");//為了解決中文名稱亂碼問題  
        headers.setContentDispositionFormData("attachment", fileName);   
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),    
                                          headers, HttpStatus.CREATED);    
    }    
}  

JSP
<href="./downloadFile/download" >下載</a>  


paulwong 2014-10-29 17:17 發(fā)表評論
]]>
Spring對HttpSession的重新封閉http://www.aygfsteel.com/paulwong/archive/2014/08/19/417090.htmlpaulwongpaulwongTue, 19 Aug 2014 01:13:00 GMThttp://www.aygfsteel.com/paulwong/archive/2014/08/19/417090.htmlhttp://www.aygfsteel.com/paulwong/comments/417090.htmlhttp://www.aygfsteel.com/paulwong/archive/2014/08/19/417090.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/417090.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/417090.htmlhttps://github.com/spring-projects/spring-session/tree/master/samples

paulwong 2014-08-19 09:13 發(fā)表評論
]]>
Spring Data REST,Spring MVC的REST擴展http://www.aygfsteel.com/paulwong/archive/2014/07/09/415635.htmlpaulwongpaulwongWed, 09 Jul 2014 09:36:00 GMThttp://www.aygfsteel.com/paulwong/archive/2014/07/09/415635.htmlhttp://www.aygfsteel.com/paulwong/comments/415635.htmlhttp://www.aygfsteel.com/paulwong/archive/2014/07/09/415635.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/415635.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/415635.htmlhttp://spring.io/blog/2012/06/26/spring-data-rest-1-0-0-rc1-released

RESTify your JPA Entities
https://www.openshift.com/blogs/restify-your-jpa-entities

babdev-spring
https://github.com/gregorriegler/babdev-spring/tree/master/spring-data-rest

https://github.com/spring-projects/spring-data-rest

paulwong 2014-07-09 17:36 發(fā)表評論
]]>
基于springMVC+springSecurity3.x+Mybaits3.x的權(quán)限系統(tǒng)http://www.aygfsteel.com/paulwong/archive/2013/11/24/406757.htmlpaulwongpaulwongSun, 24 Nov 2013 12:54:00 GMThttp://www.aygfsteel.com/paulwong/archive/2013/11/24/406757.htmlhttp://www.aygfsteel.com/paulwong/comments/406757.htmlhttp://www.aygfsteel.com/paulwong/archive/2013/11/24/406757.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/406757.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/406757.htmlhttps://github.com/lanyuancom/lanyuan @import url(http://www.aygfsteel.com/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);

paulwong 2013-11-24 20:54 發(fā)表評論
]]>
SPRING各種例子http://www.aygfsteel.com/paulwong/archive/2013/11/11/406213.htmlpaulwongpaulwongMon, 11 Nov 2013 06:44:00 GMThttp://www.aygfsteel.com/paulwong/archive/2013/11/11/406213.htmlhttp://www.aygfsteel.com/paulwong/comments/406213.htmlhttp://www.aygfsteel.com/paulwong/archive/2013/11/11/406213.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/406213.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/406213.htmlhttps://github.com/skprasadu/spring-mvc-rest


spring-mvc-examples
https://github.com/skprasadu/spring-mvc-examples


spring-security-examples
https://github.com/skprasadu/spring-security-examples


pro-spring-mvc-code
https://github.com/mdeinum/pro-spring-mvc-code












paulwong 2013-11-11 14:44 發(fā)表評論
]]>
SPRINGMVC增加LOGBACKhttp://www.aygfsteel.com/paulwong/archive/2013/11/11/406209.htmlpaulwongpaulwongMon, 11 Nov 2013 05:44:00 GMThttp://www.aygfsteel.com/paulwong/archive/2013/11/11/406209.htmlhttp://www.aygfsteel.com/paulwong/comments/406209.htmlhttp://www.aygfsteel.com/paulwong/archive/2013/11/11/406209.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/406209.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/406209.html
<dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jcl-over-slf4j</artifactId>
        <version>1.7.2</version>      
</dependency>
      
<dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.0.9</version>      
</dependency>


web.xml
<!-- spring logback -->  
<context-param>  
    <param-name>logbackConfigLocation</param-name>  
    <param-value>classpath:logback.xml</param-value>  
</context-param>    
<listener>  
    <listener-class>mypackage.LogbackConfigListener</listener-class>  
</listener>  


logback.xml
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>

    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.FileAppender">
        <file>bookstore.log</file>
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
            </pattern>
        </encoder>
    </appender>

    <logger name="org.springframework" level="INFO" />
    <logger name="org.springframework.web" level="INFO" />


    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <!-- <appender-ref ref="FILE" /> -->
    </root>

</configuration>



LogbackConfigurer.java
import java.io.File;
import java.io.FileNotFoundException;
import java.net.URL;

import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;
import org.springframework.util.SystemPropertyUtils;

import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.joran.JoranConfigurator;
import ch.qos.logback.core.joran.spi.JoranException;


public abstract class LogbackConfigurer {

    /** Pseudo URL prefix for loading from the class path: "classpath:" */
    public static final String       CLASSPATH_URL_PREFIX = "classpath:";

    /** Extension that indicates a logback XML config file: ".xml" */
    public static final String       XML_FILE_EXTENSION   = ".xml";

    private static LoggerContext     lc                   = (LoggerContext) LoggerFactory.getILoggerFactory();
    private static JoranConfigurator configurator         = new JoranConfigurator();

    /**
     * Initialize logback from the given file location, with no config file refreshing. Assumes an XML file in case of a ".xml" file extension, and a properties file otherwise.
     * 
     * 
@param location
     *            the location of the config file: either a "classpath:" location (e.g. "classpath:mylogback.properties"), an absolute file URL (e.g. "file:C:/logback.properties), or a plain absolute path in the file system (e.g. "C:/logback.properties")
     * 
@throws FileNotFoundException
     *             if the location specifies an invalid file path
     
*/
    public static void initLogging(String location) throws FileNotFoundException {
        String resolvedLocation = SystemPropertyUtils.resolvePlaceholders(location);
        URL url = ResourceUtils.getURL(resolvedLocation);
        if (resolvedLocation.toLowerCase().endsWith(XML_FILE_EXTENSION)) {
//            DOMConfigurator.configure(url);
            configurator.setContext(lc);
            lc.reset();
            try {
                configurator.doConfigure(url);
            } catch (JoranException ex) {
                throw new FileNotFoundException(url.getPath());
            }
            lc.start();
        }
//        else {
//            PropertyConfigurator.configure(url);
//        }
    }

    /**
     * Shut down logback, properly releasing all file locks.
     * <p>
     * This isn't strictly necessary, but recommended for shutting down logback in a scenario where the host VM stays alive (for example, when shutting down an application in a J2EE environment).
     
*/
    public static void shutdownLogging() {
        lc.stop();
    }

    /**
     * Set the specified system property to the current working directory.
     * <p>
     * This can be used e.g. for test environments, for applications that leverage logbackWebConfigurer's "webAppRootKey" support in a web environment.
     * 
     * 
@param key
     *            system property key to use, as expected in logback configuration (for example: "demo.root", used as "${demo.root}/WEB-INF/demo.log")
     * 
@see org.springframework.web.util.logbackWebConfigurer
     
*/
    public static void setWorkingDirSystemProperty(String key) {
        System.setProperty(key, new File("").getAbsolutePath());
    }

}


LogbackWebConfigurer.java
import java.io.FileNotFoundException;

import javax.servlet.ServletContext;

import org.springframework.util.ResourceUtils;
import org.springframework.util.SystemPropertyUtils;
import org.springframework.web.util.WebUtils;

public abstract class LogbackWebConfigurer {

    /** Parameter specifying the location of the logback config file */
    public static final String CONFIG_LOCATION_PARAM     = "logbackConfigLocation";

    /** Parameter specifying the refresh interval for checking the logback config file */
    public static final String REFRESH_INTERVAL_PARAM    = "logbackRefreshInterval";

    /** Parameter specifying whether to expose the web app root system property */
    public static final String EXPOSE_WEB_APP_ROOT_PARAM = "logbackExposeWebAppRoot";

    /**
     * Initialize logback, including setting the web app root system property.
     * 
     * 
@param servletContext
     *            the current ServletContext
     * 
@see WebUtils#setWebAppRootSystemProperty
     
*/
    public static void initLogging(ServletContext servletContext) {
        // Expose the web app root system property.
        if (exposeWebAppRoot(servletContext)) {
            WebUtils.setWebAppRootSystemProperty(servletContext);
        }

        // Only perform custom logback initialization in case of a config file.
        String location = servletContext.getInitParameter(CONFIG_LOCATION_PARAM);
        if (location != null) {
            // Perform actual logback initialization; else rely on logback's default initialization.
            try {
                // Return a URL (e.g. "classpath:" or "file:") as-is;
                
// consider a plain file path as relative to the web application root directory.
                if (!ResourceUtils.isUrl(location)) {
                    // Resolve system property placeholders before resolving real path.
                    location = SystemPropertyUtils.resolvePlaceholders(location);
                    location = WebUtils.getRealPath(servletContext, location);
                }

                // Write log message to server log.
                servletContext.log("Initializing logback from [" + location + "]");

                // Initialize without refresh check, i.e. without logback's watchdog thread.
                LogbackConfigurer.initLogging(location);

            } catch (FileNotFoundException ex) {
                throw new IllegalArgumentException("Invalid 'logbackConfigLocation' parameter: " + ex.getMessage());
            }
        }
    }

    /**
     * Shut down logback, properly releasing all file locks and resetting the web app root system property.
     * 
     * 
@param servletContext
     *            the current ServletContext
     * 
@see WebUtils#removeWebAppRootSystemProperty
     
*/
    public static void shutdownLogging(ServletContext servletContext) {
        servletContext.log("Shutting down logback");
        try {
            LogbackConfigurer.shutdownLogging();
        } finally {
            // Remove the web app root system property.
            if (exposeWebAppRoot(servletContext)) {
                WebUtils.removeWebAppRootSystemProperty(servletContext);
            }
        }
    }

    /**
     * Return whether to expose the web app root system property, checking the corresponding ServletContext init parameter.
     * 
     * 
@see #EXPOSE_WEB_APP_ROOT_PARAM
     
*/
    private static boolean exposeWebAppRoot(ServletContext servletContext) {
        String exposeWebAppRootParam = servletContext.getInitParameter(EXPOSE_WEB_APP_ROOT_PARAM);
        return (exposeWebAppRootParam == null || Boolean.valueOf(exposeWebAppRootParam));
    }

}


LogbackConfigListener.java
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class LogbackConfigListener implements ServletContextListener {

    public void contextInitialized(ServletContextEvent event) {
        LogbackWebConfigurer.initLogging(event.getServletContext());
    }

    public void contextDestroyed(ServletContextEvent event) {
        LogbackWebConfigurer.shutdownLogging(event.getServletContext());
    }
}





paulwong 2013-11-11 13:44 發(fā)表評論
]]>
spring3MVC+JSONhttp://www.aygfsteel.com/paulwong/archive/2012/05/18/378452.htmlpaulwongpaulwongThu, 17 May 2012 16:14:00 GMThttp://www.aygfsteel.com/paulwong/archive/2012/05/18/378452.htmlhttp://www.aygfsteel.com/paulwong/comments/378452.htmlhttp://www.aygfsteel.com/paulwong/archive/2012/05/18/378452.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/378452.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/378452.html <!-- 自動解析action返回值 解析成json格式 -->
<context:component-scan base-package="com.bplow.*.web" />  
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />  
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >  
    
<property name="messageConverters">  
        
<util:list id="beanList">  
            
<ref bean="mappingJacksonHttpMessageConverter"/>  
        
</util:list>  
    
</property>  
</bean>  
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
    
<property name="supportedMediaTypes">  
        
<list>  
            
<value>text/html;charset=UTF-8</value>  
        
</list>  
    
</property>  
</bean>  
<!-- 自動解析action返回值 解析成json格式 -->
然后需要額外的jar包 jackson 1.1,這里讓我很無語,我首先下的1.9放上去什么方法找不到,換1.8x 方法找不到 我一直試到1.6 后來怒了用最老的 好了。。。坑,這絕對是坑啊

然后你的action中直接返回對象,集合,map吧 非常爽啊。測試如下





package com.bplow.test.web;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class TestAction {

// ResponseBody 對應(yīng)string則對應(yīng)ajax getText
@RequestMapping(value = "/testAction", method = RequestMethod.GET)
@ResponseBody
public String allOnActivities() throws UnsupportedEncodingException {

return "{'title':'HelloWorldGOGOGO'}";
}


@RequestMapping(value
= "/testAction2", method = RequestMethod.GET)
@ResponseBody
public TestVo getJsonVo() {

TestVo vo
= new TestVo();
vo.setTitle(
"吃吧");
return vo;
}


@RequestMapping(value
= "/testAction3", method = RequestMethod.GET)
@ResponseBody
public List getJsonList() {

TestVo vo
= new TestVo();
vo.setTitle(
"吃吧");
List l
= new LinkedList();
l.add(vo);
l.add(vo);
l.add(vo);
l.add(vo);
l.add(vo);
return l;
}


@RequestMapping(value
= "/testAction4", method = RequestMethod.GET)
@ResponseBody
public Map getMap() {

TestVo vo
= new TestVo();
vo.setTitle(
"吃吧");
HashMap hsm
= new HashMap();
hsm.put(
"a", 123);
hsm.put(
"b", "123");
hsm.put(
"c", vo);
return hsm;
}

}


paulwong 2012-05-18 00:14 發(fā)表評論
]]>
開始Spring MVChttp://www.aygfsteel.com/paulwong/archive/2012/03/29/373004.htmlpaulwongpaulwongThu, 29 Mar 2012 11:06:00 GMThttp://www.aygfsteel.com/paulwong/archive/2012/03/29/373004.htmlhttp://www.aygfsteel.com/paulwong/comments/373004.htmlhttp://www.aygfsteel.com/paulwong/archive/2012/03/29/373004.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/373004.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/373004.html
  <servlet>
    
<servlet-name>dispatcher</servlet-name>
    
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    
<init-param>
        
<param-name>contextConfigLocation</param-name>
<!-- 如果配置文件位于classpath下,可以這么寫: classpath:dispatcher.xml -->
        
<param-value>/WEB-INF/dispatcher.xml</param-value>
    
</init-param>
    
<load-on-startup>1</load-on-startup>
  
</servlet>

  
<servlet-mapping>
    
<servlet-name>dispatcher</servlet-name>
    
<url-pattern>/</url-pattern>
  
</servlet-mapping>

注:由于DispatcherServlet在初始化的過程中需要一個配置文件來生產(chǎn)文件中的各種bean,并生成WebApplicationContext對象,保存到ServletContext中(如果DispatcherServlet有多個,那么每一個DispatcherServlet都對應(yīng)一個WebApplicationContext),我們可以在Servlet的init-param中配置配置文件的路徑,當(dāng)然如果我們沒有配置Init-Param,它會默認(rèn)到WEB-INF的文件夾中找[servletname]-servlet.xml文件,例如上面如果我們沒有配置,則會去尋找dispatcher-servlet.xml這個配置文件。(在init-param中我們可以指定多個配置文件,用逗號分隔也可以使用通配符*)
配置上文中我們指定的所需的dispatcher.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:context
="http://www.springframework.org/schema/context"
xmlns:mvc
="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"
>

    
<context:component-scan base-package="com.controls" />
    
<mvc:annotation-driven />
    
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
       
<property name="prefix" value="/WEB-INF/views/"></property>
       
<property name="suffix" value=".jsp"></property>
       
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>
    
</bean>
</beans>



配置文件說明:
<context:component-scan base-package="com.controls" />
由于我們使用了基于注解的Controller,所以這里指定了需要被掃描的包路徑,如果有多個可以使用逗號分隔
<mvc:annotation-driven />

上面的spring mvc流程圖中我們知道DispatcherServlet接管請求后,會由HandlerMapping來執(zhí)行映射,所以我們需要注冊HanlderMapping,比如上面的標(biāo)簽會自動注冊比如DefaultAnnotationHandlerMapping(執(zhí)行請求到Controller的映射)和AnnotationMethodHandlerAdapter(調(diào)用controller中的方法)這樣的bean,當(dāng)然這個標(biāo)簽還提供了其他的一些支持(更多介紹請參照spring官方文檔第455頁)。

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

       
<property name="prefix" value="/WEB-INF/views/"></property>

       
<property name="suffix" value=".jsp"></property>

       
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property>

</bean>

上面spring mvc流程圖的最后controller處理完畢后會交給一個ViewResolver進行處理,大體上是解析視圖邏輯名并經(jīng)過一定的處理獲取一個視圖,這里的意思是設(shè)置視圖用jsp來處理(比如我們設(shè)置viewClass為JstlView)來進行處理,就是以forward的形式轉(zhuǎn)發(fā)給jsp,這個地址是:/WEB-INF/views/[controller返回值].jsp ,當(dāng)然視圖解析器可以定義多個,(視圖解析器不會處理ModelAndView中已經(jīng)設(shè)置了View的請求,因為已經(jīng)有View來處理了,那當(dāng)然就不需要它來解析到真正的視圖View啦)
編寫Controller控制器這里我們使用例子的形式來說明

實現(xiàn)一個控制器類@Controller
@Controller
@RequestMapping(
"/user")
public class UserControl {

}

只要給類加上Controller的注解,并放在被掃描的包中,那么這個類就是一個控制器了,RequestMapping表明匹配的路徑,可以寫在類或者類的方法上,如果類上面有RequestMapping注解,那么其下面的方法就是相對于類上面注解地址的一個相對路徑


定義一個接管請求的方法方法名:無任何要求
--------------------------------------------------------------
參數(shù):(順序以及個數(shù)無任何要求)
HttpServletRequest
HttpServletResponse
PrintWriter 相當(dāng)于HttpResponse.getWriter()獲得的對象
Map 其實是獲得了ModelAndView中的Model
BindingResult 綁定數(shù)據(jù)的處理結(jié)果
HttpSession 如果使用此參數(shù),需要注意如果是第一次訪問還沒有session的話會報錯
@PathVariable 用于接收路徑變量
@RequestParam 相當(dāng)于調(diào)用request.getParameter(“name”)方法
@CookieValue 獲取cookie的值
@RequestHeader 獲取header中的值
實體對象 會根據(jù)請求的參數(shù)名,注入到這個對象對于得屬性中,必須提供set方法
等等等等等
--------------------------------------------------------------
返回值:
void
返回值是void,如果接收了PrintWriter 或者 HttpServletResponse 參數(shù),那么返回的ModelAndView就是null,也就是直接將輸出流輸出到客戶端,如果方法沒有接收輸出參數(shù),后面會默認(rèn)生成一個視圖名

String 視圖邏輯名

ModelAndView 是一個視圖邏輯名+Map的封裝類
其他任意類型 存入ModelAndView中的Model
--------------------------------------------------------------

不管我們的返回類型是什么,返回值會通過處理,最終返回一個ModelAndView或者null
例1:給方法定義一個請求映射并使用路徑變量 @RequestMapping("/id/{userid}/name/{username}")

@RequestMapping("/id/{userid}/name/{username}")
public String queryUser(@PathVariable("userid"long userID, @PathVariable("username") String userName, Map<String, User> model) {
       User user 
= new User();
       user.setUserID(userID);
       user.setUserName(userName);
       model.put(
"userInfo", user);
       
return "Home";
    }


@RequestMapping定義路由映射,其中{userid} {username} 是PathVariable(路徑變量)
這樣我們只需訪問 http://localhost:8080/SpringMVC/user/id/10001/name/liudehua 就能進入上面的方法
RequestMapping還可以使用通配符,如: /test/*/name/{name}

例2:接受請求參數(shù)@RequestMapping("/save")
@RequestMapping("/save")
public String save(@RequestParam("userName") String userName,@RequestParam("Age"int age) {
       System.out.println(userName);
       System.out.println(age);
       
return "Home";
}


例3:請求參數(shù)直接注入到Model@RequestMapping("/save")
@RequestMapping("/save")
public String save(User user) {
       System.out.println(user.getUserID());
       System.out.println(user.getUserName());
       
return "Home";
}

例4:轉(zhuǎn)發(fā)與重定向轉(zhuǎn)發(fā): (相當(dāng)于 request.getRequestDispatcher(“”).forward(request, response))
return “forward:/user/test”;

重定向: (相當(dāng)于response.redirect(“”))
return “redirect:/user/test”
return “redirect:http://www.google.com.hk”;

例5:根據(jù)HttpMethod來過濾請求
@RequestMapping(params="hello=world", method={RequestMethod.GET, RequestMethod.POST}
public String helloworld() {
}
 


例6:根據(jù)參數(shù)來進行過濾
@RequestMapping(params="hello=world", method={RequestMethod.GET, RequestMethod.POST})  
public String helloworld() {
}
  

必須有個hello的參數(shù)并且名稱為world,而且只能是get或post請求才會進入此方法

http://www.cnblogs.com/zhaoyang/archive/2012/01/07/2315425.html

paulwong 2012-03-29 19:06 發(fā)表評論
]]>
Spring MVC 的請求參數(shù)獲取的幾種方法http://www.aygfsteel.com/paulwong/archive/2012/03/23/372564.htmlpaulwongpaulwongFri, 23 Mar 2012 09:36:00 GMThttp://www.aygfsteel.com/paulwong/archive/2012/03/23/372564.htmlhttp://www.aygfsteel.com/paulwong/comments/372564.htmlhttp://www.aygfsteel.com/paulwong/archive/2012/03/23/372564.html#Feedback2http://www.aygfsteel.com/paulwong/comments/commentRss/372564.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/372564.html通過@PathVariabl注解獲取路徑中傳遞參數(shù)

JAVA
 @RequestMapping(value = "/{id}/{str}")
 
public ModelAndView helloWorld(@PathVariable String id, @PathVariable String str) {
 System.out.println(id);
 System.out.println(str);
 
return new ModelAndView("/helloWorld");
}


用@ModelAttribute注解獲取POST請求的FORM表單數(shù)據(jù)
JSP
<form method="post" action="hao.do">
 a: 
<input id="a" type="text" name="a"/>
 b: 
<input id="b" type="text" name="b"/>
 
<input type="submit" value="Submit" />
</form>


JAVA pojo
 public class Pojo{
 
private String a;
 
private int b;
}


JAVA controller
@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("pojo") Pojo pojo) {
 
return "helloWorld";
 }


直接用HttpServletRequest獲取
JAVA
@RequestMapping(method = RequestMethod.GET)
public String get(HttpServletRequest request, HttpServletResponse response) {
 System.out.println(request.getParameter(
"a"));
 
return "helloWorld";
}


用注解@RequestParam綁定請求參數(shù)a到變量a
當(dāng)請求參數(shù)a不存在時會有異常發(fā)生,可以通過設(shè)置屬性required=false解決,
例如: @RequestParam(value="a", required=false)
JAVA
@RequestMapping(value = "/requestParam", method = RequestMethod.GET)
public String setupForm(@RequestParam("a") String a, ModelMap model) {
 System.out.println(a);
return "helloWorld";}


paulwong 2012-03-23 17:36 發(fā)表評論
]]>
基于注解的SpringMVC+freemarker環(huán)境搭建http://www.aygfsteel.com/paulwong/archive/2012/03/19/372220.htmlpaulwongpaulwongMon, 19 Mar 2012 13:32:00 GMThttp://www.aygfsteel.com/paulwong/archive/2012/03/19/372220.htmlhttp://www.aygfsteel.com/paulwong/comments/372220.htmlhttp://www.aygfsteel.com/paulwong/archive/2012/03/19/372220.html#Feedback3http://www.aygfsteel.com/paulwong/comments/commentRss/372220.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/372220.html
  • 首先用IDE建一個web工程。(這個就不詳細介紹了)
  • 引入響應(yīng)的jar包
  • web.xml
    <?xml version="1.0" ?>
    <web-app 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_3_0.xsd"
        version
    ="3.0">
        
    <!--  Spring 服務(wù)層的配置文件 -->
        
    <context-param>
            
    <param-name>contextConfigLocation</param-name>
            
    <param-value>classpath:applicationContext.xml</param-value>
        
    </context-param>
        
        
    <!--  Spring 容器啟動監(jiān)聽器 -->
        
    <listener>
            
    <listener-class>org.springframework.web.context.ContextLoaderListener
            
    </listener-class>
        
    </listener>

        
    <servlet>
            
    <servlet-name>springmvc</servlet-name>
            
    <servlet-class>org.springframework.web.servlet.DispatcherServlet
            
    </servlet-class>
            
    <load-on-startup>1</load-on-startup>
        
    </servlet>
        
    <!--為DispatcherServlet建立映射 -->
        
    <servlet-mapping>
            
    <servlet-name>springmvc</servlet-name>
            
    <url-pattern>/</url-pattern>
        
    </servlet-mapping>
    </web-app>

  • SpringMVC另外一個重要的配置文件。
    DispatcherServlet會根絕web.xml中配置的<servlet-name>去找<servlet-name>-servlet.xml的文件來加載spring的一些配置信息。我這里就應(yīng)該取名叫springmvc-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:context
    ="http://www.springframework.org/schema/context"
        xsi:schemaLocation
    ="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-2.5.xsd"
    >
        
        
    <!--對web包中的所有類進行掃描,以完成Bean創(chuàng)建和自動依賴注入的功能 -->
        
    <context:component-scan base-package="com.liba.spring.mvc"/>
        
        
    <!-- 啟動Spring MVC的注解功能,完成請求和注解POJO的映射   請求映射-->
        
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />
        
            
    <!--以下三種視圖配置根據(jù)需要任選一種即可 -->

        
    <!--  一般的視圖配置 -->
        
    <!--<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" 
            p:prefix="/WEB-INF/view/" p:suffix=".jsp"/>
    -->
        
        
    <!-- 針對freemarker的視圖配置 -->
        
    <bean id="viewResolver"
            class
    ="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
            
    <property name="cache" value="true" />
            
    <property name="prefix" value="" />
            
    <property name="suffix" value=".ftl" />
            
    <property name="contentType" value="text/html;charset=UTF-8"></property>
            
    <property name="requestContextAttribute" value="request" />
            
    <property name="exposeSpringMacroHelpers" value="true" />
            
    <property name="exposeRequestAttributes" value="true" />
            
    <property name="exposeSessionAttributes" value="true" />
        
    </bean>
            
            
        
    <!-- View resolvers can also be configured with ResourceBundles or XML files. 
            If you need different view resolving based on Locale, you have to use the 
            resource bundle resolver. 
    -->
        
    <!-- 這個是針對返回視圖還是json值的視圖配置   來分別處理同步和異步請求 -->
        
    <!--<bean
                class="org.springframework.web.servlet.view.ContentNegotiatingViewResolver">
                <property name="mediaTypes">
                    <map>
                        <entry key="html" value="text/html" />
                        <entry key="json" value="application/json" />
                    </map>
                </property>
                <property name="favorParameter" value="true" />
                <property name="viewResolvers">
                    <list>
                        <bean class="org.springframework.web.servlet.view.BeanNameViewResolver" />
                        <bean id="viewResolver"
                            class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
                            <property name="cache" value="true" />
                            <property name="prefix" value="" />
                            <property name="suffix" value=".ftl" />
                            <property name="contentType" value="text/html;charset=UTF-8"></property>
                            <property name="requestContextAttribute" value="request" />
                            <property name="exposeSpringMacroHelpers" value="true" />
                            <property name="exposeRequestAttributes" value="true" />
                            <property name="exposeSessionAttributes" value="true" />
                        </bean>
                    </list>
                </property>
                <property name="defaultContentType" value="text/html" />
            </bean>
            
    -->
    </beans>

  • 如果是使用freemarker最為視圖模板需要再spring的配置文件applicationContext.xml中加入以下配置
    <bean id="freemarkerConfig"
            class
    ="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
            
    <property name="templateLoaderPath" value="/WEB-INF/view/" />
            
    <property name="freemarkerSettings">
                
    <props>
                    
    <prop key="template_update_delay">0</prop>
                    
    <prop key="default_encoding">UTF-8</prop>
                    
    <prop key="number_format">0.##########</prop>
                    
    <prop key="datetime_format">yyyy-MM-dd HH:mm:ss</prop>
                    
    <prop key="classic_compatible">true</prop>
                    
    <prop key="template_exception_handler">ignore</prop>
                
    </props>
            
    </property>
        
    </bean>

  • Controller建立
    import javax.servlet.http.HttpServletRequest;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.ModelAndView;

    @Controller
    public class SpringMvcController {

        @RequestMapping(value
    ="/welcome",method={RequestMethod.GET}
        
    public ModelAndView getFirstPage(HttpServletRequest request) {
                    
    //welcom就是視圖的名稱(welcom.ftl)
            ModelAndView mv = new ModelAndView("welcom");
            mv.addObject(
    "name""My First Spring Mvc");
            
    return mv;
        }

    }
    在url上敲http://localhost:8080/welcome就會到WEB-INF/view/welcom.ftl頁面渲染數(shù)據(jù)
  • welcom.ftl頁面
    <!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=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>
    Hello ${name}
    </body>
    </html>

    頁面出來的效果:

    Hello My First Spring Mvc










  • paulwong 2012-03-19 21:32 發(fā)表評論
    ]]>
    Java MVC框架性能比較http://www.aygfsteel.com/paulwong/archive/2012/03/03/371171.htmlpaulwongpaulwongSat, 03 Mar 2012 08:13:00 GMThttp://www.aygfsteel.com/paulwong/archive/2012/03/03/371171.htmlhttp://www.aygfsteel.com/paulwong/comments/371171.htmlhttp://www.aygfsteel.com/paulwong/archive/2012/03/03/371171.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/371171.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/371171.html

    測試環(huán)境:

    CPU:酷睿2 T5750,
    內(nèi)存:DDR2-667 2G,
    Web容器:Tomcat6.0,最大線程數(shù)設(shè)置為1000,
    操作系統(tǒng):WinXP-sp3

    測試步驟:

    搭建6個Web工程,如下:
    1.純JSP:不包含任何MVC框架,只有一個測試用的JSP頁面。
    2.struts1:包含一個Action,不做任何邏輯處理,直接轉(zhuǎn)發(fā)到一個JSP頁面
    3.struts2 JSP:不包含Action,只包含測試JSP頁面,直接訪問該頁面。
    4.struts2 單例Action:采用Spring來管理Struts2的Action實例,并配置成單例模式。
    5.struts2 多例Action:采用Spring來管理Struts2的Action實例,并配置成單例模式。
    6.SpringMVC3:采用Spring來管理Controller實例,包含一個Controller,不做邏輯處理,收到請求后,直接返回到一個JSP頁面。

    測試結(jié)果:

    測試工程 請求數(shù) 并發(fā)數(shù) 總時間(s) 總時間(s) 總時間(s) 平均值(s) Requests Per Second(每秒處理請求數(shù))
    JSP 2000 200 5.55 3.59 4.11 4.42 452.83
    struts1 2000 200 6.77 3.83 7.00 5.86 341.03
    struts2 JSP 2000 200 25.20 26.30 24.11 25.20 79.35
    struts2 單例Action 2000 200 28.36 27.59 27.69 27.88 71.74
    struts2 多例Action 2000 200 31.31 31.97 39.56 34.28 58.34
    SpringMVC3 2000 200 7.16 7.50 4.27 6.31 317.09

    說明:

    以上測試雖不是非常的精確,但基本能說明一定的問題。每個JSP頁面和Action都不包含任何的業(yè)務(wù)邏輯代碼,只是請求轉(zhuǎn)發(fā)。每輪測試取三次總時間的平均值。所有工程的測試均全部完成并正常處理請求,沒有請求拒絕情況發(fā)生。

    結(jié)論:

    1. 純JSP的性能應(yīng)該最高,這不難理解,JSP被編譯成Servlet后,沒有任何多余的功能,收到請求后直接處理。(這也驗證一句經(jīng)典的話:越原始效率就越高。

    2. struts1的性能是僅次于純JSP的,由于struts1采用單例Action模式,且本身的封裝相比struts2應(yīng)該說簡單很多,雖然開發(fā)效率不如struts2,但已經(jīng)過多年的實踐考驗,性能穩(wěn)定高效。

    3. 相比來說struts2的性能就比較差了,這不難理解,struts2之所以開發(fā)方便,是由于采用值棧、OGNL表達式、攔截器等技術(shù)對請求參數(shù)的映射和返回結(jié)果進行了處理,另外還采用大量的標(biāo)簽庫等,這些都無疑增加了處理的時間。因此降低了效率。在我們實際的項目中,我測試本地工程訪問每秒處理請求數(shù)只能達到35左右,應(yīng)該說還有不少可優(yōu)化的空間。

    4. 很多人認(rèn)為struts2性能差是因為它的多例Action模式導(dǎo)致的,但我們采用spring管理struts2的Action,并設(shè)置按單例方式生成Action實例后,發(fā)現(xiàn)其性能有所提高,但并不是很明顯。由此可見,多例Action模式并不是struts2性能瓶頸所在。另外,我們在struts2中采用JSP方式訪問,發(fā)現(xiàn)其性能依舊和沒有采用任何MVC框架的純JSP之間存在好幾倍的差距,這又從另一個側(cè)面證實了我們剛才得出結(jié)論,struts2性能的瓶頸不在于它的多例Action模式。

    5. SpringMVC3的性能略遜于struts1,但基本是同級別的,這讓人眼前一亮,springMVC有著不比struts2差的開發(fā)效率和解耦度,但性能卻是struts2的好幾倍,這讓我們灰常振奮,SpringMVC無疑又是項目開發(fā)的一個好的選擇。


    paulwong 2012-03-03 16:13 發(fā)表評論
    ]]>
    Spring MVC如何防止重復(fù)提交?類似Struts Token機制!http://www.aygfsteel.com/paulwong/archive/2012/02/20/370375.htmlpaulwongpaulwongMon, 20 Feb 2012 14:57:00 GMThttp://www.aygfsteel.com/paulwong/archive/2012/02/20/370375.htmlhttp://www.aygfsteel.com/paulwong/comments/370375.htmlhttp://www.aygfsteel.com/paulwong/archive/2012/02/20/370375.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/370375.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/370375.html
    可以這么說,當(dāng)setSessionForm(true)之后,如果沒有先后經(jīng)歷顯示表單、提交表單的過程,就會被認(rèn)為是重復(fù)提交表單。

    而有一些情況下卻必須重復(fù)提交表單,如,修改數(shù)據(jù)庫的數(shù)據(jù)后,試圖寫入數(shù)據(jù)庫時因某些異常失敗,如果此時異常被當(dāng)前頁面捕獲并依舊返回當(dāng)前頁面,由于command已經(jīng)被Spring在后臺從session中移走,因此,就被認(rèn)為是無效重復(fù)提交,從而導(dǎo)致第二次經(jīng)修改后的記錄無法正確提交到數(shù)據(jù)庫中。handleInvalidSubmit()必須考慮到這種情況。

    paulwong 2012-02-20 22:57 發(fā)表評論
    ]]>
    SPRING MVChttp://www.aygfsteel.com/paulwong/archive/2012/02/20/370373.htmlpaulwongpaulwongMon, 20 Feb 2012 14:53:00 GMThttp://www.aygfsteel.com/paulwong/archive/2012/02/20/370373.htmlhttp://www.aygfsteel.com/paulwong/comments/370373.htmlhttp://www.aygfsteel.com/paulwong/archive/2012/02/20/370373.html#Feedback0http://www.aygfsteel.com/paulwong/comments/commentRss/370373.htmlhttp://www.aygfsteel.com/paulwong/services/trackbacks/370373.html
    1. ACTION SERVLET:前端控制器,和所有的WEB框架一樣,是所有的請求的中心入口
    2. MAPPING HANDLER: 比對URL,找出負(fù)責(zé)處理的控制器
    3. CONTROLLER:控制器,負(fù)責(zé)處理前端的請求,返回MODELVIEW
    4. VIEW RESOLVER:根據(jù)CONTROLLER返回的MODEL VIEW找出負(fù)責(zé)展現(xiàn)的VIEW
    5. VIEW:由于展現(xiàn)內(nèi)容可以有不同方式,如JSP,F(xiàn)REEMARKER等,VIEW就負(fù)責(zé)展現(xiàn),分兩步,取得要展現(xiàn)的模版的路徑,使用解釋器解釋并取得最終內(nèi)容。一般一個SPRING就一個展現(xiàn)器,如JSTLVIEW,對于不同的URL,只是JSP頁面路徑不同,從CONTROLLER返回的MODEL VIEW中取得JSP路徑,輸出最終內(nèi)容
    6. FORM HANDLER:頁面如果有表單,就涉及到如何從表單中讀取數(shù)據(jù)或?qū)?shù)據(jù)綁定到表單中,表單處理器已經(jīng)和CONTROLLER結(jié)合在一起了,只須繼承SIMPLE FORM HANDLER就可以,在JSP中配置COMMANDNAME值,就可以此為KEY,從MODELVIEW中取表單值或綁定值到表單中
    在STRUTS中,會有一配置文件:STRUTS-COMFIG.XML,配置了所要用到的BEAN的內(nèi)容,好處是直觀,但項目大了,免不了配置文件數(shù)量龐大,為了減少配置文件的數(shù)量,引入注釋,實際上可以理解為配置文件不用手寫,由容器在啟動時動態(tài)幫你生成,只須在相應(yīng)代碼,如類名,方法上加上注釋,容器在解釋這些類的時候就會動態(tài)生成一虛擬的配置文件,供后續(xù)使用。具體的注釋有@CONTROLLER/@SERVICE/@REQUESTMAPPING等。



    Spring MVC 3 深入總結(jié)
    http://www.aygfsteel.com/qcyycom/archive/2013/07/11/401467.html

    paulwong 2012-02-20 22:53 發(fā)表評論
    ]]>
    主站蜘蛛池模板: 永济市| 遂昌县| 昔阳县| 图木舒克市| 申扎县| 漯河市| 新巴尔虎右旗| 三门峡市| 渑池县| 密云县| 巧家县| 繁峙县| 巩留县| 石景山区| 固安县| 莆田市| 唐河县| 临泽县| 波密县| 河间市| 竹山县| 谷城县| 达州市| 天等县| 永兴县| 罗江县| 浦北县| 丰城市| 建平县| 米泉市| 普格县| 比如县| 蕉岭县| 阿拉善左旗| 南皮县| 德清县| 文化| 杭锦旗| 砚山县| 灌南县| 越西县|