1.项目整体结构图如下
2.服务层代码如下
package org.app.demo.spring.service;
/**
*
* @author wujinsong
*
*/
public interface HelloWorldService {
public String getNewName(String userName);
}
package org.app.demo.spring.service.impl;
import org.app.demo.spring.service.HelloWorldService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Service
public class HelloWorldServiceImpl implements HelloWorldService {
@Override
@Transactional
public String getNewName(String userName) {
return "Hello Spring!" + userName;
}
}
3.控制层代码
package org.app.demo.spring.controller;
import javax.servlet.http.HttpServletRequest;
import org.app.demo.spring.service.HelloWorldService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
@RequestMapping("/helloworld.do")
public class HelloWorldController {
@Autowired
private HelloWorldService helloWorldService;
@RequestMapping
public String getNewName(@RequestParam("userName") String userName,
HttpServletRequest request) {
String newUserName = helloWorldService.getNewName(userName);
request.setAttribute("newUserName", newUserName);
return "helloworld";
}
}
4.视图层代码
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="helloworld.do" method="post">
请输入姓名:<input type="text" name="userName"> <input type="submit"
value="提交"> <br />
</form>
</body>
</html>
helloworld.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=request.getAttribute("newUserName") %>
</body>
</html>