作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试学习如何使用Spring MVC和Hibernate构建应用程序。目前,我一直坚持将复选框值插入MySQL数据库。
我的数据库表结构如下:
id name interest
id name interest
1 Steve PHP
2 Steve Java
3 Wuagh C#
4 Wuagh PHP
id name interest
1 Steve PHP, Java
2 Wuagh C#, PHP
<c:url var="action" value="/register" ></c:url>
<form:form action="${action}" modelAttribute="subscriber" method="POST" >
<div>
<label>Name</label>
<form:input path="name"/>
<form:errors path="name" cssClass="error"/>
</div>
<div>
<label>Interests</label>
<form:checkboxes path="interest" items="${records.interests}"/>
</div>
<input type="submit" value="Submit">
</form:form>
package com.spring.org;
@Controller
public class HomeController {
@Autowired
private SubscriberService subService;
@RequestMapping(value="/register", method= RequestMethod.GET)
public ModelAndView RegistrationForm(@ModelAttribute Subscriber subscriber, BindingResult result)
{
HashMap<Integer, String> interest = new HashMap<Integer, String>();
interest.put(1,"Java");
interest.put(2,"PHP");
interest.put(3, "C#");
return new ModelAndView("regForm", "records", interest);
}
@RequestMapping(value="/register", method= RequestMethod.POST)
public ModelAndView RegistrationFormSubmit(@ModelAttribute("subscriber") @Valid Subscriber subscriber, BindingResult result)
{
if (result.hasErrors()) {
return new ModelAndView("regForm");
}
else
{
subService.addSubscriber(subscriber);
return new ModelAndView("redirect:/showList");
}
}
}
@Entity
@Table(name = "PERSON", schema = "java2")
public class Subscriber {
@Id
@Column(name="ID")
@GeneratedValue
private int id;
@NotEmpty(message = "Please enter your Name.")
private String name;
private String[] interest;
public String getName() {return name;}
public void setName(String name) { this.name = name; }
public String[] getInterest() { return interest; }
public void setInterest(String[] interest) { this.interest = interest; }
}
@Service
public class SubscriberServiceImpl implements SubscriberService{
@Autowired
private SubscriberDao subsDao ;
@Override
public void addSubscriber(Subscriber subscriber) {
subsDao.addSubscriber(subscriber);
}
}
@Repository
public class SubscriberDaoImpl implements SubscriberDao {
@Autowired
private SessionFactory sessionFactory ;
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public void addSubscriber(Subscriber subscriber) {
getSessionFactory().openSession().save(subscriber);
}
}
最佳答案
This链接以及documentation也会为您提供帮助。
这是一个数据绑定问题,表单将以字符串形式返回值,而不是最初返回的类型。
关于java - 在Spring MVC中将复选框值插入数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25691255/
我是一名优秀的程序员,十分优秀!