我正在使用 Eclipse、Spring MVC、Maven 和 Tomcat。此 index.jsp
在 Web 浏览器中的显示完全如下所示。它无法正确渲染。
知道出了什么问题吗?
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Index</h1>
</body>
</html>
@Controller
public class HelloController {
@RequestMapping("/greeting")
public String sayHello() {
System.out.println("Greeting");
return "hello";
}
@RequestMapping("/")
public String index() {
System.out.println("Index page");
return "index";
}
}
最佳答案
Controller 有一个 GET 和一个 POST RequestMethod。但是,快速浏览一下,您需要将 @RequestMapping("/greeting") 更改为 @RequestMapping(value = "/greeting") 只是为了初学者。默认情况下,您的 jsp 文件应位于/src/main/webapp/WEB-INF/views (Spring MVC Starter Project)
当您返回一个字符串时 - Spring MVC 将查找具有该 .jsp 的 jsp。所以在这个例子中你只想有greeting.jsp
@Controller
public class GreetingController {
/**
* GET
*/
@RequestMapping(value = "/greeting", method = RequestMethod.GET)
public String handleRequest() {
// This will be used when you GET the URL
return "greeting";
}
/**
* POST
*/
@RequestMapping(value = "/greeting", method = RequestMethod.POST)
public String processSubmit(){
// This will be used when you POST to the URL
//TODO Do something here and it will put you right back in your page
return "greeting";
}
}
如果您还有其他问题,请继续评论。另请检查我的帐户中的其他示例 Neither BindingResult nor plain target object for bean name available as request attr
希望这有帮助。祝你好运!
请注意,Spring 有更多的 RequestMethod,但 GET 和 POST 是最常用且最容易理解的。
关于java - JSP 在 Web 浏览器中输出纯文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29088439/