How do you query a database from JSP Form Data? - java

I am in need of assistance. I am trying to write a basic form that populates a drop-down list and based on what you select, it queries the database. However, I cannot get it to do it, It just receives all the queries. I am at a loss so if you have any helpful advice or helpful links, that'd be great. I really need to learn Spring MVC, and Hibernate combined. thanks!
HomeController Code: (This controller populates the list)
/**
* Handles requests for the application home page.
*/
#Controller
public class SearchController {
#Autowired
FilmBo filmBo;
/**
* Simply selects the home view to render by returning its name.
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String home(Locale locale, ModelMap model) {
Selection selection = new Selection();
model.addAttribute("selection", selection);
return "search";
}
#ModelAttribute("categoryList")
public List<String> populateList(){
List<String> categoryList = filmBo.searchByCategory("");
return categoryList;
}
}
Here is the MainController that the form upon submit gets sent to:
public class FilmController {
private static final Logger logger = LoggerFactory.getLogger(SearchController.class);
#Autowired
FilmBo filmBo;
#RequestMapping(value = "/films", method = RequestMethod.GET)
public String home(Locale locale, Model model, #RequestParam(value="title",required=false) String title,
#RequestParam(value="category",required=false) String category) {
logger.info("Welcome home! The client locale is {}.", locale);
List<Film> filmList = filmBo.searchByTitle(title);
logger.info("filmList: " + filmList);
model.addAttribute("filmList", filmList);
List<String> filmCategory = filmBo.searchByCategory(category);
logger.info("filmCategory: " + filmCategory);
model.addAttribute("filmCategory",filmCategory);
return "films";
}
}
Here is my jsp page:
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%# page session="false"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div class="form">
<form:form action="${pageContext.request.contextPath}/films"
method="GET" commandName="selection">
Film Title<input type="text" name="title">
<br>
Select a Film Category:<br>
<form:select path="selection">
<form:option value="NONE" label="--- Select ---" />
<form:options name="category" items="${categoryList}" />
</form:select>
<button name="submit" type="submit">Submit Name</button>
</form:form>
</div>
</body>
</html>

Related

Is it possible to output a drop-down list with values from DB in an easier way?

This way is not greatest. I'm looking for a better way. Is it possible to do without Lists?
My PageController:
public class CreateUserPageController {
#Autowired
private UserServiceImpl userServiceImpl;
#RequestMapping(value = "/create-user", method = RequestMethod.GET)
public ModelAndView showForm() {
ModelAndView model = new ModelAndView("admin/create-user");
model.addObject("user", new User());
UserRoleDTO[] roles = UserRoleDTO.values();
List<String> roleNames = new ArrayList<>();
for (UserRoleDTO role : roles) {
roleNames.add(role.getName());
}
model.addObject("roleNames", roleNames);
return model;
}
#RequestMapping(value = "/create-user", method = RequestMethod.POST)
public ModelAndView submitForm(#ModelAttribute("user") User user) {
userServiceImpl.create(user);
return showForm();
}
}
My JSP:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>Create test</title>
</head>
<body>
<h1>Create Test</h1>
<form:form method="POST" action="/create-test" modelAttribute="topicTestDTO">
<form:input path="topic.name" type="text" list="topic_list" placeholder="choose or create topic"/>
<datalist id="topic_list">
<c:forEach items="${topicList}" var="topic">
<option>${topic}</option>
</c:forEach>
</datalist>
<br>
<form:input path="test.name" type="text" placeholder="create test name"/>
<input type="submit">
</form:form>
</body>
</html>
Thanks for help.
If you need more information, tell me which one and I'll complete the code.
Here the problem is for every request it goes to Database to retrieve the data, even data is not changing also it reduces the performance of application.
By using local cache we can achieve performance, so while application loading it self data will be queried from database and store it in cache,then we can reuse the data from cache.

Doesn't switch to another .jsp when I click submit. Spring mvc

My controller. When I open the browser, the start page starts.jsp and create model User, which haves one field(String name) and set,get method. In start.jsp haves field of text and submit "LOGIN".
#Controller
public class HomeController {
#RequestMapping(value = "/", method = RequestMethod.GET)
public ModelAndView start() {
return new ModelAndView("start", "user", new User());
}
#RequestMapping(value = "/input", method = RequestMethod.POST)
public ModelAndView input(#ModelAttribute("user") User user) {
return new ModelAndView("input", "userName", user);
}
}
My start page. Have text field and submit.
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
<title>start</title>
</head>
<body>
<h1>TEST</h1>
<form:form method="post" commandName="user" action="input">
<input type="text" name="name"><br>
<input type="submit" value="LOGIN">
</form:form>
</body>
</html>
My problem: I open localhost:8080/webapp and input name. In the moment there is creating examplar of model User. I push "LOGIN" and I turn in localhost:8080/input, where "input.jsp" is two page, which output "Hello world, {name}". But if I replace action="input" in start.jsp with action="webapp\input" then everything is good. But I think it's bad idea.
I don't see any issues with your code. I tried to set this example and works fine for below configuration.
webapp-servlet.xml:
<context:component-scan base-package = "com.test" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
JSP locations :
\WEB-INF\jsp\input.jsp
\WEB-INF\jsp\start.jsp
sample input.jsp:
<%# page import="com.test.*" %>
<html>
<head>
<title>start</title>
</head>
<body>
<h1>TEST</h1>
<%
User user = (User)request.getAttribute("userName");
%>
Hello - <%=user.getName() %>
</body>
</html>
No changes required in start.jsp and HomeController

How can I update changed data on button?

I want to edit data of the user by inputting new value in the textbox such as his first name and show these changes in his profile.
I tried to use Ajax but I don't understand what the url should be in there.
That's my jsp file with edit form and Ajax script:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<script type="text/javascript">
$("edit").click(function() {
var firstName = $(request.getParameter("firstname")).val();
$.ajax({
url: '',
type: 'POST',
data: {
firstName: firstName
}
});
});
</script>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>${title}</title>
</head>
<body>
<h4>To edit your information fill the fields, please.</h4>
<form name='f' action="${pageContext.request.contextPath}/j_spring_security_check" method='POST'>
<table>
<tr>
<td>First Name:</td>
<td><input type='text' name='firstname' id='firstname' value='${firstname}'></td>
</tr>
<tr>
<td><input name="edit" type="submit" value="Submit" /></td>
</tr>
</table>
</form>
I have update and get methods for the first name in one of the classes:
public class UserInfoDAOImpl extends JdbcDaoSupport implements UserInfoDAO {
#Autowired
public UserInfoDAOImpl(DataSource dataSource) {
this.setDataSource(dataSource);
}
//.....other methods
#Override
public void editFirstName(String userName, String fName){
String sql = "update Users set FirstName = ? where Username = ?";
Object[] params = new Object[] {fName, userName};
this.getJdbcTemplate().update(sql, params);
}
#Override
public String getFirstName(String userName) {
// TODO Auto-generated method stub
String sql = "select u.FirstName from Users u where u.Username = ? ";
Object[] params = new Object[] { userName };
String firstName = (String)getJdbcTemplate().queryForObject(sql, params, String.class);
return firstName;
}
}
So I don't really get to use these already written methods to update the data and get these changes in user profile.
I am new to Ajax so I'm glad to get any help.
You are wrong on your JSP, the j_spring_security_check is default URL Spring Login.
For updating firstname you must do #RequestMapping #ResponseBody on your Controller de handle the Ajax Request.

Spring MVC form submission, populate on the same page

I am trying to create a simple function using a post method. What I want is whatever is entered in the form and submitted- it should appear on the same page below the form. However the text just disappears once I click "submit". Here is my code
Contoller
#Controller
public class SearchController {
#RequestMapping(value = "/search", method = RequestMethod.GET)
public String goToSearch(Model model) {
model.addAttribute("item", new Item());
return "itemsearch";
}
#RequestMapping(value = "/search", method = RequestMethod.POST)
public String search(Item item, Model model, #RequestParam String itemId) throws IOException{
model.addAttribute("item", new Item());
return "itemsearch";
}
}
Jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="s" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<!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>
<h2>Search for an item</h2>
<sf:form action="search" method="POST" modelAttribute="item">
<label>Please enter the item Id number:<sf:input type="text" name="itemId" id="itemId" path="itemId" /></label><br/>
<input type="submit" value="Submit" path="submit" />
<br> You are trying to search for Id Number: <b><h3>${item.itemId}<h3></h3></b>
</sf:form>
Item class
public class Item {
private String itemId;
private List<String> itemDetails;
public List<String> getItemDetails() {
return itemDetails;
}
public void setItemDetails(List<String> itemDetails) {
this.itemDetails = itemDetails;
}
public String getItemId() {
return itemId;
}
public void setItemId(String itemId) {
this.itemId = itemId;
}
}
Many thanks
I think you need a basic understanding how Spring MVC works.
Have a look at this picture:
You see an incoming request (your POST request) from the client which is redirected to the desired controller. The controller (your SearchController) makes some business magic and returns the model to the front controller. The model is by default empty. You can add objects that should be rendered via model.addAttribute("someId", someObject);
The passed model is now handled by the view template (itemsearch) which connects the template and the model to a (static) response that is passed to the client.
And there is the problem. You are passing in your controller new Item() to the model. It is an empty object which has no values (and no id which you want to render after the form submition). Therefore on your JSP page could be nothing displayed. Just pass the found item or the item from your request to the model.

Extrating data from jsp form to controller and saving them to database

Hello I am trying to save data from a form to database however I have no idea how to continue now. I have this following code.
I tried using the request.getParameter("id") in the controller which gave me an compiler error.
So how do I get the data from the jsp form to the controller and then save them to the MySQL database ?
jsp file
<%# taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="ProductController" method="post">
<p>Enter product name :</p> <input id="productName" type="text" name="username"> <BR>
<p>Enter product serial number :</p> <input id="serialNumber" type="password" name="password"> <BR>
<input type="submit" placeholder="Submit" />
</form>
</body>
</html>
The controller
#Controller
#RequestMapping("/product")
public class ProductController {
#Autowired
private ProductService productService;
#RequestMapping("/list")
public ModelAndView list() {
ModelAndView modelAndView = new ModelAndView("product/list");
System.out.println("Count:" + productService.getProducts().size());
modelAndView.addObject("test", "mytest");
modelAndView.addObject("count", productService.getProducts().size());
modelAndView.addObject("products", productService.getProducts());
return modelAndView;
}
}
and product DAO
#Override
public void saveProduct(Product product) {
//persist(product);
Session session = this.sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.persist(product);
tx.commit();
session.close();
}
you have to use name attribute of html element to get value, like request.getParameter("username");

Categories

Resources