上一篇我们看来hello入门接着我们添加jdbc链接
配置mysql driver
在applicationContext中配置mysql驱动(可以采用另一种方式将配置单独出来写在文件中)
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://127.0.0.1:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="12345678"/>
</bean>
<!-- 配置事物管理 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
Dao层定义操作
@Repository("userDao")
public class UserDao implements IUserDao {
JdbcTemplate jdbcTemplate;
@Resource(name = "dataSource")
public void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
@Override
public int addUser(User user) {
int result = this.jdbcTemplate.update("insert into user(name, age) values(?,?)",
new Object[]{
user.getName(),
user.getAge()});
return result;
}
@Override
public List<User> allUser() {
List<User> allUserResult = this.jdbcTemplate.query("select *from user", new RowMapper<User>() {
@Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
String name = resultSet.getString("name");
int id = resultSet.getInt("id");
int age = resultSet.getInt("age");
return new User(name, age, id);
}
});
return allUserResult;
}
}
依次配置完成Server model,然后我们写出Controller
Action
@Controller
@Scope("prototype")
@RequestMapping("/u")
public class UserController {
IUserService userService;
@Resource(name = "userService")
public void setUserService(UserService userService) {
this.userService = userService;
}
@RequestMapping("/addUser")
public String user(Model model) {
User user = new User("jackLee", 30, 1);
model.addAttribute("user", user);
int addUserResult = this.userService.addUser(user);
model.addAttribute("msg", "插入结果:" + addUserResult);
return "redirect:/u/allUser";
}
@RequestMapping("/allUser")
public String allUser(Model model) {
List<User> allUserResult = userService.allUser();
model.addAttribute("allUsers", allUserResult);
return "allUser";
}
@RequestMapping("/json")
@ResponseBody
public String json(Model model) {
List<User> allUserResult = userService.allUser();
model.addAttribute("allUsers", allUserResult);
return JSON.toJSONString(model);
}
}
数据库预览

user表

到此我们就可以看出通过浏览器栏查看效果
http://localhost:8080/smvc_war_exploded/u/json

http://localhost:8080/smvc_war_exploded/u/allUser

【敲黑板】
网友评论