您的位置:首页 > 编程语言 > Java开发

spring mvc Hello World

2013-07-26 13:21 375 查看
index.jsp

<body>
<font size="2px" face="verdana">
Welcome...
<a href="java4s.html"><br> Click here to check the output :-)</a>
</font>

</body>


package java4s;

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

@Controller
public class Java4sController {

@RequestMapping("/java4s")
public ModelAndView helloWorld() {

String message =  "Welcome to Java4s.com Spring MVC 3.2.x Sessions";
message += "<br>You Did it....!";

return new ModelAndView("welcomePage", "welcomeMessage", message);
}

}
welcome-servlet.xml

<context:component-scan base-package="java4s" />

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
welcomePage.jsp

<html>
<body>
<font face="verdana" size="2">In Jsp
${welcomeMessage}
</font>
</body>
</html>


Execution Flow

Run the application, then index.jsp file will be executed > click on the link given (I have given <a href=”java4s.html”>Click here to check the output</a>)

Once you click on that link, container will check the URL pattern at web.xml and passes the request to the DispatcherServlet

DispatcherServlet then passes that request to our controller class

Actually we are passing java4s.html from index.jsp right ? so DispatcherServlet verifies this ‘java4s’ name with the string in @RequestMapping(“-”) in our controller class if same it will executes the following method, which gives ModelAndView object as return
type

In our controller class we are returning…

return new ModelAndView("welcomePage", "welcomeMessage", message);

Means first argument is ‘View’ page name [ Where we are sending our result ], second, third arguments are key,values

So DispatcherServlet search for the name welcomePage in /jsp folder with extension .jsp [ you can change the 'view page' folder name/location and its extension in welcome-servlet.xml at line numbers 14,15], once the file was opened you can access the data
by using the key welcomeMessage [2nd parameter in ModelAndView object]

Check welcomePage.jsp > i am printing the result by calling the key ${welcomeMessage}

Note

In web.xml we have given servlet name as welcome, so spring configuration file name must be welcome-servlet.xml [ {servletName-in-web.xml}-servlet.xml ]

原文:http://www.java4s.com/spring-mvc/spring-mvc-hello-world-spring-mvc-3-2-hello-world-example-in-eclipse/

源代码:http://pan.baidu.com/share/link?shareid=3998828960&uk=3878681452
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: