前言:表单标签库的简单运用
代码:
main.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%@ taglib prefix="fm" uri="http://www.springframework.org/tags/form" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
My JSP 'main.jsp' starting page
姓名:
编号:
年龄:
爱好:
性别: 男
女
学院:
信息与控制学院
生命学院
经管学院
学前教育学院
model:
package model;
import java.util.List;
public class User {
private String name;
private int age;
private String number;
private List hobbys;
private String sex;
private int dept;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public List getHobbys() {
return hobbys;
}
public void setHobbys(List hobbys) {
this.hobbys = hobbys;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public int getDept() {
return dept;
}
public void setDept(int dept) {
this.dept = dept;
}
}
HelloController:
package controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping(value="/hello")
@SessionAttributes(value="user")
public class HelloController {
//形参方式
@RequestMapping(value="/register",method=RequestMethod.POST)
public String register( String username, String pwd, String age,Model m){
if(username.equals("1931030119")){
//1创建一个对象:绑定数据用
User user = new User();
//2设置用户名
user.setName("lisi");
//3设置年龄
user.setAge(18);
//4设置编号
user.setNumber("A001");
String a[]={"运动","看书","游戏"};
List list = new ArrayList();
for(int i =0;i<3;i++){
list.add(a[i]);
}
user.setHobbys(list);
user.setSex("男");
user.setDept(4);
//设置user值,返回给结果页面
m.addAttribute("user",user);
//返回结果页面
return "main";
}else{
return "index";
}
}
}
常见问题:
1.
乱码问题可以在web.xml设置过滤器解决,代码如下
EncodingFilter org.springframework.web.filter.CharacterEncodingFilter encoding UTF-8 forceEncoding true EncodingFilter /*
该问题可能因为其他标签未包含在fm:form中导致



