spring mvc helloworld 和表单功能、页面重定向

Spring MVC Hello World 例子

这里有个很好的教程:https://www.cnblogs.com/wormday/p/8435617.html

下面的例子说明了如何使用 Spring MVC 框架来编写一个简单的基于 web 的 Hello World 应用程序。下面让我们使用 ideal IDE,然后按照下面的步骤使用 Spring 的 Web 框架来开发一个动态 Web 应用程序:

这里是 HelloController.java 文件的内容:

 1 package com.tutorialspoint;
 2 import org.springframework.stereotype.Controller;
 3 import org.springframework.web.bind.annotation.RequestMapping;
 4 import org.springframework.web.bind.annotation.RequestMethod;
 5 import org.springframework.ui.ModelMap;
 6 @Controller
 7 @RequestMapping("/hello")
 8 public class HelloController{ 
 9    @RequestMapping(method = RequestMethod.GET)
10    public String printHello(ModelMap model) {
11       model.addAttribute("message", "Hello Spring MVC Framework!");
12       return "hello";
13    }
14 }

下面是 Spring Web 配置文件 web.xml 的内容

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>HelloWeb</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloWeb</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

下面是另一个 Spring Web 配置文件 HelloWeb-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:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <context:component-scan base-package="com.rxhui.springmvc"/>

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


</beans>

下面是 Spring 视图文件 hello.jsp 的内容,注意:1.dispatch-servlet.xml中前缀是/jsp,所以应该把hello.jsp放入一个jsp文件夹中。

<%@ page contentType="text/html; charset=UTF-8" %>
<html>
<head>
<title>Hello World</title>
</head>
<body>
   <h2>${message}</h2>
</body>
</html>

使用Ideal导出war:project structure->Artifacts->+->WebApplication:Exploded-> WebApplication:Archive-> 改名->save->build-> build Artifacts -> 刚才的Archive->build

现在启动你的 Tomcat 服务器,并且确保你能够使用标准的浏览器访问 webapps 文件夹中的其他 web 页面。现在尝试访问该 URL http://localhost:8080/HelloWeb/hello。如果你的 Spring Web 应用程序一切都正常,就可以看到页面,注意,这里访问的url中HelloWeb是webapps下包的名字,如果使用IDE直接调试Tomcat,不需要带HelloWeb。

 

Spring MVC 表单处理例子

这里是 Student.java 文件的内容:

public class Student {
   private Integer age;
   private String name;
   private Integer id;
   public void setAge(Integer age) {
      this.age = age;
   }
   public Integer getAge() {
      return age;
   }
   public void setName(String name) {
      this.name = name;
   }
   public String getName() {
      return name;
   }
   public void setId(Integer id) {
      this.id = id;
   }
   public Integer getId() {
      return id;
   }
}

下面是 StudentController.java 文件的内容:

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.ui.ModelMap;
@Controller
public class StudentController {
   @RequestMapping(value = "/student", method = RequestMethod.GET)
   public ModelAndView student() {
      return new ModelAndView("student", "command", new Student());
   }   
   @RequestMapping(value = "/addStudent", method = RequestMethod.POST)
   public String addStudent(@ModelAttribute("SpringWeb")Student student, 
   ModelMap model) {
      model.addAttribute("name", student.getName());
      model.addAttribute("age", student.getAge());
      model.addAttribute("id", student.getId());      
      return "result";
   }
}

在这里,第一个 service 方法 student(),我们已经在名称为 “command” 的 ModelAndView 对象中传递一个空的 Student 对象,因为 spring 框架需要一个名称的 “command” 的对象,如果你在 JSP 文件中使用 <form:form> 标签。所以,当 student() 方法被调用时,它返回 student.jsp 视图。

注意:上面的command是ModelAndView默认的名称,但是如果想要正常运行,还需要在jsp中注入一个bean.

第二个 service 方法 addStudent() 将调用 HelloWeb/addStudent URL 中的 POST 方法。你将根据提交的信息准备好你的模型对象。最后一个 “result” 视图会从 service 方法中返回,它将导致呈现 result.jsp。

下面是 Spring Web 配置文件 web.xml 的内容

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

    <display-name>Spring MVC Form Handling</display-name>


    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>HelloWeb</servlet-name>
        <servlet-class>
            org.springframework.web.servlet.DispatcherServlet
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>HelloWeb</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

下面是另一个 Spring Web 配置文件 HelloWeb-servlet.xml 的内容

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:context="http://www.springframework.org/schema/context"
   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">

   <context:component-scan base-package="com.tutorialspoint" />

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

</beans>

下面是 Spring 视图文件 student.jsp 的内容

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring MVC Form Handling</title>
</head>
<body>

<h2>Student Information</h2>
<jsp:useBean id="command" class="com.xxx.xx.Student" scope="request"/>
<form:form  method="POST" action="/addStudent">
    <table>
        <tr>
            <td><form:label path="name">Name</form:label></td>
            <td><form:input path="name" /></td>
        </tr>
        <tr>
            <td><form:label path="age">Age</form:label></td>
            <td><form:input path="age" /></td>
        </tr>
        <tr>
            <td><form:label path="id">id</form:label></td>
            <td><form:input path="id" /></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="Submit"/>
            </td>
        </tr>
    </table>
</form:form>
</body>
</html>
<jsp:useBean id="command" class="com.xxx.xx.Student" scope="request"/>这句会向form中注入一个student,否则会抛出Neither BindingResult nor plain target object for bean name 'command' available as request attribute

下面是 Spring 视图文件 result.jsp 的内容

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
    <title>Spring MVC Form Handling</title>
</head>
<body>

<h2>Submitted Student Information</h2>
   <table>
    <tr>
        <td>Name</td>
        <td>${name}</td>
    </tr>
    <tr>
        <td>Age</td>
        <td>${age}</td>
    </tr>
    <tr>
        <td>ID</td>
        <td>${id}</td>
    </tr>
</table>  
</body>
</html>

 

Spring 页面重定向例子

 这里只用WebController的例子说明一下

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class WebController {
   @RequestMapping(value = "/index", method = RequestMethod.GET)
   public String index() {
       return "index";
   }   
   @RequestMapping(value = "/redirect", method = RequestMethod.GET)
   public String redirect() {     
      return "redirect:finalPage";
   }   
   @RequestMapping(value = "/finalPage", method = RequestMethod.GET)
   public String finalPage() {     
      return "final";
   }
}
这里实际的流程是访问/index页面,点击按钮进行重定向,发送执行/redirect,“redirect:finalPage"中,redirect是个关键词,就是重定向url的意思,冒号后面的finalPage是urlGet请求,最终会返回final.jsp

posted on 2018-07-04 10:55  重八  阅读(223)  评论(0编辑  收藏  举报

导航