中文字幕剧情在线观看一区,亚洲精品一区二区三区在线观看,一区二区三区久久网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;  
  
/** 
 * <一句話功能簡(jiǎn)述> 
 * <功能詳細(xì)描述> 
 *  
 * 
@author  Administrator 
 * 
@version  [版本號(hào), 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(定價(jià)后).xlsx";  
        File file=new File(path);  
        HttpHeaders headers = new HttpHeaders();    
        String fileName=new String("你好.xlsx".getBytes("UTF-8"),"iso-8859-1");//為了解決中文名稱亂碼問(wèn)題  
        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>  


]]>
Spring對(duì)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

]]>
Spring Data REST,Spring MVC的REST擴(kuò)展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

]]>
基于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);

]]>
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












]]>
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());
    }
}





]]>
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 <!-- 自動(dòng)解析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>  
<!-- 自動(dòng)解析action返回值 解析成json格式 -->
然后需要額外的jar包 jackson 1.1,這里讓我很無(wú)語(yǔ),我首先下的1.9放上去什么方法找不到,換1.8x 方法找不到 我一直試到1.6 后來(lái)怒了用最老的 好了。。。坑,這絕對(duì)是坑啊

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





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 對(duì)應(yīng)string則對(duì)應(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;
}

}


]]>
開(kāi)始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下,可以這么寫(xiě): 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在初始化的過(guò)程中需要一個(gè)配置文件來(lái)生產(chǎn)文件中的各種bean,并生成WebApplicationContext對(duì)象,保存到ServletContext中(如果DispatcherServlet有多個(gè),那么每一個(gè)DispatcherServlet都對(duì)應(yīng)一個(gè)WebApplicationContext),我們可以在Servlet的init-param中配置配置文件的路徑,當(dāng)然如果我們沒(méi)有配置Init-Param,它會(huì)默認(rèn)到WEB-INF的文件夾中找[servletname]-servlet.xml文件,例如上面如果我們沒(méi)有配置,則會(huì)去尋找dispatcher-servlet.xml這個(gè)配置文件。(在init-param中我們可以指定多個(gè)配置文件,用逗號(hào)分隔也可以使用通配符*)
配置上文中我們指定的所需的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>



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

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

<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處理完畢后會(huì)交給一個(gè)ViewResolver進(jìn)行處理,大體上是解析視圖邏輯名并經(jīng)過(guò)一定的處理獲取一個(gè)視圖,這里的意思是設(shè)置視圖用jsp來(lái)處理(比如我們?cè)O(shè)置viewClass為JstlView)來(lái)進(jìn)行處理,就是以forward的形式轉(zhuǎn)發(fā)給jsp,這個(gè)地址是:/WEB-INF/views/[controller返回值].jsp ,當(dāng)然視圖解析器可以定義多個(gè),(視圖解析器不會(huì)處理ModelAndView中已經(jīng)設(shè)置了View的請(qǐng)求,因?yàn)橐呀?jīng)有View來(lái)處理了,那當(dāng)然就不需要它來(lái)解析到真正的視圖View啦)
編寫(xiě)Controller控制器這里我們使用例子的形式來(lái)說(shuō)明

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

}

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


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

String 視圖邏輯名

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

不管我們的返回類型是什么,返回值會(huì)通過(guò)處理,最終返回一個(gè)ModelAndView或者null
例1:給方法定義一個(gè)請(qǐng)求映射并使用路徑變量 @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(路徑變量)
這樣我們只需訪問(wèn) http://localhost:8080/SpringMVC/user/id/10001/name/liudehua 就能進(jìn)入上面的方法
RequestMapping還可以使用通配符,如: /test/*/name/{name}

例2:接受請(qǐng)求參數(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:請(qǐng)求參數(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來(lái)過(guò)濾請(qǐng)求
@RequestMapping(params="hello=world", method={RequestMethod.GET, RequestMethod.POST}
public String helloworld() {
}
 


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

必須有個(gè)hello的參數(shù)并且名稱為world,而且只能是get或post請(qǐng)求才會(huì)進(jìn)入此方法

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

]]>
Spring MVC 的請(qǐng)求參數(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通過(guò)@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請(qǐng)求的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綁定請(qǐng)求參數(shù)a到變量a
當(dāng)請(qǐng)求參數(shù)a不存在時(shí)會(huì)有異常發(fā)生,可以通過(guò)設(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";}


]]>
基于注解的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建一個(gè)web工程。(這個(gè)就不詳細(xì)介紹了)
  • 引入響應(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 容器啟動(dòng)監(jiān)聽(tīng)器 -->
        
    <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另外一個(gè)重要的配置文件。
    DispatcherServlet會(huì)根絕web.xml中配置的<servlet-name>去找<servlet-name>-servlet.xml的文件來(lái)加載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"
    >
        
        
    <!--對(duì)web包中的所有類進(jìn)行掃描,以完成Bean創(chuàng)建和自動(dòng)依賴注入的功能 -->
        
    <context:component-scan base-package="com.liba.spring.mvc"/>
        
        
    <!-- 啟動(dòng)Spring MVC的注解功能,完成請(qǐng)求和注解POJO的映射   請(qǐng)求映射-->
        
    <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"/>
    -->
        
        
    <!-- 針對(duì)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. 
    -->
        
    <!-- 這個(gè)是針對(duì)返回視圖還是json值的視圖配置   來(lái)分別處理同步和異步請(qǐng)求 -->
        
    <!--<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就會(huì)到WEB-INF/view/welcom.ftl頁(yè)面渲染數(shù)據(jù)
  • welcom.ftl頁(yè)面
    <!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>

    頁(yè)面出來(lái)的效果:

    Hello My First Spring Mvc










  • ]]>
    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

    測(cè)試環(huán)境:

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

    測(cè)試步驟:

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

    測(cè)試結(jié)果:

    測(cè)試工程 請(qǐng)求數(shù) 并發(fā)數(shù) 總時(shí)間(s) 總時(shí)間(s) 總時(shí)間(s) 平均值(s) Requests Per Second(每秒處理請(qǐng)求數(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

    說(shuō)明:

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

    結(jié)論:

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

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

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

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

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


    ]]>
    Spring MVC如何防止重復(fù)提交?類似Struts Token機(jī)制!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
    可以這么說(shuō),當(dāng)setSessionForm(true)之后,如果沒(méi)有先后經(jīng)歷顯示表單、提交表單的過(guò)程,就會(huì)被認(rèn)為是重復(fù)提交表單。

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

    ]]>
    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框架一樣,是所有的請(qǐng)求的中心入口
    2. MAPPING HANDLER: 比對(duì)URL,找出負(fù)責(zé)處理的控制器
    3. CONTROLLER:控制器,負(fù)責(zé)處理前端的請(qǐng)求,返回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)容。一般一個(gè)SPRING就一個(gè)展現(xiàn)器,如JSTLVIEW,對(duì)于不同的URL,只是JSP頁(yè)面路徑不同,從CONTROLLER返回的MODEL VIEW中取得JSP路徑,輸出最終內(nèi)容
    6. FORM HANDLER:頁(yè)面如果有表單,就涉及到如何從表單中讀取數(shù)據(jù)或?qū)?shù)據(jù)綁定到表單中,表單處理器已經(jīng)和CONTROLLER結(jié)合在一起了,只須繼承SIMPLE FORM HANDLER就可以,在JSP中配置COMMANDNAME值,就可以此為KEY,從MODELVIEW中取表單值或綁定值到表單中
    在STRUTS中,會(huì)有一配置文件:STRUTS-COMFIG.XML,配置了所要用到的BEAN的內(nèi)容,好處是直觀,但項(xiàng)目大了,免不了配置文件數(shù)量龐大,為了減少配置文件的數(shù)量,引入注釋,實(shí)際上可以理解為配置文件不用手寫(xiě),由容器在啟動(dòng)時(shí)動(dòng)態(tài)幫你生成,只須在相應(yīng)代碼,如類名,方法上加上注釋,容器在解釋這些類的時(shí)候就會(huì)動(dòng)態(tài)生成一虛擬的配置文件,供后續(xù)使用。具體的注釋有@CONTROLLER/@SERVICE/@REQUESTMAPPING等。



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

    ]]>
    主站蜘蛛池模板: 龙井市| 盐津县| 久治县| 东光县| 虹口区| 蕉岭县| 左云县| 河南省| 莎车县| 临西县| 高青县| 临湘市| 濮阳县| 浠水县| 安溪县| 白银市| 鲜城| 怀来县| 牡丹江市| 满洲里市| 达拉特旗| 姚安县| 邵阳市| 滨海县| 乌什县| 莲花县| 河东区| 达孜县| 阿巴嘎旗| 岗巴县| 石楼县| 百色市| 苏尼特右旗| 宁南县| 旅游| 于田县| 呼图壁县| 山阴县| 昌江| 遵化市| 武强县|