The way the result jumps
-
ModelAndView
Sets the ModelAndView object to jump to the specified page based on the name of the ViewName and the view resolver.
- Page: {view parser prefix}+ViewName+{view parser suffix}
<! -- View resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<! -- prefix -- -- >
<property name="prefix" value="/WEB-INF/jsp/" />
<! - the suffix - >
<property name="suffix" value=".jsp" />
</bean>
Copy the code
Corresponding Controller class
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
// Returns a model view object
ModelAndView mv = new ModelAndView();
mv.addObject("msg"."ControllerTest1");
mv.setViewName("test");
returnmv; }}Copy the code
-
ServletAPI
By setting up the ServletAPI, no view parser is required.
- Output via HttpServletResponse
- Redirection is implemented via HttpServletResponse
- Forwarding is implemented via HttpServletResponse
@Controller
public class controller {
@RequestMapping("/result/t1")
public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.getWriter().println("servletAPI");
}
@RequestMapping("/result/t2")
public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.sendRedirect("/index.jsp");
}
@RequestMapping("/result/t3")
public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
/ / forwarding
req.setAttribute("msg"."/result/t3");
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp); }}Copy the code
-
SpringMVC
Forwarding and redirection via SpringMVC annotations (no view parser required)
@Controller
public class ResultSpringMVC {
@RequestMapping("/rsm/t1")
public String test1(a){
/ / forwarding
return "/index.jsp";
}
@RequestMapping("/rsm/t2")
public String test2(a){
Forward / / 2
return "forward:/index.jsp";
}
@RequestMapping("/rsm/t3")
public String test3(a){
/ / redirection
return "redirect:/index.jsp"; }}Copy the code
Forwarding and redirection via SpringMVC annotations (view parser required)
@Controller
public class ResultSpringMVC2 {
@RequestMapping("/rsm2/t1")
public String test1(a){
/ / forwarding
return "test";
}
@RequestMapping("/rsm2/t2")
public String test2(a){
/ / redirection
return "redirect:/index.jsp";
//return "redirect:hello.do"; //hello.do for another request /}}Copy the code
-
The data processing
-
Processing submitted data
-
1. The domain name submitted is the same as the parameter name of the processing method
Submit data: http://localhost:8080/test? name=lyw
Treatment methods:
@RequestMapping("/test")
public String hello(String name){
System.out.println(name);
return "hello";
}
Copy the code
Background output: LYW
-
2. The domain name submitted is inconsistent with the parameter name of the processing method
Submit data: http://localhost:8080/test? username=lyw
Treatment methods:
// @requestParam ("username") : specifies the name of the field submitted by username.
@RequestMapping("/test")
public String hello(@RequestParam("username") String name){
System.out.println(name);
return "hello";
}
Copy the code
Background output: LYW
-
The submitted data is an object
The submitted form field must have the same property name as the object, and the parameters can be used directly by the object
- Entity class
public class User {
private int id;
private String name;
private int age;
/ / structure
//get/set
//tostring()
}
Copy the code
- Submit data: http://localhost:8080/test? name=lyw&id=1&age=20
- Treatment methods:
@RequestMapping("/test")
public String user(User user){
System.out.println(user);
return "hello";
}
Copy the code
User {id=1, name=’lyw’, age=20}
-
Note: if the object is used, the parameter name passed by the front end must be the same as the object name, otherwise null.
-
Data is displayed to the front end
-
1. Through ModelAndView
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
// Returns a model view object
ModelAndView mv = new ModelAndView();
mv.addObject("msg"."ControllerTest1");
mv.setViewName("test");
returnmv; }}Copy the code
-
2. Through ModelMap
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
// Encapsulate the data to be displayed in the view
// req.setattribute ("name",name);
model.addAttribute("name",name);
System.out.println(name);
return "hello";
}
Copy the code
-
3, through the Model
@RequestMapping("/ct2/hello")
public String hello(@RequestParam("username") String name, Model model){
// Encapsulate the data to be displayed in the view
// req.setattribute ("name",name);
model.addAttribute("msg",name);
System.out.println(name);
return "test";
}
Copy the code
- note
Model has only a few methods suitable for storing data, simplifying the operation and understanding of Model objects for beginners;
ModelMap inherits LinkedMap. In addition to implementing some of its own methods, ModelMap also inherits LinkedMap methods and features;
ModelAndView can store data at the same time, can set the returned logical view, control the jump of the display layer.
-
The code problem
SpringMVC gives us a filter that can be configured in web.xml
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/ *</url-pattern>
</filter-mapping>
Copy the code
- Note: In some extreme cases, this filter is not friendly to GET support
Treatment methods:
- Modify tomcat configuration file: Set encoding!
<Connector URIEncoding="utf-8" port="8080" protocol="HTTP / 1.1"
connectionTimeout="20000"
redirectPort="8443" />
Copy the code
- Custom filter (written by the great god found on the Internet)
package com.kuang.filter; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequestWrapper; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Map; Public class GenericEncodingFilter implements Filter {@override public void destroy() { } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletResponse myResponse=(HttpServletResponse) response; myResponse.setContentType("text/html; charset=UTF-8"); HttpServletRequest = (HttpServletRequest) request; HttpServletRequest = (HttpServletRequest) request; Myrequest = new myRequest (HttpServletRequest); chain.doFilter(myrequest, response); } @override public void init(FilterConfig FilterConfig) throws ServletException {}} It's a wrapper class class MyRequest extends HttpServletRequestWrapper {private it request; Private Boolean hasEncode; Public MyRequest(HttpServletRequest Request) {super(request); public MyRequest(HttpServletRequest Request) {super(request); // super must write this.request = request; } @override public Map getParameterMap() {String method = request.getMethod(); If (method equalsIgnoreCase (" post ")) {/ / post request try {/ / processing post gibberish request. SetCharacterEncoding (" utf-8 "); return request.getParameterMap(); } catch (UnsupportedEncodingException e) { e.printStackTrace(); }} else if (method.equalSignorecase ("get")) {// Get request Map<String, String[]> parameterMap = request.getParameterMap(); if (! HasEncode) {// Ensure that the get manual encoding logic is run only once for (String parameterName: parameterMap.keySet()) { String[] values = parameterMap.get(parameterName); if (values ! = null) { for (int i = 0; i < values.length; Values [I] = new String(values[I].getBytes(" ISo-8859-1 "), "utF-8 "); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } } } hasEncode = true; } return parameterMap; } return super.getParameterMap(); } @override public String getParameter(String name) {Map<String, String[]> parameterMap = getParameterMap(); String[] values = parameterMap.get(name); if (values == null) { return null; } return values[0]; @override public String[] getParameterValues(String name) {Map<String, String[]> parameterMap = getParameterMap(); String[] values = parameterMap.get(name); return values; }}Copy the code
In general, SpringMVC’s default garble handling works fine!