这篇文章的代码基于上一篇文章《springmvc的helloworld(1)》,讲如何在springmvc如何接收页面参数。
第一步:
index.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="helloworld.do">
userName:<input type="text" name="userName"><br>
<input type="submit" value="提交">
</form>
<form action="helloworldPost.do" method="post">
userName:<input type="text" name="userName"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
第二步:
修改HellowolrdAction:
package com.action;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class HelloworldAction {
@RequestMapping(value = "/helloworld.do")
public String hellowolrd(Model model,@RequestParam("userName") String userName ) {
model.addAttribute("userName", userName);
return "result";
}
@RequestMapping(value = "/helloworld.do", method = RequestMethod.POST)
public String hellowolrdPost(Model model,@RequestParam("userName") String userName ) {
model.addAttribute("userName", userName);
return "result";
}
}
第三步:
传递阐述会出现中文乱码问题
1,get请求。在tomcat中加上URIEncoding="utf-8"。如:
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" URIEncoding="utf-8"/>
2,post请求,在web.xml加上Character Encoding filter
<!-- Character Encoding filter -->
<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>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
本文介绍如何在SpringMVC中通过GET和POST方法接收页面参数,并解决中文乱码问题。首先展示了index.jsp页面的代码,包括两个提交按钮分别对应GET和POST请求。接着详细解释了HelloworldAction类中处理请求的方法,以及如何使用@RequestParam注解来获取参数。最后给出了针对GET和POST请求的中文乱码解决方案。
166

被折叠的 条评论
为什么被折叠?



