SpringMVC Tutorial 2 [Processing Response Requests]

Posted by redhair on Sun, 05 May 2019 18:32:04 +0200

1. Basic operations

1. How to respond to requests

Not responding | void+@ResponseBody comment |

ModelAndView | via setViewName method | Specify Response Page Directly| Return value is of type String, Return result specifies jump address|

Redirect|prefix the jump address with redirect:prefix is sufficient|

Both variables are declared in the HttpServletRequest and HttpServletResponse | parameters.Then jump through the relevant api |

The last time you saw ModelAndView's response, you started with void

1. Return void

When the return value is void, no return is required in the method. In the browser, springmvc defaults to finding pages with the same name as the method and returns them as a view of the method.If you really don't need this method to return to the page, you can use the @ResponseBody annotation to indicate that a request has ended.

@RequestMapping("/test1")
@ResponseBody
public void test1() {    
   System.out.println("test1");
}

Here's how the various requests are handled and the implementation code, so the results are not illustrated one by one

Configure the web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>SpringMVC-01-hello</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
	<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:Spring-MVC.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
</web-app>

Configure the configuration file for spring-mvc

<?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"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		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-4.3.xsd">
	<!-- Open Scan -->
	<context:component-scan base-package="com.sxt"/>
	
	<!-- open SpringMVC Ways of Annotation -->
	<mvc:annotation-driven></mvc:annotation-driven>
	
	<!-- Configure View Parser and Controller A method used together with a tag behind it-->
	<!--  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
			<property name="prefix" value="/"/>
			<property name="suffix" value=".jsp"/>
	</bean>  -->
</beans>

Custom Controller,index jsp page content customization

package com.sxt;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

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

@Controller
@RequestMapping("/hello")
public class HelloController {

	//ModelAndView, response mode
	@RequestMapping("/hello1")
	public ModelAndView hello1(){
		System.out.println("-----hello1---");
		ModelAndView m = new ModelAndView();
		m.setViewName("/index.jsp");
		return m;
	}
	//Returns a string
	@RequestMapping("/hello2")
	@ResponseBody//The comment indicates that a request ends here
	public void  hello2(){
		
		System.out.println("aaaa");
	}
	/*
	 * This method requires the spring-mvc profile configuration view parser to automatically add the index prefix suffix, which can be used when turned on
	@RequestMapping("/h1")
	public String hello3(){
		System.out.println("111");
		return "index";
	}*/
	//Redirect jump: Return path Note: The returned character band'/'means to start from the root directory, without'/' looks from the current directory
	@RequestMapping("/h2")
	public String hello4(){
		System.out.println("111");
		return "redirect:/index.jsp";
	}
	//Through request and response
	@RequestMapping("/h5")
	public void hello5(HttpServletRequest request,HttpServletResponse response) throws IOException, Exception{
		System.out.println("333");
		request.getRequestDispatcher("/index.jsp").forward(request, response);
	}

}

The above method is the same except that the view resolver needs to be configured in the configuration file

Description for @RequertMapping

1. Mapping Path The most basic function of @RequestMapping is to use:

@RequestMapping("/delete")
 public String delete(){
 	System.out.println("Porpo Roast Duck: Delete Data Operation....");
 	return "/hello";
 }

Narrow Request Narrowing requests are used to restrict the request path by placing @RequestMapping on the class so that the method's request path is @RequestMapping on the @ReqmestMapping+ method on the class Request Method Qualification

Basic data types

java basic data type + string When using the basic data type, the parameter name matches the key of the parameter passed from the browser so that automatic mapping can be achieved

/**
 * Receive parameters
 *    Basic data types
 * @param id
 * @param name
 * @return
 */ @RequestMapping("add") public String add(int id,String name){ System.out.println(id+"---"+name); return "/hello"; } 

If the parameter name does not match the key passed from the browser, it can be resolved by @RequestParam.as follows

/**
 * Receive parameters
 *    Basic data types
 *    Request parameters can be specified through the @RequestParam class if they do not match the parameter name
 * @param id
 * @param name
 * @return
 */ @RequestMapping("add") 
 public String add(int id,@RequestParam("username")String name){
  			System.out.println(id+"---"+name); 
 			 return "/hello";
   }

Add @ReuestParam and if you re-specify the parameter name, the default parameter name will remain the original parameter name. Also note that when you add this comment, the corresponding parameter will become a required parameter. If you do not pass the relevant parameter, an exception will be thrown But there are two ways to solve this if you don't want to pass parameters

1. Specifying this parameter through the required property is not required

/**
 * Receive parameters
 *    Basic data types
 *    Request parameters can be specified through the @RequestParam class if they do not match the parameter name
 * @param id
 * @param name
 * @return
 */ @RequestMapping("add")
  public String add(int id ,@RequestParam(value="username",required=false)String name){ 
 				 System.out.println(id+"---"+name); 
 				 return "/hello";
   }

2. Give the specified parameter a default value through the defaultValue property

/**
 * Receive parameters
 *    Basic data types
 *    Request parameters can be specified through the @RequestParam class if they do not match the parameter name
 * @param id
 * @param name
 * @return
 */ @RequestMapping("add")
  public String add(int id ,@RequestParam(value="username",defaultValue="kaoya")String name){
   					System.out.println(id+"---"+name);
   						 return "/hello";
     }

object

Create a book object and a user object

package com.sxt.bean;

public class Book {
	private Integer id;
	
	private String name;

	@Override
	public String toString() {
		return "Book [id=" + id + ", name=" + name + "]";
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
}

package com.sxt.bean;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class User {
	private Integer id;

	private Integer age;

	private String unama;
	private String[] favorites;

	private List<String> list;

	private Date birth;

	private Book book;

	@Override
	public String toString() {
		return "User [id=" + id + ", age=" + age + ", unama=" + unama + ", favorites=" + Arrays.toString(favorites)
				+ ", list=" + list + ", birth=" + birth + ", book=" + book + "]";
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	public String getUnama() {
		return unama;
	}

	public void setUnama(String unama) {
		this.unama = unama;
	}

	public String[] getFavorites() {
		return favorites;
	}

	public void setFavorites(String[] favorites) {
		this.favorites = favorites;
	}

	public List<String> getList() {
		return list;
	}

	public void setList(List<String> list) {
		this.list = list;
	}

	public Date getBirth() {
		return birth;
	}

	public void setBirth(Date birth) {
		this.birth = birth;
	}

	public Book getBook() {
		return book;
	}

	public void setBook(Book book) {
		this.book = book;
	}

	
}

create profile

<?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"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		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-4.3.xsd">
	<!-- Open Scan -->
	<context:component-scan base-package="com.sxt"/>
	
	<!-- open SpringMVC Ways of Annotation -->
	<mvc:annotation-driven></mvc:annotation-driven>
</beans>

Create user.jsp page

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="add" method="post">
	<table>
		<tr>
			<td>number</td>
			<td><input type="text" name="id"></td>
		</tr>
		<tr>
			<td>Name</td>
			<td><input type="text" name="unama"></td>
		</tr>
		<tr>
			<td>Age</td>
			<td><input type="text" name="age"></td>
		</tr>
		<tr>
			<td>id</td>
			<td><input type="text" name="book.id"></td>
		</tr>
		<tr>
			<td>author</td>
			<td><input type="text" name="book.name"></td>
		</tr>
		<tr>
			<td><input type="submit" value="Add to"></td>
		</tr>
	</table>
</form>

</body>
</html>

Create a custom Controller

package com.sxt;

import java.util.Date;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sxt.bean.User;

@Controller
public class UserController {

	@RequestMapping("/add")//Object Acceptance Data Method
	@ResponseBody
	public void add(User user) {
		System.out.println(user);
	}

}

test

Nothing else is worth it because of the object being tested

Data Acceptance for Arrays and Collections

bean layer and configuration file, web.xml file are the same

package com.sxt;

import java.util.Date;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sxt.bean.User;

@Controller
public class UserController {
	//Array Data Acquisition
	@RequestMapping("/add2")
	@ResponseBody
	public void add3(User user) {
		System.out.println(user);
		String[] favorites = user.getFavorites();
		for (String f : favorites) {
			System.out.println(f);
		}

	}
	//Collection Data Acquisition
	@RequestMapping("/add3")
	@ResponseBody
	public void add4(User user) {
		System.out.println(user);
		System.out.println(user.getList());

	}

}

Create corresponding jsp page

Get the jsp page of the array class Get the jsp page of the collection class

Test Access Path

Output result of array

Collection Output Results

Summary: 1. Arrays (whether basic data types or object arrays) can be written directly into interface parameters. 2. Collections, whether basic data types or objects, need a wrapper class to wrap them and cannot be written directly in interface parameters. 3. For basic data types, arrays and collections are written in the same way in the form 4. For object data types, arrays and collections are written in the same way in the form

Data type acceptance

Accepting a Data type is a Data type that needs to be accepted through a converter

Customize Controller

Create a custom converter

package com.sxt;

import java.util.Date;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sxt.bean.User;

@Controller
public class UserController {
	@RequestMapping("/add4")
	@ResponseBody
	public void add4(Date d) {
		System.out.println(d);

	}

}

package com.sxt;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.springframework.core.convert.converter.Converter;
/**
 * Data Type Converter
 * @author Administrator
 *
 */
public class Convert implements Converter<String, Date>{

	@Override
	public Date convert(String arg0) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		try {
			return format.parse(arg0);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}

Configuring in the spring-mvc.xml configuration file

<?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"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		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-4.3.xsd">
		<!-- Open Scan -->
	<context:component-scan base-package="com.sxt"/>
	
	<!-- open SpringMVC Ways of Annotation -->
	<mvc:annotation-driven conversion-service="formattingConversionServiceFactoryBean"></mvc:annotation-driven>
	<bean class="org.springframework.format.support.FormattingConversionServiceFactoryBean" id="formattingConversionServiceFactoryBean">
		<property name="converters">
			<set>
				<bean class="com.sxt.Convert"/>
			</set>
		</property>
	</bean>
	
</beans>

test

Response data

3.1ModelAndView 3.2HttpServletRequest 3.3HttpSession 3.4Map

Create a custom controller

package com.sxt;

import java.util.Map;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class HelloController {
	@RequestMapping("query1")
	public String add(Map<String, Object> map){
		map.put("msg", "aaaa");
		return "/index.jsp";
	}
	
	@RequestMapping("query2")
	public String add1(Model m){
		m.addAttribute("msg", "bbb");
		return "/index.jsp";
	}
	
	@RequestMapping("query3")
	public String add2(ModelMap mm){
		mm.addAttribute("msg", "ccc");
		return "/index.jsp";
	}
	
	@RequestMapping("query4")
	public ModelAndView add3(){
			ModelAndView view = new ModelAndView();
			view.addObject("msg", "ddd");
			view.setViewName("index.jsp");
			return view;
	}
}

Create a springmvc configuration file

<?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"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
		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-4.3.xsd">
		<!-- Open Scan -->
	<context:component-scan base-package="com.sxt"/>
	
	<!-- open SpringMVC Ways of Annotation -->
	<mvc:annotation-driven ></mvc:annotation-driven>
	
</beans>

Create index.jsp page

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Insert title here</title>
</head>
<body>
${msg}

<h3>request:${requestScope.msg }</h3>
	<h3>session:${sessionScope.msg }</h3>
	<h3>application:${applicationScope.msg }</h3>
</body>
</html>
request:${requestScope.msg }
session:${sessionScope.msg }
application:${applicationScope.msg }
Check in which scope the msg is saved and it turns out to be saved in the request scope

Note: Add the comment @SessionAttributes to keep the data in session scope.

post Submit Chinese Scrambling Problem

Add the following code to the web.xml file

<!-- spring Character set filters provided by frames -->
 <!-- spring Web MVC The framework provides org.springframework.web.filter.CharacterEncodingFilter For resolving POST Chinese scrambling caused by manners  --> 
 <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>
 </filter>
 	  	  	 <filter-mapping > 
 	  	  	 <filter-name>encodingFilter</filter-name>
 	  	  	  <url-pattern>/*</url-pattern> 
 </filter-mapping> 

Topics: Programming Spring JSP Java xml