本文是本人在学习网络视屏springMVC的过程中的学习笔记。
为了更便于理解我决定从实际使用的角度解释。
我们在浏览器输入地址
http://localhost:8080/springMVC6/user/data/toUser
界面如下:
此时后台是跳转到下面class的toUser方法的
package com.tgb.web.controller.annotation; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/user/data") public class DataController { @RequestMapping(value="/addUser") public String addUser(String userName,String age,HttpServletRequest request){ request.setAttribute("userName", userName); request.setAttribute("age", age); String result ="this is addUser------"; return "userManager"; } @RequestMapping(value="/delUser") public String delUser(){ String result ="this is delUser------"; return ""; } @RequestMapping(value="/toUser") public String toUser(){ return "addUser"; } }
addUser.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <script type="text/javascript" src="../js/jquery-1.7.1.min.js"></script> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> <script type="text/javascript"> function addUser(){ var form = document.forms[0]; form.action = "/springMVC6/user/data/addUser"; form.method="post"; form.submit(); } </script> </head> <body> <h>添加用户</h> <form action=""> 姓名:<input type="text" name="userName"/> 年龄:<input type="text" name="age"/> <input type="button" value="添加" onclick="addUser()"> </form> </body> </html>
当在界面输入“斯蒂芬”,点击“添加”,会调用/springMVC6/user/data/addUser,而此路径对应的是DataController的addUser方法。此方法通过request获取参数。
特别注意:
再输入中文的时候,后台接收回出现乱码。
这个时候需要在web.xml中配置字符过滤器
<!-- 强制转码 防止乱码出现 start --> <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> <!-- 强制转码 防止乱码出现 end -->
<Connector URIEncoding="UTF-8" port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" />
原文:http://blog.csdn.net/junshuaizhang/article/details/26391889